babylon.max.js 5.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294
  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. /**
  1269. * Gather the list of keyboard event types as constants.
  1270. */
  1271. var KeyboardEventTypes = /** @class */ (function () {
  1272. function KeyboardEventTypes() {
  1273. }
  1274. /**
  1275. * The keydown event is fired when a key becomes active (pressed).
  1276. */
  1277. KeyboardEventTypes.KEYDOWN = 0x01;
  1278. /**
  1279. * The keyup event is fired when a key has been released.
  1280. */
  1281. KeyboardEventTypes.KEYUP = 0x02;
  1282. return KeyboardEventTypes;
  1283. }());
  1284. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1285. /**
  1286. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1287. */
  1288. var KeyboardInfo = /** @class */ (function () {
  1289. /**
  1290. * Instantiates a new keyboard info.
  1291. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1292. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1293. * @param event Defines the related dom event
  1294. */
  1295. function KeyboardInfo(
  1296. /**
  1297. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1298. */
  1299. type,
  1300. /**
  1301. * Defines the related dom event
  1302. */
  1303. event) {
  1304. this.type = type;
  1305. this.event = event;
  1306. }
  1307. return KeyboardInfo;
  1308. }());
  1309. BABYLON.KeyboardInfo = KeyboardInfo;
  1310. /**
  1311. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1312. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1313. */
  1314. var KeyboardInfoPre = /** @class */ (function (_super) {
  1315. __extends(KeyboardInfoPre, _super);
  1316. /**
  1317. * Instantiates a new keyboard pre info.
  1318. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1319. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1320. * @param event Defines the related dom event
  1321. */
  1322. function KeyboardInfoPre(
  1323. /**
  1324. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1325. */
  1326. type,
  1327. /**
  1328. * Defines the related dom event
  1329. */
  1330. event) {
  1331. var _this = _super.call(this, type, event) || this;
  1332. _this.type = type;
  1333. _this.event = event;
  1334. _this.skipOnPointerObservable = false;
  1335. return _this;
  1336. }
  1337. return KeyboardInfoPre;
  1338. }(KeyboardInfo));
  1339. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1340. })(BABYLON || (BABYLON = {}));
  1341. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1342. var BABYLON;
  1343. (function (BABYLON) {
  1344. /**
  1345. * Gather the list of pointer event types as constants.
  1346. */
  1347. var PointerEventTypes = /** @class */ (function () {
  1348. function PointerEventTypes() {
  1349. }
  1350. /**
  1351. * The pointerdown event is fired when a pointer becomes active. For mouse, it is fired when the device transitions from no buttons depressed to at least one button depressed. For touch, it is fired when physical contact is made with the digitizer. For pen, it is fired when the stylus makes physical contact with the digitizer.
  1352. */
  1353. PointerEventTypes.POINTERDOWN = 0x01;
  1354. /**
  1355. * The pointerup event is fired when a pointer is no longer active.
  1356. */
  1357. PointerEventTypes.POINTERUP = 0x02;
  1358. /**
  1359. * The pointermove event is fired when a pointer changes coordinates.
  1360. */
  1361. PointerEventTypes.POINTERMOVE = 0x04;
  1362. /**
  1363. * The pointerwheel event is fired when a mouse wheel has been rotated.
  1364. */
  1365. PointerEventTypes.POINTERWHEEL = 0x08;
  1366. /**
  1367. * The pointerpick event is fired when a mesh or sprite has been picked by the pointer.
  1368. */
  1369. PointerEventTypes.POINTERPICK = 0x10;
  1370. /**
  1371. * The pointertap event is fired when a the object has been touched and released without drag.
  1372. */
  1373. PointerEventTypes.POINTERTAP = 0x20;
  1374. /**
  1375. * The pointertap event is fired when a the object has been touched and released twice without drag.
  1376. */
  1377. PointerEventTypes.POINTERDOUBLETAP = 0x40;
  1378. return PointerEventTypes;
  1379. }());
  1380. BABYLON.PointerEventTypes = PointerEventTypes;
  1381. /**
  1382. * Base class of pointer info types.
  1383. */
  1384. var PointerInfoBase = /** @class */ (function () {
  1385. /**
  1386. * Instantiates the base class of pointers info.
  1387. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1388. * @param event Defines the related dom event
  1389. */
  1390. function PointerInfoBase(
  1391. /**
  1392. * Defines the type of event (BABYLON.PointerEventTypes)
  1393. */
  1394. type,
  1395. /**
  1396. * Defines the related dom event
  1397. */
  1398. event) {
  1399. this.type = type;
  1400. this.event = event;
  1401. }
  1402. return PointerInfoBase;
  1403. }());
  1404. BABYLON.PointerInfoBase = PointerInfoBase;
  1405. /**
  1406. * This class is used to store pointer related info for the onPrePointerObservable event.
  1407. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1408. */
  1409. var PointerInfoPre = /** @class */ (function (_super) {
  1410. __extends(PointerInfoPre, _super);
  1411. /**
  1412. * Instantiates a PointerInfoPre to store pointer related info to the onPrePointerObservable event.
  1413. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1414. * @param event Defines the related dom event
  1415. * @param localX Defines the local x coordinates of the pointer when the event occured
  1416. * @param localY Defines the local y coordinates of the pointer when the event occured
  1417. */
  1418. function PointerInfoPre(type, event, localX, localY) {
  1419. var _this = _super.call(this, type, event) || this;
  1420. /**
  1421. * Ray from a pointer if availible (eg. 6dof controller)
  1422. */
  1423. _this.ray = null;
  1424. _this.skipOnPointerObservable = false;
  1425. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1426. return _this;
  1427. }
  1428. return PointerInfoPre;
  1429. }(PointerInfoBase));
  1430. BABYLON.PointerInfoPre = PointerInfoPre;
  1431. /**
  1432. * This type contains all the data related to a pointer event in Babylon.js.
  1433. * 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.
  1434. */
  1435. var PointerInfo = /** @class */ (function (_super) {
  1436. __extends(PointerInfo, _super);
  1437. /**
  1438. * Instantiates a PointerInfo to store pointer related info to the onPointerObservable event.
  1439. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1440. * @param event Defines the related dom event
  1441. * @param pickInfo Defines the picking info associated to the info (if any)\
  1442. */
  1443. function PointerInfo(type, event,
  1444. /**
  1445. * Defines the picking info associated to the info (if any)\
  1446. */
  1447. pickInfo) {
  1448. var _this = _super.call(this, type, event) || this;
  1449. _this.pickInfo = pickInfo;
  1450. return _this;
  1451. }
  1452. return PointerInfo;
  1453. }(PointerInfoBase));
  1454. BABYLON.PointerInfo = PointerInfo;
  1455. })(BABYLON || (BABYLON = {}));
  1456. //# sourceMappingURL=babylon.pointerEvents.js.map
  1457. var BABYLON;
  1458. (function (BABYLON) {
  1459. /**
  1460. * Constant used to convert a value to gamma space
  1461. * @ignorenaming
  1462. */
  1463. BABYLON.ToGammaSpace = 1 / 2.2;
  1464. /**
  1465. * Constant used to convert a value to linear space
  1466. * @ignorenaming
  1467. */
  1468. BABYLON.ToLinearSpace = 2.2;
  1469. /**
  1470. * Constant used to define the minimal number value in Babylon.js
  1471. * @ignorenaming
  1472. */
  1473. BABYLON.Epsilon = 0.001;
  1474. /**
  1475. * Class used to hold a RBG color
  1476. */
  1477. var Color3 = /** @class */ (function () {
  1478. /**
  1479. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1480. * @param r defines the red component (between 0 and 1, default is 0)
  1481. * @param g defines the green component (between 0 and 1, default is 0)
  1482. * @param b defines the blue component (between 0 and 1, default is 0)
  1483. */
  1484. function Color3(
  1485. /**
  1486. * Defines the red component (between 0 and 1, default is 0)
  1487. */
  1488. r,
  1489. /**
  1490. * Defines the green component (between 0 and 1, default is 0)
  1491. */
  1492. g,
  1493. /**
  1494. * Defines the blue component (between 0 and 1, default is 0)
  1495. */
  1496. b) {
  1497. if (r === void 0) { r = 0; }
  1498. if (g === void 0) { g = 0; }
  1499. if (b === void 0) { b = 0; }
  1500. this.r = r;
  1501. this.g = g;
  1502. this.b = b;
  1503. }
  1504. /**
  1505. * Creates a string with the Color3 current values
  1506. * @returns the string representation of the Color3 object
  1507. */
  1508. Color3.prototype.toString = function () {
  1509. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1510. };
  1511. /**
  1512. * Returns the string "Color3"
  1513. * @returns "Color3"
  1514. */
  1515. Color3.prototype.getClassName = function () {
  1516. return "Color3";
  1517. };
  1518. /**
  1519. * Compute the Color3 hash code
  1520. * @returns an unique number that can be used to hash Color3 objects
  1521. */
  1522. Color3.prototype.getHashCode = function () {
  1523. var hash = this.r || 0;
  1524. hash = (hash * 397) ^ (this.g || 0);
  1525. hash = (hash * 397) ^ (this.b || 0);
  1526. return hash;
  1527. };
  1528. // Operators
  1529. /**
  1530. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1531. * @param array defines the array where to store the r,g,b components
  1532. * @param index defines an optional index in the target array to define where to start storing values
  1533. * @returns the current Color3 object
  1534. */
  1535. Color3.prototype.toArray = function (array, index) {
  1536. if (index === undefined) {
  1537. index = 0;
  1538. }
  1539. array[index] = this.r;
  1540. array[index + 1] = this.g;
  1541. array[index + 2] = this.b;
  1542. return this;
  1543. };
  1544. /**
  1545. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1546. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1547. * @returns a new {BABYLON.Color4} object
  1548. */
  1549. Color3.prototype.toColor4 = function (alpha) {
  1550. if (alpha === void 0) { alpha = 1; }
  1551. return new Color4(this.r, this.g, this.b, alpha);
  1552. };
  1553. /**
  1554. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1555. * @returns the new array
  1556. */
  1557. Color3.prototype.asArray = function () {
  1558. var result = new Array();
  1559. this.toArray(result, 0);
  1560. return result;
  1561. };
  1562. /**
  1563. * Returns the luminance value
  1564. * @returns a float value
  1565. */
  1566. Color3.prototype.toLuminance = function () {
  1567. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1568. };
  1569. /**
  1570. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1571. * @param otherColor defines the second operand
  1572. * @returns the new Color3 object
  1573. */
  1574. Color3.prototype.multiply = function (otherColor) {
  1575. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1576. };
  1577. /**
  1578. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1579. * @param otherColor defines the second operand
  1580. * @param result defines the Color3 object where to store the result
  1581. * @returns the current Color3
  1582. */
  1583. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1584. result.r = this.r * otherColor.r;
  1585. result.g = this.g * otherColor.g;
  1586. result.b = this.b * otherColor.b;
  1587. return this;
  1588. };
  1589. /**
  1590. * Determines equality between Color3 objects
  1591. * @param otherColor defines the second operand
  1592. * @returns true if the rgb values are equal to the given ones
  1593. */
  1594. Color3.prototype.equals = function (otherColor) {
  1595. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1596. };
  1597. /**
  1598. * Determines equality between the current Color3 object and a set of r,b,g values
  1599. * @param r defines the red component to check
  1600. * @param g defines the green component to check
  1601. * @param b defines the blue component to check
  1602. * @returns true if the rgb values are equal to the given ones
  1603. */
  1604. Color3.prototype.equalsFloats = function (r, g, b) {
  1605. return this.r === r && this.g === g && this.b === b;
  1606. };
  1607. /**
  1608. * Multiplies in place each rgb value by scale
  1609. * @param scale defines the scaling factor
  1610. * @returns the updated Color3
  1611. */
  1612. Color3.prototype.scale = function (scale) {
  1613. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1614. };
  1615. /**
  1616. * Multiplies the rgb values by scale and stores the result into "result"
  1617. * @param scale defines the scaling factor
  1618. * @param result defines the Color3 object where to store the result
  1619. * @returns the unmodified current Color3
  1620. */
  1621. Color3.prototype.scaleToRef = function (scale, result) {
  1622. result.r = this.r * scale;
  1623. result.g = this.g * scale;
  1624. result.b = this.b * scale;
  1625. return this;
  1626. };
  1627. /**
  1628. * Scale the current Color3 values by a factor and add the result to a given Color3
  1629. * @param scale defines the scale factor
  1630. * @param result defines color to store the result into
  1631. * @returns the unmodified current Color3
  1632. */
  1633. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1634. result.r += this.r * scale;
  1635. result.g += this.g * scale;
  1636. result.b += this.b * scale;
  1637. return this;
  1638. };
  1639. /**
  1640. * Clamps the rgb values by the min and max values and stores the result into "result"
  1641. * @param min defines minimum clamping value (default is 0)
  1642. * @param max defines maximum clamping value (default is 1)
  1643. * @param result defines color to store the result into
  1644. * @returns the original Color3
  1645. */
  1646. Color3.prototype.clampToRef = function (min, max, result) {
  1647. if (min === void 0) { min = 0; }
  1648. if (max === void 0) { max = 1; }
  1649. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1650. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1651. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1652. return this;
  1653. };
  1654. /**
  1655. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1656. * @param otherColor defines the second operand
  1657. * @returns the new Color3
  1658. */
  1659. Color3.prototype.add = function (otherColor) {
  1660. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1661. };
  1662. /**
  1663. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1664. * @param otherColor defines the second operand
  1665. * @param result defines Color3 object to store the result into
  1666. * @returns the unmodified current Color3
  1667. */
  1668. Color3.prototype.addToRef = function (otherColor, result) {
  1669. result.r = this.r + otherColor.r;
  1670. result.g = this.g + otherColor.g;
  1671. result.b = this.b + otherColor.b;
  1672. return this;
  1673. };
  1674. /**
  1675. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1676. * @param otherColor defines the second operand
  1677. * @returns the new Color3
  1678. */
  1679. Color3.prototype.subtract = function (otherColor) {
  1680. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1681. };
  1682. /**
  1683. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1684. * @param otherColor defines the second operand
  1685. * @param result defines Color3 object to store the result into
  1686. * @returns the unmodified current Color3
  1687. */
  1688. Color3.prototype.subtractToRef = function (otherColor, result) {
  1689. result.r = this.r - otherColor.r;
  1690. result.g = this.g - otherColor.g;
  1691. result.b = this.b - otherColor.b;
  1692. return this;
  1693. };
  1694. /**
  1695. * Copy the current object
  1696. * @returns a new Color3 copied the current one
  1697. */
  1698. Color3.prototype.clone = function () {
  1699. return new Color3(this.r, this.g, this.b);
  1700. };
  1701. /**
  1702. * Copies the rgb values from the source in the current Color3
  1703. * @param source defines the source Color3 object
  1704. * @returns the updated Color3 object
  1705. */
  1706. Color3.prototype.copyFrom = function (source) {
  1707. this.r = source.r;
  1708. this.g = source.g;
  1709. this.b = source.b;
  1710. return this;
  1711. };
  1712. /**
  1713. * Updates the Color3 rgb values from the given floats
  1714. * @param r defines the red component to read from
  1715. * @param g defines the green component to read from
  1716. * @param b defines the blue component to read from
  1717. * @returns the current Color3 object
  1718. */
  1719. Color3.prototype.copyFromFloats = function (r, g, b) {
  1720. this.r = r;
  1721. this.g = g;
  1722. this.b = b;
  1723. return this;
  1724. };
  1725. /**
  1726. * Updates the Color3 rgb values from the given floats
  1727. * @param r defines the red component to read from
  1728. * @param g defines the green component to read from
  1729. * @param b defines the blue component to read from
  1730. * @returns the current Color3 object
  1731. */
  1732. Color3.prototype.set = function (r, g, b) {
  1733. return this.copyFromFloats(r, g, b);
  1734. };
  1735. /**
  1736. * Compute the Color3 hexadecimal code as a string
  1737. * @returns a string containing the hexadecimal representation of the Color3 object
  1738. */
  1739. Color3.prototype.toHexString = function () {
  1740. var intR = (this.r * 255) | 0;
  1741. var intG = (this.g * 255) | 0;
  1742. var intB = (this.b * 255) | 0;
  1743. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1744. };
  1745. /**
  1746. * Computes a new Color3 converted from the current one to linear space
  1747. * @returns a new Color3 object
  1748. */
  1749. Color3.prototype.toLinearSpace = function () {
  1750. var convertedColor = new Color3();
  1751. this.toLinearSpaceToRef(convertedColor);
  1752. return convertedColor;
  1753. };
  1754. /**
  1755. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1756. * @param convertedColor defines the Color3 object where to store the linear space version
  1757. * @returns the unmodified Color3
  1758. */
  1759. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1760. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1761. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1762. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1763. return this;
  1764. };
  1765. /**
  1766. * Computes a new Color3 converted from the current one to gamma space
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.prototype.toGammaSpace = function () {
  1770. var convertedColor = new Color3();
  1771. this.toGammaSpaceToRef(convertedColor);
  1772. return convertedColor;
  1773. };
  1774. /**
  1775. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1776. * @param convertedColor defines the Color3 object where to store the gamma space version
  1777. * @returns the unmodified Color3
  1778. */
  1779. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1780. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1781. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1782. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1783. return this;
  1784. };
  1785. // Statics
  1786. /**
  1787. * Creates a new Color3 from the string containing valid hexadecimal values
  1788. * @param hex defines a string containing valid hexadecimal values
  1789. * @returns a new Color3 object
  1790. */
  1791. Color3.FromHexString = function (hex) {
  1792. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1793. return new Color3(0, 0, 0);
  1794. }
  1795. var r = parseInt(hex.substring(1, 3), 16);
  1796. var g = parseInt(hex.substring(3, 5), 16);
  1797. var b = parseInt(hex.substring(5, 7), 16);
  1798. return Color3.FromInts(r, g, b);
  1799. };
  1800. /**
  1801. * Creates a new Vector3 from the starting index of the given array
  1802. * @param array defines the source array
  1803. * @param offset defines an offset in the source array
  1804. * @returns a new Color3 object
  1805. */
  1806. Color3.FromArray = function (array, offset) {
  1807. if (offset === void 0) { offset = 0; }
  1808. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1809. };
  1810. /**
  1811. * Creates a new Color3 from integer values (< 256)
  1812. * @param r defines the red component to read from (value between 0 and 255)
  1813. * @param g defines the green component to read from (value between 0 and 255)
  1814. * @param b defines the blue component to read from (value between 0 and 255)
  1815. * @returns a new Color3 object
  1816. */
  1817. Color3.FromInts = function (r, g, b) {
  1818. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1819. };
  1820. /**
  1821. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1822. * @param start defines the start Color3 value
  1823. * @param end defines the end Color3 value
  1824. * @param amount defines the gradient value between start and end
  1825. * @returns a new Color3 object
  1826. */
  1827. Color3.Lerp = function (start, end, amount) {
  1828. var result = new Color3(0.0, 0.0, 0.0);
  1829. Color3.LerpToRef(start, end, amount, result);
  1830. return result;
  1831. };
  1832. /**
  1833. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1834. * @param left defines the start value
  1835. * @param right defines the end value
  1836. * @param amount defines the gradient factor
  1837. * @param result defines the Color3 object where to store the result
  1838. */
  1839. Color3.LerpToRef = function (left, right, amount, result) {
  1840. result.r = left.r + ((right.r - left.r) * amount);
  1841. result.g = left.g + ((right.g - left.g) * amount);
  1842. result.b = left.b + ((right.b - left.b) * amount);
  1843. };
  1844. /**
  1845. * Returns a Color3 value containing a red color
  1846. * @returns a new Color3 object
  1847. */
  1848. Color3.Red = function () { return new Color3(1, 0, 0); };
  1849. /**
  1850. * Returns a Color3 value containing a green color
  1851. * @returns a new Color3 object
  1852. */
  1853. Color3.Green = function () { return new Color3(0, 1, 0); };
  1854. /**
  1855. * Returns a Color3 value containing a blue color
  1856. * @returns a new Color3 object
  1857. */
  1858. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1859. /**
  1860. * Returns a Color3 value containing a black color
  1861. * @returns a new Color3 object
  1862. */
  1863. Color3.Black = function () { return new Color3(0, 0, 0); };
  1864. /**
  1865. * Returns a Color3 value containing a white color
  1866. * @returns a new Color3 object
  1867. */
  1868. Color3.White = function () { return new Color3(1, 1, 1); };
  1869. /**
  1870. * Returns a Color3 value containing a purple color
  1871. * @returns a new Color3 object
  1872. */
  1873. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1874. /**
  1875. * Returns a Color3 value containing a magenta color
  1876. * @returns a new Color3 object
  1877. */
  1878. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1879. /**
  1880. * Returns a Color3 value containing a yellow color
  1881. * @returns a new Color3 object
  1882. */
  1883. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1884. /**
  1885. * Returns a Color3 value containing a gray color
  1886. * @returns a new Color3 object
  1887. */
  1888. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1889. /**
  1890. * Returns a Color3 value containing a teal color
  1891. * @returns a new Color3 object
  1892. */
  1893. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1894. /**
  1895. * Returns a Color3 value containing a random color
  1896. * @returns a new Color3 object
  1897. */
  1898. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1899. return Color3;
  1900. }());
  1901. BABYLON.Color3 = Color3;
  1902. /**
  1903. * Class used to hold a RBGA color
  1904. */
  1905. var Color4 = /** @class */ (function () {
  1906. /**
  1907. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1908. * @param r defines the red component (between 0 and 1, default is 0)
  1909. * @param g defines the green component (between 0 and 1, default is 0)
  1910. * @param b defines the blue component (between 0 and 1, default is 0)
  1911. * @param a defines the alpha component (between 0 and 1, default is 1)
  1912. */
  1913. function Color4(
  1914. /**
  1915. * Defines the red component (between 0 and 1, default is 0)
  1916. */
  1917. r,
  1918. /**
  1919. * Defines the green component (between 0 and 1, default is 0)
  1920. */
  1921. g,
  1922. /**
  1923. * Defines the blue component (between 0 and 1, default is 0)
  1924. */
  1925. b,
  1926. /**
  1927. * Defines the alpha component (between 0 and 1, default is 1)
  1928. */
  1929. a) {
  1930. if (r === void 0) { r = 0; }
  1931. if (g === void 0) { g = 0; }
  1932. if (b === void 0) { b = 0; }
  1933. if (a === void 0) { a = 1; }
  1934. this.r = r;
  1935. this.g = g;
  1936. this.b = b;
  1937. this.a = a;
  1938. }
  1939. // Operators
  1940. /**
  1941. * Adds in place the given Color4 values to the current Color4 object
  1942. * @param right defines the second operand
  1943. * @returns the current updated Color4 object
  1944. */
  1945. Color4.prototype.addInPlace = function (right) {
  1946. this.r += right.r;
  1947. this.g += right.g;
  1948. this.b += right.b;
  1949. this.a += right.a;
  1950. return this;
  1951. };
  1952. /**
  1953. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1954. * @returns the new array
  1955. */
  1956. Color4.prototype.asArray = function () {
  1957. var result = new Array();
  1958. this.toArray(result, 0);
  1959. return result;
  1960. };
  1961. /**
  1962. * Stores from the starting index in the given array the Color4 successive values
  1963. * @param array defines the array where to store the r,g,b components
  1964. * @param index defines an optional index in the target array to define where to start storing values
  1965. * @returns the current Color4 object
  1966. */
  1967. Color4.prototype.toArray = function (array, index) {
  1968. if (index === undefined) {
  1969. index = 0;
  1970. }
  1971. array[index] = this.r;
  1972. array[index + 1] = this.g;
  1973. array[index + 2] = this.b;
  1974. array[index + 3] = this.a;
  1975. return this;
  1976. };
  1977. /**
  1978. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1979. * @param right defines the second operand
  1980. * @returns a new Color4 object
  1981. */
  1982. Color4.prototype.add = function (right) {
  1983. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1984. };
  1985. /**
  1986. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1987. * @param right defines the second operand
  1988. * @returns a new Color4 object
  1989. */
  1990. Color4.prototype.subtract = function (right) {
  1991. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1992. };
  1993. /**
  1994. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1995. * @param right defines the second operand
  1996. * @param result defines the Color4 object where to store the result
  1997. * @returns the current Color4 object
  1998. */
  1999. Color4.prototype.subtractToRef = function (right, result) {
  2000. result.r = this.r - right.r;
  2001. result.g = this.g - right.g;
  2002. result.b = this.b - right.b;
  2003. result.a = this.a - right.a;
  2004. return this;
  2005. };
  2006. /**
  2007. * Creates a new Color4 with the current Color4 values multiplied by scale
  2008. * @param scale defines the scaling factor to apply
  2009. * @returns a new Color4 object
  2010. */
  2011. Color4.prototype.scale = function (scale) {
  2012. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  2013. };
  2014. /**
  2015. * Multiplies the current Color4 values by scale and stores the result in "result"
  2016. * @param scale defines the scaling factor to apply
  2017. * @param result defines the Color4 object where to store the result
  2018. * @returns the current unmodified Color4
  2019. */
  2020. Color4.prototype.scaleToRef = function (scale, result) {
  2021. result.r = this.r * scale;
  2022. result.g = this.g * scale;
  2023. result.b = this.b * scale;
  2024. result.a = this.a * scale;
  2025. return this;
  2026. };
  2027. /**
  2028. * Scale the current Color4 values by a factor and add the result to a given Color4
  2029. * @param scale defines the scale factor
  2030. * @param result defines the Color4 object where to store the result
  2031. * @returns the unmodified current Color4
  2032. */
  2033. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2034. result.r += this.r * scale;
  2035. result.g += this.g * scale;
  2036. result.b += this.b * scale;
  2037. result.a += this.a * scale;
  2038. return this;
  2039. };
  2040. /**
  2041. * Clamps the rgb values by the min and max values and stores the result into "result"
  2042. * @param min defines minimum clamping value (default is 0)
  2043. * @param max defines maximum clamping value (default is 1)
  2044. * @param result defines color to store the result into.
  2045. * @returns the cuurent Color4
  2046. */
  2047. Color4.prototype.clampToRef = function (min, max, result) {
  2048. if (min === void 0) { min = 0; }
  2049. if (max === void 0) { max = 1; }
  2050. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2051. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2052. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2053. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2054. return this;
  2055. };
  2056. /**
  2057. * Multipy an Color4 value by another and return a new Color4 object
  2058. * @param color defines the Color4 value to multiply by
  2059. * @returns a new Color4 object
  2060. */
  2061. Color4.prototype.multiply = function (color) {
  2062. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2063. };
  2064. /**
  2065. * Multipy a Color4 value by another and push the result in a reference value
  2066. * @param color defines the Color4 value to multiply by
  2067. * @param result defines the Color4 to fill the result in
  2068. * @returns the result Color4
  2069. */
  2070. Color4.prototype.multiplyToRef = function (color, result) {
  2071. result.r = this.r * color.r;
  2072. result.g = this.g * color.g;
  2073. result.b = this.b * color.b;
  2074. result.a = this.a * color.a;
  2075. return result;
  2076. };
  2077. /**
  2078. * Creates a string with the Color4 current values
  2079. * @returns the string representation of the Color4 object
  2080. */
  2081. Color4.prototype.toString = function () {
  2082. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2083. };
  2084. /**
  2085. * Returns the string "Color4"
  2086. * @returns "Color4"
  2087. */
  2088. Color4.prototype.getClassName = function () {
  2089. return "Color4";
  2090. };
  2091. /**
  2092. * Compute the Color4 hash code
  2093. * @returns an unique number that can be used to hash Color4 objects
  2094. */
  2095. Color4.prototype.getHashCode = function () {
  2096. var hash = this.r || 0;
  2097. hash = (hash * 397) ^ (this.g || 0);
  2098. hash = (hash * 397) ^ (this.b || 0);
  2099. hash = (hash * 397) ^ (this.a || 0);
  2100. return hash;
  2101. };
  2102. /**
  2103. * Creates a new Color4 copied from the current one
  2104. * @returns a new Color4 object
  2105. */
  2106. Color4.prototype.clone = function () {
  2107. return new Color4(this.r, this.g, this.b, this.a);
  2108. };
  2109. /**
  2110. * Copies the given Color4 values into the current one
  2111. * @param source defines the source Color4 object
  2112. * @returns the current updated Color4 object
  2113. */
  2114. Color4.prototype.copyFrom = function (source) {
  2115. this.r = source.r;
  2116. this.g = source.g;
  2117. this.b = source.b;
  2118. this.a = source.a;
  2119. return this;
  2120. };
  2121. /**
  2122. * Copies the given float values into the current one
  2123. * @param r defines the red component to read from
  2124. * @param g defines the green component to read from
  2125. * @param b defines the blue component to read from
  2126. * @param a defines the alpha component to read from
  2127. * @returns the current updated Color4 object
  2128. */
  2129. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2130. this.r = r;
  2131. this.g = g;
  2132. this.b = b;
  2133. this.a = a;
  2134. return this;
  2135. };
  2136. /**
  2137. * Copies the given float values into the current one
  2138. * @param r defines the red component to read from
  2139. * @param g defines the green component to read from
  2140. * @param b defines the blue component to read from
  2141. * @param a defines the alpha component to read from
  2142. * @returns the current updated Color4 object
  2143. */
  2144. Color4.prototype.set = function (r, g, b, a) {
  2145. return this.copyFromFloats(r, g, b, a);
  2146. };
  2147. /**
  2148. * Compute the Color4 hexadecimal code as a string
  2149. * @returns a string containing the hexadecimal representation of the Color4 object
  2150. */
  2151. Color4.prototype.toHexString = function () {
  2152. var intR = (this.r * 255) | 0;
  2153. var intG = (this.g * 255) | 0;
  2154. var intB = (this.b * 255) | 0;
  2155. var intA = (this.a * 255) | 0;
  2156. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2157. };
  2158. /**
  2159. * Computes a new Color4 converted from the current one to linear space
  2160. * @returns a new Color4 object
  2161. */
  2162. Color4.prototype.toLinearSpace = function () {
  2163. var convertedColor = new Color4();
  2164. this.toLinearSpaceToRef(convertedColor);
  2165. return convertedColor;
  2166. };
  2167. /**
  2168. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2169. * @param convertedColor defines the Color4 object where to store the linear space version
  2170. * @returns the unmodified Color4
  2171. */
  2172. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2173. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2174. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2175. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2176. convertedColor.a = this.a;
  2177. return this;
  2178. };
  2179. /**
  2180. * Computes a new Color4 converted from the current one to gamma space
  2181. * @returns a new Color4 object
  2182. */
  2183. Color4.prototype.toGammaSpace = function () {
  2184. var convertedColor = new Color4();
  2185. this.toGammaSpaceToRef(convertedColor);
  2186. return convertedColor;
  2187. };
  2188. /**
  2189. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2190. * @param convertedColor defines the Color4 object where to store the gamma space version
  2191. * @returns the unmodified Color4
  2192. */
  2193. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2194. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2195. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2196. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2197. convertedColor.a = this.a;
  2198. return this;
  2199. };
  2200. // Statics
  2201. /**
  2202. * Creates a new Color4 from the string containing valid hexadecimal values
  2203. * @param hex defines a string containing valid hexadecimal values
  2204. * @returns a new Color4 object
  2205. */
  2206. Color4.FromHexString = function (hex) {
  2207. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2208. return new Color4(0.0, 0.0, 0.0, 0.0);
  2209. }
  2210. var r = parseInt(hex.substring(1, 3), 16);
  2211. var g = parseInt(hex.substring(3, 5), 16);
  2212. var b = parseInt(hex.substring(5, 7), 16);
  2213. var a = parseInt(hex.substring(7, 9), 16);
  2214. return Color4.FromInts(r, g, b, a);
  2215. };
  2216. /**
  2217. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2218. * @param left defines the start value
  2219. * @param right defines the end value
  2220. * @param amount defines the gradient factor
  2221. * @returns a new Color4 object
  2222. */
  2223. Color4.Lerp = function (left, right, amount) {
  2224. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2225. Color4.LerpToRef(left, right, amount, result);
  2226. return result;
  2227. };
  2228. /**
  2229. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2230. * @param left defines the start value
  2231. * @param right defines the end value
  2232. * @param amount defines the gradient factor
  2233. * @param result defines the Color4 object where to store data
  2234. */
  2235. Color4.LerpToRef = function (left, right, amount, result) {
  2236. result.r = left.r + (right.r - left.r) * amount;
  2237. result.g = left.g + (right.g - left.g) * amount;
  2238. result.b = left.b + (right.b - left.b) * amount;
  2239. result.a = left.a + (right.a - left.a) * amount;
  2240. };
  2241. /**
  2242. * Creates a new Color4 from a Color3 and an alpha value
  2243. * @param color3 defines the source Color3 to read from
  2244. * @param alpha defines the alpha component (1.0 by default)
  2245. * @returns a new Color4 object
  2246. */
  2247. Color4.FromColor3 = function (color3, alpha) {
  2248. if (alpha === void 0) { alpha = 1.0; }
  2249. return new Color4(color3.r, color3.g, color3.b, alpha);
  2250. };
  2251. /**
  2252. * Creates a new Color4 from the starting index element of the given array
  2253. * @param array defines the source array to read from
  2254. * @param offset defines the offset in the source array
  2255. * @returns a new Color4 object
  2256. */
  2257. Color4.FromArray = function (array, offset) {
  2258. if (offset === void 0) { offset = 0; }
  2259. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2260. };
  2261. /**
  2262. * Creates a new Color3 from integer values (< 256)
  2263. * @param r defines the red component to read from (value between 0 and 255)
  2264. * @param g defines the green component to read from (value between 0 and 255)
  2265. * @param b defines the blue component to read from (value between 0 and 255)
  2266. * @param a defines the alpha component to read from (value between 0 and 255)
  2267. * @returns a new Color3 object
  2268. */
  2269. Color4.FromInts = function (r, g, b, a) {
  2270. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2271. };
  2272. /**
  2273. * Check the content of a given array and convert it to an array containing RGBA data
  2274. * If the original array was already containing count * 4 values then it is returned directly
  2275. * @param colors defines the array to check
  2276. * @param count defines the number of RGBA data to expect
  2277. * @returns an array containing count * 4 values (RGBA)
  2278. */
  2279. Color4.CheckColors4 = function (colors, count) {
  2280. // Check if color3 was used
  2281. if (colors.length === count * 3) {
  2282. var colors4 = [];
  2283. for (var index = 0; index < colors.length; index += 3) {
  2284. var newIndex = (index / 3) * 4;
  2285. colors4[newIndex] = colors[index];
  2286. colors4[newIndex + 1] = colors[index + 1];
  2287. colors4[newIndex + 2] = colors[index + 2];
  2288. colors4[newIndex + 3] = 1.0;
  2289. }
  2290. return colors4;
  2291. }
  2292. return colors;
  2293. };
  2294. return Color4;
  2295. }());
  2296. BABYLON.Color4 = Color4;
  2297. /**
  2298. * Class representing a vector containing 2 coordinates
  2299. */
  2300. var Vector2 = /** @class */ (function () {
  2301. /**
  2302. * Creates a new Vector2 from the given x and y coordinates
  2303. * @param x defines the first coordinate
  2304. * @param y defines the second coordinate
  2305. */
  2306. function Vector2(
  2307. /** defines the first coordinate */
  2308. x,
  2309. /** defines the second coordinate */
  2310. y) {
  2311. if (x === void 0) { x = 0; }
  2312. if (y === void 0) { y = 0; }
  2313. this.x = x;
  2314. this.y = y;
  2315. }
  2316. /**
  2317. * Gets a string with the Vector2 coordinates
  2318. * @returns a string with the Vector2 coordinates
  2319. */
  2320. Vector2.prototype.toString = function () {
  2321. return "{X: " + this.x + " Y:" + this.y + "}";
  2322. };
  2323. /**
  2324. * Gets class name
  2325. * @returns the string "Vector2"
  2326. */
  2327. Vector2.prototype.getClassName = function () {
  2328. return "Vector2";
  2329. };
  2330. /**
  2331. * Gets current vector hash code
  2332. * @returns the Vector2 hash code as a number
  2333. */
  2334. Vector2.prototype.getHashCode = function () {
  2335. var hash = this.x || 0;
  2336. hash = (hash * 397) ^ (this.y || 0);
  2337. return hash;
  2338. };
  2339. // Operators
  2340. /**
  2341. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2342. * @param array defines the source array
  2343. * @param index defines the offset in source array
  2344. * @returns the current Vector2
  2345. */
  2346. Vector2.prototype.toArray = function (array, index) {
  2347. if (index === void 0) { index = 0; }
  2348. array[index] = this.x;
  2349. array[index + 1] = this.y;
  2350. return this;
  2351. };
  2352. /**
  2353. * Copy the current vector to an array
  2354. * @returns a new array with 2 elements: the Vector2 coordinates.
  2355. */
  2356. Vector2.prototype.asArray = function () {
  2357. var result = new Array();
  2358. this.toArray(result, 0);
  2359. return result;
  2360. };
  2361. /**
  2362. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2363. * @param source defines the source Vector2
  2364. * @returns the current updated Vector2
  2365. */
  2366. Vector2.prototype.copyFrom = function (source) {
  2367. this.x = source.x;
  2368. this.y = source.y;
  2369. return this;
  2370. };
  2371. /**
  2372. * Sets the Vector2 coordinates with the given floats
  2373. * @param x defines the first coordinate
  2374. * @param y defines the second coordinate
  2375. * @returns the current updated Vector2
  2376. */
  2377. Vector2.prototype.copyFromFloats = function (x, y) {
  2378. this.x = x;
  2379. this.y = y;
  2380. return this;
  2381. };
  2382. /**
  2383. * Sets the Vector2 coordinates with the given floats
  2384. * @param x defines the first coordinate
  2385. * @param y defines the second coordinate
  2386. * @returns the current updated Vector2
  2387. */
  2388. Vector2.prototype.set = function (x, y) {
  2389. return this.copyFromFloats(x, y);
  2390. };
  2391. /**
  2392. * Add another vector with the current one
  2393. * @param otherVector defines the other vector
  2394. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2395. */
  2396. Vector2.prototype.add = function (otherVector) {
  2397. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2398. };
  2399. /**
  2400. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2401. * @param otherVector defines the other vector
  2402. * @param result defines the target vector
  2403. * @returns the unmodified current Vector2
  2404. */
  2405. Vector2.prototype.addToRef = function (otherVector, result) {
  2406. result.x = this.x + otherVector.x;
  2407. result.y = this.y + otherVector.y;
  2408. return this;
  2409. };
  2410. /**
  2411. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2412. * @param otherVector defines the other vector
  2413. * @returns the current updated Vector2
  2414. */
  2415. Vector2.prototype.addInPlace = function (otherVector) {
  2416. this.x += otherVector.x;
  2417. this.y += otherVector.y;
  2418. return this;
  2419. };
  2420. /**
  2421. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2422. * @param otherVector defines the other vector
  2423. * @returns a new Vector2
  2424. */
  2425. Vector2.prototype.addVector3 = function (otherVector) {
  2426. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2427. };
  2428. /**
  2429. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2430. * @param otherVector defines the other vector
  2431. * @returns a new Vector2
  2432. */
  2433. Vector2.prototype.subtract = function (otherVector) {
  2434. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2435. };
  2436. /**
  2437. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2438. * @param otherVector defines the other vector
  2439. * @param result defines the target vector
  2440. * @returns the unmodified current Vector2
  2441. */
  2442. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2443. result.x = this.x - otherVector.x;
  2444. result.y = this.y - otherVector.y;
  2445. return this;
  2446. };
  2447. /**
  2448. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2449. * @param otherVector defines the other vector
  2450. * @returns the current updated Vector2
  2451. */
  2452. Vector2.prototype.subtractInPlace = function (otherVector) {
  2453. this.x -= otherVector.x;
  2454. this.y -= otherVector.y;
  2455. return this;
  2456. };
  2457. /**
  2458. * Multiplies in place the current Vector2 coordinates by the given ones
  2459. * @param otherVector defines the other vector
  2460. * @returns the current updated Vector2
  2461. */
  2462. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2463. this.x *= otherVector.x;
  2464. this.y *= otherVector.y;
  2465. return this;
  2466. };
  2467. /**
  2468. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2469. * @param otherVector defines the other vector
  2470. * @returns a new Vector2
  2471. */
  2472. Vector2.prototype.multiply = function (otherVector) {
  2473. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2474. };
  2475. /**
  2476. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2477. * @param otherVector defines the other vector
  2478. * @param result defines the target vector
  2479. * @returns the unmodified current Vector2
  2480. */
  2481. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2482. result.x = this.x * otherVector.x;
  2483. result.y = this.y * otherVector.y;
  2484. return this;
  2485. };
  2486. /**
  2487. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2488. * @param x defines the first coordinate
  2489. * @param y defines the second coordinate
  2490. * @returns a new Vector2
  2491. */
  2492. Vector2.prototype.multiplyByFloats = function (x, y) {
  2493. return new Vector2(this.x * x, this.y * y);
  2494. };
  2495. /**
  2496. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2497. * @param otherVector defines the other vector
  2498. * @returns a new Vector2
  2499. */
  2500. Vector2.prototype.divide = function (otherVector) {
  2501. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2502. };
  2503. /**
  2504. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2505. * @param otherVector defines the other vector
  2506. * @param result defines the target vector
  2507. * @returns the unmodified current Vector2
  2508. */
  2509. Vector2.prototype.divideToRef = function (otherVector, result) {
  2510. result.x = this.x / otherVector.x;
  2511. result.y = this.y / otherVector.y;
  2512. return this;
  2513. };
  2514. /**
  2515. * Divides the current Vector2 coordinates by the given ones
  2516. * @param otherVector defines the other vector
  2517. * @returns the current updated Vector2
  2518. */
  2519. Vector2.prototype.divideInPlace = function (otherVector) {
  2520. return this.divideToRef(otherVector, this);
  2521. };
  2522. /**
  2523. * Gets a new Vector2 with current Vector2 negated coordinates
  2524. * @returns a new Vector2
  2525. */
  2526. Vector2.prototype.negate = function () {
  2527. return new Vector2(-this.x, -this.y);
  2528. };
  2529. /**
  2530. * Multiply the Vector2 coordinates by scale
  2531. * @param scale defines the scaling factor
  2532. * @returns the current updated Vector2
  2533. */
  2534. Vector2.prototype.scaleInPlace = function (scale) {
  2535. this.x *= scale;
  2536. this.y *= scale;
  2537. return this;
  2538. };
  2539. /**
  2540. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2541. * @param scale defines the scaling factor
  2542. * @returns a new Vector2
  2543. */
  2544. Vector2.prototype.scale = function (scale) {
  2545. var result = new Vector2(0, 0);
  2546. this.scaleToRef(scale, result);
  2547. return result;
  2548. };
  2549. /**
  2550. * Scale the current Vector2 values by a factor to a given Vector2
  2551. * @param scale defines the scale factor
  2552. * @param result defines the Vector2 object where to store the result
  2553. * @returns the unmodified current Vector2
  2554. */
  2555. Vector2.prototype.scaleToRef = function (scale, result) {
  2556. result.x = this.x * scale;
  2557. result.y = this.y * scale;
  2558. return this;
  2559. };
  2560. /**
  2561. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2562. * @param scale defines the scale factor
  2563. * @param result defines the Vector2 object where to store the result
  2564. * @returns the unmodified current Vector2
  2565. */
  2566. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2567. result.x += this.x * scale;
  2568. result.y += this.y * scale;
  2569. return this;
  2570. };
  2571. /**
  2572. * Gets a boolean if two vectors are equals
  2573. * @param otherVector defines the other vector
  2574. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2575. */
  2576. Vector2.prototype.equals = function (otherVector) {
  2577. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2578. };
  2579. /**
  2580. * Gets a boolean if two vectors are equals (using an epsilon value)
  2581. * @param otherVector defines the other vector
  2582. * @param epsilon defines the minimal distance to consider equality
  2583. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2584. */
  2585. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2586. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2587. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2588. };
  2589. /**
  2590. * Gets a new Vector2 from current Vector2 floored values
  2591. * @returns a new Vector2
  2592. */
  2593. Vector2.prototype.floor = function () {
  2594. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2595. };
  2596. /**
  2597. * Gets a new Vector2 from current Vector2 floored values
  2598. * @returns a new Vector2
  2599. */
  2600. Vector2.prototype.fract = function () {
  2601. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2602. };
  2603. // Properties
  2604. /**
  2605. * Gets the length of the vector
  2606. * @returns the vector length (float)
  2607. */
  2608. Vector2.prototype.length = function () {
  2609. return Math.sqrt(this.x * this.x + this.y * this.y);
  2610. };
  2611. /**
  2612. * Gets the vector squared length
  2613. * @returns the vector squared length (float)
  2614. */
  2615. Vector2.prototype.lengthSquared = function () {
  2616. return (this.x * this.x + this.y * this.y);
  2617. };
  2618. // Methods
  2619. /**
  2620. * Normalize the vector
  2621. * @returns the current updated Vector2
  2622. */
  2623. Vector2.prototype.normalize = function () {
  2624. var len = this.length();
  2625. if (len === 0)
  2626. return this;
  2627. var num = 1.0 / len;
  2628. this.x *= num;
  2629. this.y *= num;
  2630. return this;
  2631. };
  2632. /**
  2633. * Gets a new Vector2 copied from the Vector2
  2634. * @returns a new Vector2
  2635. */
  2636. Vector2.prototype.clone = function () {
  2637. return new Vector2(this.x, this.y);
  2638. };
  2639. // Statics
  2640. /**
  2641. * Gets a new Vector2(0, 0)
  2642. * @returns a new Vector2
  2643. */
  2644. Vector2.Zero = function () {
  2645. return new Vector2(0, 0);
  2646. };
  2647. /**
  2648. * Gets a new Vector2(1, 1)
  2649. * @returns a new Vector2
  2650. */
  2651. Vector2.One = function () {
  2652. return new Vector2(1, 1);
  2653. };
  2654. /**
  2655. * Gets a new Vector2 set from the given index element of the given array
  2656. * @param array defines the data source
  2657. * @param offset defines the offset in the data source
  2658. * @returns a new Vector2
  2659. */
  2660. Vector2.FromArray = function (array, offset) {
  2661. if (offset === void 0) { offset = 0; }
  2662. return new Vector2(array[offset], array[offset + 1]);
  2663. };
  2664. /**
  2665. * Sets "result" from the given index element of the given array
  2666. * @param array defines the data source
  2667. * @param offset defines the offset in the data source
  2668. * @param result defines the target vector
  2669. */
  2670. Vector2.FromArrayToRef = function (array, offset, result) {
  2671. result.x = array[offset];
  2672. result.y = array[offset + 1];
  2673. };
  2674. /**
  2675. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2676. * @param value1 defines 1st point of control
  2677. * @param value2 defines 2nd point of control
  2678. * @param value3 defines 3rd point of control
  2679. * @param value4 defines 4th point of control
  2680. * @param amount defines the interpolation factor
  2681. * @returns a new Vector2
  2682. */
  2683. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2684. var squared = amount * amount;
  2685. var cubed = amount * squared;
  2686. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2687. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2688. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2689. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2690. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2691. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2692. return new Vector2(x, y);
  2693. };
  2694. /**
  2695. * 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".
  2696. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2697. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2698. * @param value defines the value to clamp
  2699. * @param min defines the lower limit
  2700. * @param max defines the upper limit
  2701. * @returns a new Vector2
  2702. */
  2703. Vector2.Clamp = function (value, min, max) {
  2704. var x = value.x;
  2705. x = (x > max.x) ? max.x : x;
  2706. x = (x < min.x) ? min.x : x;
  2707. var y = value.y;
  2708. y = (y > max.y) ? max.y : y;
  2709. y = (y < min.y) ? min.y : y;
  2710. return new Vector2(x, y);
  2711. };
  2712. /**
  2713. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2714. * @param value1 defines the 1st control point
  2715. * @param tangent1 defines the outgoing tangent
  2716. * @param value2 defines the 2nd control point
  2717. * @param tangent2 defines the incoming tangent
  2718. * @param amount defines the interpolation factor
  2719. * @returns a new Vector2
  2720. */
  2721. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2722. var squared = amount * amount;
  2723. var cubed = amount * squared;
  2724. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2725. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2726. var part3 = (cubed - (2.0 * squared)) + amount;
  2727. var part4 = cubed - squared;
  2728. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2729. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2730. return new Vector2(x, y);
  2731. };
  2732. /**
  2733. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2734. * @param start defines the start vector
  2735. * @param end defines the end vector
  2736. * @param amount defines the interpolation factor
  2737. * @returns a new Vector2
  2738. */
  2739. Vector2.Lerp = function (start, end, amount) {
  2740. var x = start.x + ((end.x - start.x) * amount);
  2741. var y = start.y + ((end.y - start.y) * amount);
  2742. return new Vector2(x, y);
  2743. };
  2744. /**
  2745. * Gets the dot product of the vector "left" and the vector "right"
  2746. * @param left defines first vector
  2747. * @param right defines second vector
  2748. * @returns the dot product (float)
  2749. */
  2750. Vector2.Dot = function (left, right) {
  2751. return left.x * right.x + left.y * right.y;
  2752. };
  2753. /**
  2754. * Returns a new Vector2 equal to the normalized given vector
  2755. * @param vector defines the vector to normalize
  2756. * @returns a new Vector2
  2757. */
  2758. Vector2.Normalize = function (vector) {
  2759. var newVector = vector.clone();
  2760. newVector.normalize();
  2761. return newVector;
  2762. };
  2763. /**
  2764. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2765. * @param left defines 1st vector
  2766. * @param right defines 2nd vector
  2767. * @returns a new Vector2
  2768. */
  2769. Vector2.Minimize = function (left, right) {
  2770. var x = (left.x < right.x) ? left.x : right.x;
  2771. var y = (left.y < right.y) ? left.y : right.y;
  2772. return new Vector2(x, y);
  2773. };
  2774. /**
  2775. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2776. * @param left defines 1st vector
  2777. * @param right defines 2nd vector
  2778. * @returns a new Vector2
  2779. */
  2780. Vector2.Maximize = function (left, right) {
  2781. var x = (left.x > right.x) ? left.x : right.x;
  2782. var y = (left.y > right.y) ? left.y : right.y;
  2783. return new Vector2(x, y);
  2784. };
  2785. /**
  2786. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2787. * @param vector defines the vector to transform
  2788. * @param transformation defines the matrix to apply
  2789. * @returns a new Vector2
  2790. */
  2791. Vector2.Transform = function (vector, transformation) {
  2792. var r = Vector2.Zero();
  2793. Vector2.TransformToRef(vector, transformation, r);
  2794. return r;
  2795. };
  2796. /**
  2797. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2798. * @param vector defines the vector to transform
  2799. * @param transformation defines the matrix to apply
  2800. * @param result defines the target vector
  2801. */
  2802. Vector2.TransformToRef = function (vector, transformation, result) {
  2803. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2804. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2805. result.x = x;
  2806. result.y = y;
  2807. };
  2808. /**
  2809. * Determines if a given vector is included in a triangle
  2810. * @param p defines the vector to test
  2811. * @param p0 defines 1st triangle point
  2812. * @param p1 defines 2nd triangle point
  2813. * @param p2 defines 3rd triangle point
  2814. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2815. */
  2816. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2817. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2818. var sign = a < 0 ? -1 : 1;
  2819. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2820. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2821. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2822. };
  2823. /**
  2824. * Gets the distance between the vectors "value1" and "value2"
  2825. * @param value1 defines first vector
  2826. * @param value2 defines second vector
  2827. * @returns the distance between vectors
  2828. */
  2829. Vector2.Distance = function (value1, value2) {
  2830. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2831. };
  2832. /**
  2833. * Returns the squared distance between the vectors "value1" and "value2"
  2834. * @param value1 defines first vector
  2835. * @param value2 defines second vector
  2836. * @returns the squared distance between vectors
  2837. */
  2838. Vector2.DistanceSquared = function (value1, value2) {
  2839. var x = value1.x - value2.x;
  2840. var y = value1.y - value2.y;
  2841. return (x * x) + (y * y);
  2842. };
  2843. /**
  2844. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2845. * @param value1 defines first vector
  2846. * @param value2 defines second vector
  2847. * @returns a new Vector2
  2848. */
  2849. Vector2.Center = function (value1, value2) {
  2850. var center = value1.add(value2);
  2851. center.scaleInPlace(0.5);
  2852. return center;
  2853. };
  2854. /**
  2855. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2856. * @param p defines the middle point
  2857. * @param segA defines one point of the segment
  2858. * @param segB defines the other point of the segment
  2859. * @returns the shortest distance
  2860. */
  2861. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2862. var l2 = Vector2.DistanceSquared(segA, segB);
  2863. if (l2 === 0.0) {
  2864. return Vector2.Distance(p, segA);
  2865. }
  2866. var v = segB.subtract(segA);
  2867. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2868. var proj = segA.add(v.multiplyByFloats(t, t));
  2869. return Vector2.Distance(p, proj);
  2870. };
  2871. return Vector2;
  2872. }());
  2873. BABYLON.Vector2 = Vector2;
  2874. /**
  2875. * Classed used to store (x,y,z) vector representation
  2876. * A Vector3 is the main object used in 3D geometry
  2877. * It can represent etiher the coordinates of a point the space, either a direction
  2878. * Reminder: Babylon.js uses a left handed forward facing system
  2879. */
  2880. var Vector3 = /** @class */ (function () {
  2881. /**
  2882. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2883. * @param x defines the first coordinates (on X axis)
  2884. * @param y defines the second coordinates (on Y axis)
  2885. * @param z defines the third coordinates (on Z axis)
  2886. */
  2887. function Vector3(
  2888. /**
  2889. * Defines the first coordinates (on X axis)
  2890. */
  2891. x,
  2892. /**
  2893. * Defines the second coordinates (on Y axis)
  2894. */
  2895. y,
  2896. /**
  2897. * Defines the third coordinates (on Z axis)
  2898. */
  2899. z) {
  2900. if (x === void 0) { x = 0; }
  2901. if (y === void 0) { y = 0; }
  2902. if (z === void 0) { z = 0; }
  2903. this.x = x;
  2904. this.y = y;
  2905. this.z = z;
  2906. }
  2907. /**
  2908. * Creates a string representation of the Vector3
  2909. * @returns a string with the Vector3 coordinates.
  2910. */
  2911. Vector3.prototype.toString = function () {
  2912. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2913. };
  2914. /**
  2915. * Gets the class name
  2916. * @returns the string "Vector3"
  2917. */
  2918. Vector3.prototype.getClassName = function () {
  2919. return "Vector3";
  2920. };
  2921. /**
  2922. * Creates the Vector3 hash code
  2923. * @returns a number which tends to be unique between Vector3 instances
  2924. */
  2925. Vector3.prototype.getHashCode = function () {
  2926. var hash = this.x || 0;
  2927. hash = (hash * 397) ^ (this.y || 0);
  2928. hash = (hash * 397) ^ (this.z || 0);
  2929. return hash;
  2930. };
  2931. // Operators
  2932. /**
  2933. * Creates an array containing three elements : the coordinates of the Vector3
  2934. * @returns a new array of numbers
  2935. */
  2936. Vector3.prototype.asArray = function () {
  2937. var result = [];
  2938. this.toArray(result, 0);
  2939. return result;
  2940. };
  2941. /**
  2942. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2943. * @param array defines the destination array
  2944. * @param index defines the offset in the destination array
  2945. * @returns the current Vector3
  2946. */
  2947. Vector3.prototype.toArray = function (array, index) {
  2948. if (index === void 0) { index = 0; }
  2949. array[index] = this.x;
  2950. array[index + 1] = this.y;
  2951. array[index + 2] = this.z;
  2952. return this;
  2953. };
  2954. /**
  2955. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2956. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2957. */
  2958. Vector3.prototype.toQuaternion = function () {
  2959. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2960. };
  2961. /**
  2962. * Adds the given vector to the current Vector3
  2963. * @param otherVector defines the second operand
  2964. * @returns the current updated Vector3
  2965. */
  2966. Vector3.prototype.addInPlace = function (otherVector) {
  2967. this.x += otherVector.x;
  2968. this.y += otherVector.y;
  2969. this.z += otherVector.z;
  2970. return this;
  2971. };
  2972. /**
  2973. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2974. * @param otherVector defines the second operand
  2975. * @returns the resulting Vector3
  2976. */
  2977. Vector3.prototype.add = function (otherVector) {
  2978. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2979. };
  2980. /**
  2981. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2982. * @param otherVector defines the second operand
  2983. * @param result defines the Vector3 object where to store the result
  2984. * @returns the current Vector3
  2985. */
  2986. Vector3.prototype.addToRef = function (otherVector, result) {
  2987. result.x = this.x + otherVector.x;
  2988. result.y = this.y + otherVector.y;
  2989. result.z = this.z + otherVector.z;
  2990. return this;
  2991. };
  2992. /**
  2993. * Subtract the given vector from the current Vector3
  2994. * @param otherVector defines the second operand
  2995. * @returns the current updated Vector3
  2996. */
  2997. Vector3.prototype.subtractInPlace = function (otherVector) {
  2998. this.x -= otherVector.x;
  2999. this.y -= otherVector.y;
  3000. this.z -= otherVector.z;
  3001. return this;
  3002. };
  3003. /**
  3004. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  3005. * @param otherVector defines the second operand
  3006. * @returns the resulting Vector3
  3007. */
  3008. Vector3.prototype.subtract = function (otherVector) {
  3009. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  3010. };
  3011. /**
  3012. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  3013. * @param otherVector defines the second operand
  3014. * @param result defines the Vector3 object where to store the result
  3015. * @returns the current Vector3
  3016. */
  3017. Vector3.prototype.subtractToRef = function (otherVector, result) {
  3018. result.x = this.x - otherVector.x;
  3019. result.y = this.y - otherVector.y;
  3020. result.z = this.z - otherVector.z;
  3021. return this;
  3022. };
  3023. /**
  3024. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  3025. * @param x defines the x coordinate of the operand
  3026. * @param y defines the y coordinate of the operand
  3027. * @param z defines the z coordinate of the operand
  3028. * @returns the resulting Vector3
  3029. */
  3030. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  3031. return new Vector3(this.x - x, this.y - y, this.z - z);
  3032. };
  3033. /**
  3034. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  3035. * @param x defines the x coordinate of the operand
  3036. * @param y defines the y coordinate of the operand
  3037. * @param z defines the z coordinate of the operand
  3038. * @param result defines the Vector3 object where to store the result
  3039. * @returns the current Vector3
  3040. */
  3041. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  3042. result.x = this.x - x;
  3043. result.y = this.y - y;
  3044. result.z = this.z - z;
  3045. return this;
  3046. };
  3047. /**
  3048. * Gets a new Vector3 set with the current Vector3 negated coordinates
  3049. * @returns a new Vector3
  3050. */
  3051. Vector3.prototype.negate = function () {
  3052. return new Vector3(-this.x, -this.y, -this.z);
  3053. };
  3054. /**
  3055. * Multiplies the Vector3 coordinates by the float "scale"
  3056. * @param scale defines the multiplier factor
  3057. * @returns the current updated Vector3
  3058. */
  3059. Vector3.prototype.scaleInPlace = function (scale) {
  3060. this.x *= scale;
  3061. this.y *= scale;
  3062. this.z *= scale;
  3063. return this;
  3064. };
  3065. /**
  3066. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3067. * @param scale defines the multiplier factor
  3068. * @returns a new Vector3
  3069. */
  3070. Vector3.prototype.scale = function (scale) {
  3071. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3072. };
  3073. /**
  3074. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3075. * @param scale defines the multiplier factor
  3076. * @param result defines the Vector3 object where to store the result
  3077. * @returns the current Vector3
  3078. */
  3079. Vector3.prototype.scaleToRef = function (scale, result) {
  3080. result.x = this.x * scale;
  3081. result.y = this.y * scale;
  3082. result.z = this.z * scale;
  3083. return this;
  3084. };
  3085. /**
  3086. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3087. * @param scale defines the scale factor
  3088. * @param result defines the Vector3 object where to store the result
  3089. * @returns the unmodified current Vector3
  3090. */
  3091. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3092. result.x += this.x * scale;
  3093. result.y += this.y * scale;
  3094. result.z += this.z * scale;
  3095. return this;
  3096. };
  3097. /**
  3098. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3099. * @param otherVector defines the second operand
  3100. * @returns true if both vectors are equals
  3101. */
  3102. Vector3.prototype.equals = function (otherVector) {
  3103. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3104. };
  3105. /**
  3106. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3107. * @param otherVector defines the second operand
  3108. * @param epsilon defines the minimal distance to define values as equals
  3109. * @returns true if both vectors are distant less than epsilon
  3110. */
  3111. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3112. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3113. 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);
  3114. };
  3115. /**
  3116. * Returns true if the current Vector3 coordinates equals the given floats
  3117. * @param x defines the x coordinate of the operand
  3118. * @param y defines the y coordinate of the operand
  3119. * @param z defines the z coordinate of the operand
  3120. * @returns true if both vectors are equals
  3121. */
  3122. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3123. return this.x === x && this.y === y && this.z === z;
  3124. };
  3125. /**
  3126. * Multiplies the current Vector3 coordinates by the given ones
  3127. * @param otherVector defines the second operand
  3128. * @returns the current updated Vector3
  3129. */
  3130. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3131. this.x *= otherVector.x;
  3132. this.y *= otherVector.y;
  3133. this.z *= otherVector.z;
  3134. return this;
  3135. };
  3136. /**
  3137. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3138. * @param otherVector defines the second operand
  3139. * @returns the new Vector3
  3140. */
  3141. Vector3.prototype.multiply = function (otherVector) {
  3142. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3143. };
  3144. /**
  3145. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3146. * @param otherVector defines the second operand
  3147. * @param result defines the Vector3 object where to store the result
  3148. * @returns the current Vector3
  3149. */
  3150. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3151. result.x = this.x * otherVector.x;
  3152. result.y = this.y * otherVector.y;
  3153. result.z = this.z * otherVector.z;
  3154. return this;
  3155. };
  3156. /**
  3157. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3158. * @param x defines the x coordinate of the operand
  3159. * @param y defines the y coordinate of the operand
  3160. * @param z defines the z coordinate of the operand
  3161. * @returns the new Vector3
  3162. */
  3163. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3164. return new Vector3(this.x * x, this.y * y, this.z * z);
  3165. };
  3166. /**
  3167. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3168. * @param otherVector defines the second operand
  3169. * @returns the new Vector3
  3170. */
  3171. Vector3.prototype.divide = function (otherVector) {
  3172. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3173. };
  3174. /**
  3175. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3176. * @param otherVector defines the second operand
  3177. * @param result defines the Vector3 object where to store the result
  3178. * @returns the current Vector3
  3179. */
  3180. Vector3.prototype.divideToRef = function (otherVector, result) {
  3181. result.x = this.x / otherVector.x;
  3182. result.y = this.y / otherVector.y;
  3183. result.z = this.z / otherVector.z;
  3184. return this;
  3185. };
  3186. /**
  3187. * Divides the current Vector3 coordinates by the given ones.
  3188. * @param otherVector defines the second operand
  3189. * @returns the current updated Vector3
  3190. */
  3191. Vector3.prototype.divideInPlace = function (otherVector) {
  3192. return this.divideToRef(otherVector, this);
  3193. };
  3194. /**
  3195. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3196. * @param other defines the second operand
  3197. * @returns the current updated Vector3
  3198. */
  3199. Vector3.prototype.minimizeInPlace = function (other) {
  3200. return this.minimizeInPlaceFromFloats(other.x, other.y, other.z);
  3201. };
  3202. /**
  3203. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3204. * @param other defines the second operand
  3205. * @returns the current updated Vector3
  3206. */
  3207. Vector3.prototype.maximizeInPlace = function (other) {
  3208. return this.maximizeInPlaceFromFloats(other.x, other.y, other.z);
  3209. };
  3210. /**
  3211. * Updates the current Vector3 with the minimal coordinate values between its and the given coordinates
  3212. * @param x defines the x coordinate of the operand
  3213. * @param y defines the y coordinate of the operand
  3214. * @param z defines the z coordinate of the operand
  3215. * @returns the current updated Vector3
  3216. */
  3217. Vector3.prototype.minimizeInPlaceFromFloats = function (x, y, z) {
  3218. this.x = Math.min(this.x, x);
  3219. this.y = Math.min(this.y, y);
  3220. this.z = Math.min(this.z, z);
  3221. return this;
  3222. };
  3223. /**
  3224. * Updates the current Vector3 with the maximal coordinate values between its and the given coordinates.
  3225. * @param x defines the x coordinate of the operand
  3226. * @param y defines the y coordinate of the operand
  3227. * @param z defines the z coordinate of the operand
  3228. * @returns the current updated Vector3
  3229. */
  3230. Vector3.prototype.maximizeInPlaceFromFloats = function (x, y, z) {
  3231. this.x = Math.max(this.x, x);
  3232. this.y = Math.max(this.y, y);
  3233. this.z = Math.max(this.z, z);
  3234. return this;
  3235. };
  3236. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3237. /**
  3238. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3239. */
  3240. get: function () {
  3241. var absX = Math.abs(this.x);
  3242. var absY = Math.abs(this.y);
  3243. if (absX !== absY) {
  3244. return true;
  3245. }
  3246. var absZ = Math.abs(this.z);
  3247. if (absX !== absZ) {
  3248. return true;
  3249. }
  3250. if (absY !== absZ) {
  3251. return true;
  3252. }
  3253. return false;
  3254. },
  3255. enumerable: true,
  3256. configurable: true
  3257. });
  3258. /**
  3259. * Gets a new Vector3 from current Vector3 floored values
  3260. * @returns a new Vector3
  3261. */
  3262. Vector3.prototype.floor = function () {
  3263. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3264. };
  3265. /**
  3266. * Gets a new Vector3 from current Vector3 floored values
  3267. * @returns a new Vector3
  3268. */
  3269. Vector3.prototype.fract = function () {
  3270. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3271. };
  3272. // Properties
  3273. /**
  3274. * Gets the length of the Vector3
  3275. * @returns the length of the Vecto3
  3276. */
  3277. Vector3.prototype.length = function () {
  3278. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3279. };
  3280. /**
  3281. * Gets the squared length of the Vector3
  3282. * @returns squared length of the Vector3
  3283. */
  3284. Vector3.prototype.lengthSquared = function () {
  3285. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3286. };
  3287. /**
  3288. * Normalize the current Vector3.
  3289. * Please note that this is an in place operation.
  3290. * @returns the current updated Vector3
  3291. */
  3292. Vector3.prototype.normalize = function () {
  3293. var len = this.length();
  3294. if (len === 0 || len === 1.0)
  3295. return this;
  3296. var num = 1.0 / len;
  3297. this.x *= num;
  3298. this.y *= num;
  3299. this.z *= num;
  3300. return this;
  3301. };
  3302. /**
  3303. * Normalize the current Vector3 to a new vector
  3304. * @returns the new Vector3
  3305. */
  3306. Vector3.prototype.normalizeToNew = function () {
  3307. var normalized = new Vector3(0, 0, 0);
  3308. this.normalizeToRef(normalized);
  3309. return normalized;
  3310. };
  3311. /**
  3312. * Normalize the current Vector3 to the reference
  3313. * @param reference define the Vector3 to update
  3314. * @returns the updated Vector3
  3315. */
  3316. Vector3.prototype.normalizeToRef = function (reference) {
  3317. var len = this.length();
  3318. if (len === 0 || len === 1.0) {
  3319. reference.set(this.x, this.y, this.z);
  3320. return reference;
  3321. }
  3322. var scale = 1.0 / len;
  3323. this.scaleToRef(scale, reference);
  3324. return reference;
  3325. };
  3326. /**
  3327. * Creates a new Vector3 copied from the current Vector3
  3328. * @returns the new Vector3
  3329. */
  3330. Vector3.prototype.clone = function () {
  3331. return new Vector3(this.x, this.y, this.z);
  3332. };
  3333. /**
  3334. * Copies the given vector coordinates to the current Vector3 ones
  3335. * @param source defines the source Vector3
  3336. * @returns the current updated Vector3
  3337. */
  3338. Vector3.prototype.copyFrom = function (source) {
  3339. this.x = source.x;
  3340. this.y = source.y;
  3341. this.z = source.z;
  3342. return this;
  3343. };
  3344. /**
  3345. * Copies the given floats to the current Vector3 coordinates
  3346. * @param x defines the x coordinate of the operand
  3347. * @param y defines the y coordinate of the operand
  3348. * @param z defines the z coordinate of the operand
  3349. * @returns the current updated Vector3
  3350. */
  3351. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3352. this.x = x;
  3353. this.y = y;
  3354. this.z = z;
  3355. return this;
  3356. };
  3357. /**
  3358. * Copies the given floats to the current Vector3 coordinates
  3359. * @param x defines the x coordinate of the operand
  3360. * @param y defines the y coordinate of the operand
  3361. * @param z defines the z coordinate of the operand
  3362. * @returns the current updated Vector3
  3363. */
  3364. Vector3.prototype.set = function (x, y, z) {
  3365. return this.copyFromFloats(x, y, z);
  3366. };
  3367. // Statics
  3368. /**
  3369. * Get the clip factor between two vectors
  3370. * @param vector0 defines the first operand
  3371. * @param vector1 defines the second operand
  3372. * @param axis defines the axis to use
  3373. * @param size defines the size along the axis
  3374. * @returns the clip factor
  3375. */
  3376. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3377. var d0 = Vector3.Dot(vector0, axis) - size;
  3378. var d1 = Vector3.Dot(vector1, axis) - size;
  3379. var s = d0 / (d0 - d1);
  3380. return s;
  3381. };
  3382. /**
  3383. * Get angle between two vectors
  3384. * @param vector0 angle between vector0 and vector1
  3385. * @param vector1 angle between vector0 and vector1
  3386. * @param normal direction of the normal
  3387. * @return the angle between vector0 and vector1
  3388. */
  3389. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3390. var v0 = vector0.clone().normalize();
  3391. var v1 = vector1.clone().normalize();
  3392. var dot = Vector3.Dot(v0, v1);
  3393. var n = Vector3.Cross(v0, v1);
  3394. if (Vector3.Dot(n, normal) > 0) {
  3395. return Math.acos(dot);
  3396. }
  3397. return -Math.acos(dot);
  3398. };
  3399. /**
  3400. * Returns a new Vector3 set from the index "offset" of the given array
  3401. * @param array defines the source array
  3402. * @param offset defines the offset in the source array
  3403. * @returns the new Vector3
  3404. */
  3405. Vector3.FromArray = function (array, offset) {
  3406. if (!offset) {
  3407. offset = 0;
  3408. }
  3409. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3410. };
  3411. /**
  3412. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3413. * This function is deprecated. Use FromArray instead
  3414. * @param array defines the source array
  3415. * @param offset defines the offset in the source array
  3416. * @returns the new Vector3
  3417. */
  3418. Vector3.FromFloatArray = function (array, offset) {
  3419. return Vector3.FromArray(array, offset);
  3420. };
  3421. /**
  3422. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3423. * @param array defines the source array
  3424. * @param offset defines the offset in the source array
  3425. * @param result defines the Vector3 where to store the result
  3426. */
  3427. Vector3.FromArrayToRef = function (array, offset, result) {
  3428. result.x = array[offset];
  3429. result.y = array[offset + 1];
  3430. result.z = array[offset + 2];
  3431. };
  3432. /**
  3433. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3434. * This function is deprecated. Use FromArrayToRef instead.
  3435. * @param array defines the source array
  3436. * @param offset defines the offset in the source array
  3437. * @param result defines the Vector3 where to store the result
  3438. */
  3439. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3440. return Vector3.FromArrayToRef(array, offset, result);
  3441. };
  3442. /**
  3443. * Sets the given vector "result" with the given floats.
  3444. * @param x defines the x coordinate of the source
  3445. * @param y defines the y coordinate of the source
  3446. * @param z defines the z coordinate of the source
  3447. * @param result defines the Vector3 where to store the result
  3448. */
  3449. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3450. result.x = x;
  3451. result.y = y;
  3452. result.z = z;
  3453. };
  3454. /**
  3455. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3456. * @returns a new empty Vector3
  3457. */
  3458. Vector3.Zero = function () {
  3459. return new Vector3(0.0, 0.0, 0.0);
  3460. };
  3461. /**
  3462. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3463. * @returns a new unit Vector3
  3464. */
  3465. Vector3.One = function () {
  3466. return new Vector3(1.0, 1.0, 1.0);
  3467. };
  3468. /**
  3469. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3470. * @returns a new up Vector3
  3471. */
  3472. Vector3.Up = function () {
  3473. return new Vector3(0.0, 1.0, 0.0);
  3474. };
  3475. /**
  3476. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3477. * @returns a new down Vector3
  3478. */
  3479. Vector3.Down = function () {
  3480. return new Vector3(0.0, -1.0, 0.0);
  3481. };
  3482. /**
  3483. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3484. * @returns a new forward Vector3
  3485. */
  3486. Vector3.Forward = function () {
  3487. return new Vector3(0.0, 0.0, 1.0);
  3488. };
  3489. /**
  3490. * Returns a new Vector3 set to (0.0, 0.0, -1.0)
  3491. * @returns a new forward Vector3
  3492. */
  3493. Vector3.Backward = function () {
  3494. return new Vector3(0.0, 0.0, -1.0);
  3495. };
  3496. /**
  3497. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3498. * @returns a new right Vector3
  3499. */
  3500. Vector3.Right = function () {
  3501. return new Vector3(1.0, 0.0, 0.0);
  3502. };
  3503. /**
  3504. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3505. * @returns a new left Vector3
  3506. */
  3507. Vector3.Left = function () {
  3508. return new Vector3(-1.0, 0.0, 0.0);
  3509. };
  3510. /**
  3511. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3512. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3513. * @param vector defines the Vector3 to transform
  3514. * @param transformation defines the transformation matrix
  3515. * @returns the transformed Vector3
  3516. */
  3517. Vector3.TransformCoordinates = function (vector, transformation) {
  3518. var result = Vector3.Zero();
  3519. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3520. return result;
  3521. };
  3522. /**
  3523. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3524. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3525. * @param vector defines the Vector3 to transform
  3526. * @param transformation defines the transformation matrix
  3527. * @param result defines the Vector3 where to store the result
  3528. */
  3529. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3530. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3531. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3532. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3533. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3534. result.x = x / w;
  3535. result.y = y / w;
  3536. result.z = z / w;
  3537. };
  3538. /**
  3539. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3540. * This method computes tranformed coordinates only, not transformed direction vectors
  3541. * @param x define the x coordinate of the source vector
  3542. * @param y define the y coordinate of the source vector
  3543. * @param z define the z coordinate of the source vector
  3544. * @param transformation defines the transformation matrix
  3545. * @param result defines the Vector3 where to store the result
  3546. */
  3547. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3548. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3549. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3550. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3551. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3552. result.x = rx / rw;
  3553. result.y = ry / rw;
  3554. result.z = rz / rw;
  3555. };
  3556. /**
  3557. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3558. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3559. * @param vector defines the Vector3 to transform
  3560. * @param transformation defines the transformation matrix
  3561. * @returns the new Vector3
  3562. */
  3563. Vector3.TransformNormal = function (vector, transformation) {
  3564. var result = Vector3.Zero();
  3565. Vector3.TransformNormalToRef(vector, transformation, result);
  3566. return result;
  3567. };
  3568. /**
  3569. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3570. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3571. * @param vector defines the Vector3 to transform
  3572. * @param transformation defines the transformation matrix
  3573. * @param result defines the Vector3 where to store the result
  3574. */
  3575. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3576. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3577. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3578. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3579. result.x = x;
  3580. result.y = y;
  3581. result.z = z;
  3582. };
  3583. /**
  3584. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3585. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3586. * @param x define the x coordinate of the source vector
  3587. * @param y define the y coordinate of the source vector
  3588. * @param z define the z coordinate of the source vector
  3589. * @param transformation defines the transformation matrix
  3590. * @param result defines the Vector3 where to store the result
  3591. */
  3592. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3593. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3594. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3595. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3596. };
  3597. /**
  3598. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3599. * @param value1 defines the first control point
  3600. * @param value2 defines the second control point
  3601. * @param value3 defines the third control point
  3602. * @param value4 defines the fourth control point
  3603. * @param amount defines the amount on the spline to use
  3604. * @returns the new Vector3
  3605. */
  3606. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3607. var squared = amount * amount;
  3608. var cubed = amount * squared;
  3609. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3610. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3611. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3612. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3613. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3614. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3615. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3616. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3617. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3618. return new Vector3(x, y, z);
  3619. };
  3620. /**
  3621. * 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"
  3622. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3623. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3624. * @param value defines the current value
  3625. * @param min defines the lower range value
  3626. * @param max defines the upper range value
  3627. * @returns the new Vector3
  3628. */
  3629. Vector3.Clamp = function (value, min, max) {
  3630. var x = value.x;
  3631. x = (x > max.x) ? max.x : x;
  3632. x = (x < min.x) ? min.x : x;
  3633. var y = value.y;
  3634. y = (y > max.y) ? max.y : y;
  3635. y = (y < min.y) ? min.y : y;
  3636. var z = value.z;
  3637. z = (z > max.z) ? max.z : z;
  3638. z = (z < min.z) ? min.z : z;
  3639. return new Vector3(x, y, z);
  3640. };
  3641. /**
  3642. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3643. * @param value1 defines the first control point
  3644. * @param tangent1 defines the first tangent vector
  3645. * @param value2 defines the second control point
  3646. * @param tangent2 defines the second tangent vector
  3647. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3648. * @returns the new Vector3
  3649. */
  3650. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3651. var squared = amount * amount;
  3652. var cubed = amount * squared;
  3653. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3654. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3655. var part3 = (cubed - (2.0 * squared)) + amount;
  3656. var part4 = cubed - squared;
  3657. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3658. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3659. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3660. return new Vector3(x, y, z);
  3661. };
  3662. /**
  3663. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3664. * @param start defines the start value
  3665. * @param end defines the end value
  3666. * @param amount max defines amount between both (between 0 and 1)
  3667. * @returns the new Vector3
  3668. */
  3669. Vector3.Lerp = function (start, end, amount) {
  3670. var result = new Vector3(0, 0, 0);
  3671. Vector3.LerpToRef(start, end, amount, result);
  3672. return result;
  3673. };
  3674. /**
  3675. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3676. * @param start defines the start value
  3677. * @param end defines the end value
  3678. * @param amount max defines amount between both (between 0 and 1)
  3679. * @param result defines the Vector3 where to store the result
  3680. */
  3681. Vector3.LerpToRef = function (start, end, amount, result) {
  3682. result.x = start.x + ((end.x - start.x) * amount);
  3683. result.y = start.y + ((end.y - start.y) * amount);
  3684. result.z = start.z + ((end.z - start.z) * amount);
  3685. };
  3686. /**
  3687. * Returns the dot product (float) between the vectors "left" and "right"
  3688. * @param left defines the left operand
  3689. * @param right defines the right operand
  3690. * @returns the dot product
  3691. */
  3692. Vector3.Dot = function (left, right) {
  3693. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3694. };
  3695. /**
  3696. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3697. * The cross product is then orthogonal to both "left" and "right"
  3698. * @param left defines the left operand
  3699. * @param right defines the right operand
  3700. * @returns the cross product
  3701. */
  3702. Vector3.Cross = function (left, right) {
  3703. var result = Vector3.Zero();
  3704. Vector3.CrossToRef(left, right, result);
  3705. return result;
  3706. };
  3707. /**
  3708. * Sets the given vector "result" with the cross product of "left" and "right"
  3709. * The cross product is then orthogonal to both "left" and "right"
  3710. * @param left defines the left operand
  3711. * @param right defines the right operand
  3712. * @param result defines the Vector3 where to store the result
  3713. */
  3714. Vector3.CrossToRef = function (left, right, result) {
  3715. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3716. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3717. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3718. result.copyFrom(MathTmp.Vector3[0]);
  3719. };
  3720. /**
  3721. * Returns a new Vector3 as the normalization of the given vector
  3722. * @param vector defines the Vector3 to normalize
  3723. * @returns the new Vector3
  3724. */
  3725. Vector3.Normalize = function (vector) {
  3726. var result = Vector3.Zero();
  3727. Vector3.NormalizeToRef(vector, result);
  3728. return result;
  3729. };
  3730. /**
  3731. * Sets the given vector "result" with the normalization of the given first vector
  3732. * @param vector defines the Vector3 to normalize
  3733. * @param result defines the Vector3 where to store the result
  3734. */
  3735. Vector3.NormalizeToRef = function (vector, result) {
  3736. result.copyFrom(vector);
  3737. result.normalize();
  3738. };
  3739. /**
  3740. * Project a Vector3 onto screen space
  3741. * @param vector defines the Vector3 to project
  3742. * @param world defines the world matrix to use
  3743. * @param transform defines the transform (view x projection) matrix to use
  3744. * @param viewport defines the screen viewport to use
  3745. * @returns the new Vector3
  3746. */
  3747. Vector3.Project = function (vector, world, transform, viewport) {
  3748. var cw = viewport.width;
  3749. var ch = viewport.height;
  3750. var cx = viewport.x;
  3751. var cy = viewport.y;
  3752. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3753. 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);
  3754. var matrix = MathTmp.Matrix[0];
  3755. world.multiplyToRef(transform, matrix);
  3756. matrix.multiplyToRef(viewportMatrix, matrix);
  3757. return Vector3.TransformCoordinates(vector, matrix);
  3758. };
  3759. /**
  3760. * Unproject from screen space to object space
  3761. * @param source defines the screen space Vector3 to use
  3762. * @param viewportWidth defines the current width of the viewport
  3763. * @param viewportHeight defines the current height of the viewport
  3764. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3765. * @param transform defines the transform (view x projection) matrix to use
  3766. * @returns the new Vector3
  3767. */
  3768. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3769. var matrix = MathTmp.Matrix[0];
  3770. world.multiplyToRef(transform, matrix);
  3771. matrix.invert();
  3772. source.x = source.x / viewportWidth * 2 - 1;
  3773. source.y = -(source.y / viewportHeight * 2 - 1);
  3774. var vector = Vector3.TransformCoordinates(source, matrix);
  3775. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3776. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3777. vector = vector.scale(1.0 / num);
  3778. }
  3779. return vector;
  3780. };
  3781. /**
  3782. * Unproject from screen space to object space
  3783. * @param source defines the screen space Vector3 to use
  3784. * @param viewportWidth defines the current width of the viewport
  3785. * @param viewportHeight defines the current height of the viewport
  3786. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3787. * @param view defines the view matrix to use
  3788. * @param projection defines the projection matrix to use
  3789. * @returns the new Vector3
  3790. */
  3791. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3792. var result = Vector3.Zero();
  3793. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3794. return result;
  3795. };
  3796. /**
  3797. * Unproject from screen space to object space
  3798. * @param source defines the screen space Vector3 to use
  3799. * @param viewportWidth defines the current width of the viewport
  3800. * @param viewportHeight defines the current height of the viewport
  3801. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3802. * @param view defines the view matrix to use
  3803. * @param projection defines the projection matrix to use
  3804. * @param result defines the Vector3 where to store the result
  3805. */
  3806. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3807. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3808. };
  3809. /**
  3810. * Unproject from screen space to object space
  3811. * @param sourceX defines the screen space x coordinate to use
  3812. * @param sourceY defines the screen space y coordinate to use
  3813. * @param sourceZ defines the screen space z coordinate to use
  3814. * @param viewportWidth defines the current width of the viewport
  3815. * @param viewportHeight defines the current height of the viewport
  3816. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3817. * @param view defines the view matrix to use
  3818. * @param projection defines the projection matrix to use
  3819. * @param result defines the Vector3 where to store the result
  3820. */
  3821. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3822. var matrix = MathTmp.Matrix[0];
  3823. world.multiplyToRef(view, matrix);
  3824. matrix.multiplyToRef(projection, matrix);
  3825. matrix.invert();
  3826. var screenSource = MathTmp.Vector3[0];
  3827. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3828. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3829. screenSource.z = 2 * sourceZ - 1.0;
  3830. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3831. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3832. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3833. result.scaleInPlace(1.0 / num);
  3834. }
  3835. };
  3836. /**
  3837. * Gets the minimal coordinate values between two Vector3
  3838. * @param left defines the first operand
  3839. * @param right defines the second operand
  3840. * @returns the new Vector3
  3841. */
  3842. Vector3.Minimize = function (left, right) {
  3843. var min = left.clone();
  3844. min.minimizeInPlace(right);
  3845. return min;
  3846. };
  3847. /**
  3848. * Gets the maximal coordinate values between two Vector3
  3849. * @param left defines the first operand
  3850. * @param right defines the second operand
  3851. * @returns the new Vector3
  3852. */
  3853. Vector3.Maximize = function (left, right) {
  3854. var max = left.clone();
  3855. max.maximizeInPlace(right);
  3856. return max;
  3857. };
  3858. /**
  3859. * Returns the distance between the vectors "value1" and "value2"
  3860. * @param value1 defines the first operand
  3861. * @param value2 defines the second operand
  3862. * @returns the distance
  3863. */
  3864. Vector3.Distance = function (value1, value2) {
  3865. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3866. };
  3867. /**
  3868. * Returns the squared distance between the vectors "value1" and "value2"
  3869. * @param value1 defines the first operand
  3870. * @param value2 defines the second operand
  3871. * @returns the squared distance
  3872. */
  3873. Vector3.DistanceSquared = function (value1, value2) {
  3874. var x = value1.x - value2.x;
  3875. var y = value1.y - value2.y;
  3876. var z = value1.z - value2.z;
  3877. return (x * x) + (y * y) + (z * z);
  3878. };
  3879. /**
  3880. * Returns a new Vector3 located at the center between "value1" and "value2"
  3881. * @param value1 defines the first operand
  3882. * @param value2 defines the second operand
  3883. * @returns the new Vector3
  3884. */
  3885. Vector3.Center = function (value1, value2) {
  3886. var center = value1.add(value2);
  3887. center.scaleInPlace(0.5);
  3888. return center;
  3889. };
  3890. /**
  3891. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3892. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3893. * to something in order to rotate it from its local system to the given target system
  3894. * Note: axis1, axis2 and axis3 are normalized during this operation
  3895. * @param axis1 defines the first axis
  3896. * @param axis2 defines the second axis
  3897. * @param axis3 defines the third axis
  3898. * @returns a new Vector3
  3899. */
  3900. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3901. var rotation = Vector3.Zero();
  3902. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3903. return rotation;
  3904. };
  3905. /**
  3906. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3907. * @param axis1 defines the first axis
  3908. * @param axis2 defines the second axis
  3909. * @param axis3 defines the third axis
  3910. * @param ref defines the Vector3 where to store the result
  3911. */
  3912. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3913. var quat = MathTmp.Quaternion[0];
  3914. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3915. quat.toEulerAnglesToRef(ref);
  3916. };
  3917. return Vector3;
  3918. }());
  3919. BABYLON.Vector3 = Vector3;
  3920. /**
  3921. * Vector4 class created for EulerAngle class conversion to Quaternion
  3922. */
  3923. var Vector4 = /** @class */ (function () {
  3924. /**
  3925. * Creates a Vector4 object from the given floats.
  3926. * @param x x value of the vector
  3927. * @param y y value of the vector
  3928. * @param z z value of the vector
  3929. * @param w w value of the vector
  3930. */
  3931. function Vector4(
  3932. /** x value of the vector */
  3933. x,
  3934. /** y value of the vector */
  3935. y,
  3936. /** z value of the vector */
  3937. z,
  3938. /** w value of the vector */
  3939. w) {
  3940. this.x = x;
  3941. this.y = y;
  3942. this.z = z;
  3943. this.w = w;
  3944. }
  3945. /**
  3946. * Returns the string with the Vector4 coordinates.
  3947. * @returns a string containing all the vector values
  3948. */
  3949. Vector4.prototype.toString = function () {
  3950. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3951. };
  3952. /**
  3953. * Returns the string "Vector4".
  3954. * @returns "Vector4"
  3955. */
  3956. Vector4.prototype.getClassName = function () {
  3957. return "Vector4";
  3958. };
  3959. /**
  3960. * Returns the Vector4 hash code.
  3961. * @returns a unique hash code
  3962. */
  3963. Vector4.prototype.getHashCode = function () {
  3964. var hash = this.x || 0;
  3965. hash = (hash * 397) ^ (this.y || 0);
  3966. hash = (hash * 397) ^ (this.z || 0);
  3967. hash = (hash * 397) ^ (this.w || 0);
  3968. return hash;
  3969. };
  3970. // Operators
  3971. /**
  3972. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3973. * @returns the resulting array
  3974. */
  3975. Vector4.prototype.asArray = function () {
  3976. var result = new Array();
  3977. this.toArray(result, 0);
  3978. return result;
  3979. };
  3980. /**
  3981. * Populates the given array from the given index with the Vector4 coordinates.
  3982. * @param array array to populate
  3983. * @param index index of the array to start at (default: 0)
  3984. * @returns the Vector4.
  3985. */
  3986. Vector4.prototype.toArray = function (array, index) {
  3987. if (index === undefined) {
  3988. index = 0;
  3989. }
  3990. array[index] = this.x;
  3991. array[index + 1] = this.y;
  3992. array[index + 2] = this.z;
  3993. array[index + 3] = this.w;
  3994. return this;
  3995. };
  3996. /**
  3997. * Adds the given vector to the current Vector4.
  3998. * @param otherVector the vector to add
  3999. * @returns the updated Vector4.
  4000. */
  4001. Vector4.prototype.addInPlace = function (otherVector) {
  4002. this.x += otherVector.x;
  4003. this.y += otherVector.y;
  4004. this.z += otherVector.z;
  4005. this.w += otherVector.w;
  4006. return this;
  4007. };
  4008. /**
  4009. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  4010. * @param otherVector the vector to add
  4011. * @returns the resulting vector
  4012. */
  4013. Vector4.prototype.add = function (otherVector) {
  4014. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  4015. };
  4016. /**
  4017. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  4018. * @param otherVector the vector to add
  4019. * @param result the vector to store the result
  4020. * @returns the current Vector4.
  4021. */
  4022. Vector4.prototype.addToRef = function (otherVector, result) {
  4023. result.x = this.x + otherVector.x;
  4024. result.y = this.y + otherVector.y;
  4025. result.z = this.z + otherVector.z;
  4026. result.w = this.w + otherVector.w;
  4027. return this;
  4028. };
  4029. /**
  4030. * Subtract in place the given vector from the current Vector4.
  4031. * @param otherVector the vector to subtract
  4032. * @returns the updated Vector4.
  4033. */
  4034. Vector4.prototype.subtractInPlace = function (otherVector) {
  4035. this.x -= otherVector.x;
  4036. this.y -= otherVector.y;
  4037. this.z -= otherVector.z;
  4038. this.w -= otherVector.w;
  4039. return this;
  4040. };
  4041. /**
  4042. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  4043. * @param otherVector the vector to add
  4044. * @returns the new vector with the result
  4045. */
  4046. Vector4.prototype.subtract = function (otherVector) {
  4047. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  4048. };
  4049. /**
  4050. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  4051. * @param otherVector the vector to subtract
  4052. * @param result the vector to store the result
  4053. * @returns the current Vector4.
  4054. */
  4055. Vector4.prototype.subtractToRef = function (otherVector, result) {
  4056. result.x = this.x - otherVector.x;
  4057. result.y = this.y - otherVector.y;
  4058. result.z = this.z - otherVector.z;
  4059. result.w = this.w - otherVector.w;
  4060. return this;
  4061. };
  4062. /**
  4063. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4064. */
  4065. /**
  4066. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4067. * @param x value to subtract
  4068. * @param y value to subtract
  4069. * @param z value to subtract
  4070. * @param w value to subtract
  4071. * @returns new vector containing the result
  4072. */
  4073. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  4074. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  4075. };
  4076. /**
  4077. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4078. * @param x value to subtract
  4079. * @param y value to subtract
  4080. * @param z value to subtract
  4081. * @param w value to subtract
  4082. * @param result the vector to store the result in
  4083. * @returns the current Vector4.
  4084. */
  4085. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  4086. result.x = this.x - x;
  4087. result.y = this.y - y;
  4088. result.z = this.z - z;
  4089. result.w = this.w - w;
  4090. return this;
  4091. };
  4092. /**
  4093. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  4094. * @returns a new vector with the negated values
  4095. */
  4096. Vector4.prototype.negate = function () {
  4097. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  4098. };
  4099. /**
  4100. * Multiplies the current Vector4 coordinates by scale (float).
  4101. * @param scale the number to scale with
  4102. * @returns the updated Vector4.
  4103. */
  4104. Vector4.prototype.scaleInPlace = function (scale) {
  4105. this.x *= scale;
  4106. this.y *= scale;
  4107. this.z *= scale;
  4108. this.w *= scale;
  4109. return this;
  4110. };
  4111. /**
  4112. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  4113. * @param scale the number to scale with
  4114. * @returns a new vector with the result
  4115. */
  4116. Vector4.prototype.scale = function (scale) {
  4117. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  4118. };
  4119. /**
  4120. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  4121. * @param scale the number to scale with
  4122. * @param result a vector to store the result in
  4123. * @returns the current Vector4.
  4124. */
  4125. Vector4.prototype.scaleToRef = function (scale, result) {
  4126. result.x = this.x * scale;
  4127. result.y = this.y * scale;
  4128. result.z = this.z * scale;
  4129. result.w = this.w * scale;
  4130. return this;
  4131. };
  4132. /**
  4133. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4134. * @param scale defines the scale factor
  4135. * @param result defines the Vector4 object where to store the result
  4136. * @returns the unmodified current Vector4
  4137. */
  4138. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4139. result.x += this.x * scale;
  4140. result.y += this.y * scale;
  4141. result.z += this.z * scale;
  4142. result.w += this.w * scale;
  4143. return this;
  4144. };
  4145. /**
  4146. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4147. * @param otherVector the vector to compare against
  4148. * @returns true if they are equal
  4149. */
  4150. Vector4.prototype.equals = function (otherVector) {
  4151. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4152. };
  4153. /**
  4154. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4155. * @param otherVector vector to compare against
  4156. * @param epsilon (Default: very small number)
  4157. * @returns true if they are equal
  4158. */
  4159. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4160. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4161. return otherVector
  4162. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4163. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4164. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4165. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4166. };
  4167. /**
  4168. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4169. * @param x x value to compare against
  4170. * @param y y value to compare against
  4171. * @param z z value to compare against
  4172. * @param w w value to compare against
  4173. * @returns true if equal
  4174. */
  4175. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4176. return this.x === x && this.y === y && this.z === z && this.w === w;
  4177. };
  4178. /**
  4179. * Multiplies in place the current Vector4 by the given one.
  4180. * @param otherVector vector to multiple with
  4181. * @returns the updated Vector4.
  4182. */
  4183. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4184. this.x *= otherVector.x;
  4185. this.y *= otherVector.y;
  4186. this.z *= otherVector.z;
  4187. this.w *= otherVector.w;
  4188. return this;
  4189. };
  4190. /**
  4191. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4192. * @param otherVector vector to multiple with
  4193. * @returns resulting new vector
  4194. */
  4195. Vector4.prototype.multiply = function (otherVector) {
  4196. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4197. };
  4198. /**
  4199. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4200. * @param otherVector vector to multiple with
  4201. * @param result vector to store the result
  4202. * @returns the current Vector4.
  4203. */
  4204. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4205. result.x = this.x * otherVector.x;
  4206. result.y = this.y * otherVector.y;
  4207. result.z = this.z * otherVector.z;
  4208. result.w = this.w * otherVector.w;
  4209. return this;
  4210. };
  4211. /**
  4212. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4213. * @param x x value multiply with
  4214. * @param y y value multiply with
  4215. * @param z z value multiply with
  4216. * @param w w value multiply with
  4217. * @returns resulting new vector
  4218. */
  4219. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4220. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4221. };
  4222. /**
  4223. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4224. * @param otherVector vector to devide with
  4225. * @returns resulting new vector
  4226. */
  4227. Vector4.prototype.divide = function (otherVector) {
  4228. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4229. };
  4230. /**
  4231. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4232. * @param otherVector vector to devide with
  4233. * @param result vector to store the result
  4234. * @returns the current Vector4.
  4235. */
  4236. Vector4.prototype.divideToRef = function (otherVector, result) {
  4237. result.x = this.x / otherVector.x;
  4238. result.y = this.y / otherVector.y;
  4239. result.z = this.z / otherVector.z;
  4240. result.w = this.w / otherVector.w;
  4241. return this;
  4242. };
  4243. /**
  4244. * Divides the current Vector3 coordinates by the given ones.
  4245. * @param otherVector vector to devide with
  4246. * @returns the updated Vector3.
  4247. */
  4248. Vector4.prototype.divideInPlace = function (otherVector) {
  4249. return this.divideToRef(otherVector, this);
  4250. };
  4251. /**
  4252. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4253. * @param other defines the second operand
  4254. * @returns the current updated Vector4
  4255. */
  4256. Vector4.prototype.minimizeInPlace = function (other) {
  4257. if (other.x < this.x)
  4258. this.x = other.x;
  4259. if (other.y < this.y)
  4260. this.y = other.y;
  4261. if (other.z < this.z)
  4262. this.z = other.z;
  4263. if (other.w < this.w)
  4264. this.w = other.w;
  4265. return this;
  4266. };
  4267. /**
  4268. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4269. * @param other defines the second operand
  4270. * @returns the current updated Vector4
  4271. */
  4272. Vector4.prototype.maximizeInPlace = function (other) {
  4273. if (other.x > this.x)
  4274. this.x = other.x;
  4275. if (other.y > this.y)
  4276. this.y = other.y;
  4277. if (other.z > this.z)
  4278. this.z = other.z;
  4279. if (other.w > this.w)
  4280. this.w = other.w;
  4281. return this;
  4282. };
  4283. /**
  4284. * Gets a new Vector4 from current Vector4 floored values
  4285. * @returns a new Vector4
  4286. */
  4287. Vector4.prototype.floor = function () {
  4288. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4289. };
  4290. /**
  4291. * Gets a new Vector4 from current Vector3 floored values
  4292. * @returns a new Vector4
  4293. */
  4294. Vector4.prototype.fract = function () {
  4295. 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));
  4296. };
  4297. // Properties
  4298. /**
  4299. * Returns the Vector4 length (float).
  4300. * @returns the length
  4301. */
  4302. Vector4.prototype.length = function () {
  4303. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4304. };
  4305. /**
  4306. * Returns the Vector4 squared length (float).
  4307. * @returns the length squared
  4308. */
  4309. Vector4.prototype.lengthSquared = function () {
  4310. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4311. };
  4312. // Methods
  4313. /**
  4314. * Normalizes in place the Vector4.
  4315. * @returns the updated Vector4.
  4316. */
  4317. Vector4.prototype.normalize = function () {
  4318. var len = this.length();
  4319. if (len === 0)
  4320. return this;
  4321. var num = 1.0 / len;
  4322. this.x *= num;
  4323. this.y *= num;
  4324. this.z *= num;
  4325. this.w *= num;
  4326. return this;
  4327. };
  4328. /**
  4329. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4330. * @returns this converted to a new vector3
  4331. */
  4332. Vector4.prototype.toVector3 = function () {
  4333. return new Vector3(this.x, this.y, this.z);
  4334. };
  4335. /**
  4336. * Returns a new Vector4 copied from the current one.
  4337. * @returns the new cloned vector
  4338. */
  4339. Vector4.prototype.clone = function () {
  4340. return new Vector4(this.x, this.y, this.z, this.w);
  4341. };
  4342. /**
  4343. * Updates the current Vector4 with the given one coordinates.
  4344. * @param source the source vector to copy from
  4345. * @returns the updated Vector4.
  4346. */
  4347. Vector4.prototype.copyFrom = function (source) {
  4348. this.x = source.x;
  4349. this.y = source.y;
  4350. this.z = source.z;
  4351. this.w = source.w;
  4352. return this;
  4353. };
  4354. /**
  4355. * Updates the current Vector4 coordinates with the given floats.
  4356. * @param x float to copy from
  4357. * @param y float to copy from
  4358. * @param z float to copy from
  4359. * @param w float to copy from
  4360. * @returns the updated Vector4.
  4361. */
  4362. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4363. this.x = x;
  4364. this.y = y;
  4365. this.z = z;
  4366. this.w = w;
  4367. return this;
  4368. };
  4369. /**
  4370. * Updates the current Vector4 coordinates with the given floats.
  4371. * @param x float to set from
  4372. * @param y float to set from
  4373. * @param z float to set from
  4374. * @param w float to set from
  4375. * @returns the updated Vector4.
  4376. */
  4377. Vector4.prototype.set = function (x, y, z, w) {
  4378. return this.copyFromFloats(x, y, z, w);
  4379. };
  4380. // Statics
  4381. /**
  4382. * Returns a new Vector4 set from the starting index of the given array.
  4383. * @param array the array to pull values from
  4384. * @param offset the offset into the array to start at
  4385. * @returns the new vector
  4386. */
  4387. Vector4.FromArray = function (array, offset) {
  4388. if (!offset) {
  4389. offset = 0;
  4390. }
  4391. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4392. };
  4393. /**
  4394. * Updates the given vector "result" from the starting index of the given array.
  4395. * @param array the array to pull values from
  4396. * @param offset the offset into the array to start at
  4397. * @param result the vector to store the result in
  4398. */
  4399. Vector4.FromArrayToRef = function (array, offset, result) {
  4400. result.x = array[offset];
  4401. result.y = array[offset + 1];
  4402. result.z = array[offset + 2];
  4403. result.w = array[offset + 3];
  4404. };
  4405. /**
  4406. * Updates the given vector "result" from the starting index of the given Float32Array.
  4407. * @param array the array to pull values from
  4408. * @param offset the offset into the array to start at
  4409. * @param result the vector to store the result in
  4410. */
  4411. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4412. Vector4.FromArrayToRef(array, offset, result);
  4413. };
  4414. /**
  4415. * Updates the given vector "result" coordinates from the given floats.
  4416. * @param x float to set from
  4417. * @param y float to set from
  4418. * @param z float to set from
  4419. * @param w float to set from
  4420. * @param result the vector to the floats in
  4421. */
  4422. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4423. result.x = x;
  4424. result.y = y;
  4425. result.z = z;
  4426. result.w = w;
  4427. };
  4428. /**
  4429. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4430. * @returns the new vector
  4431. */
  4432. Vector4.Zero = function () {
  4433. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4434. };
  4435. /**
  4436. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4437. * @returns the new vector
  4438. */
  4439. Vector4.One = function () {
  4440. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4441. };
  4442. /**
  4443. * Returns a new normalized Vector4 from the given one.
  4444. * @param vector the vector to normalize
  4445. * @returns the vector
  4446. */
  4447. Vector4.Normalize = function (vector) {
  4448. var result = Vector4.Zero();
  4449. Vector4.NormalizeToRef(vector, result);
  4450. return result;
  4451. };
  4452. /**
  4453. * Updates the given vector "result" from the normalization of the given one.
  4454. * @param vector the vector to normalize
  4455. * @param result the vector to store the result in
  4456. */
  4457. Vector4.NormalizeToRef = function (vector, result) {
  4458. result.copyFrom(vector);
  4459. result.normalize();
  4460. };
  4461. /**
  4462. * Returns a vector with the minimum values from the left and right vectors
  4463. * @param left left vector to minimize
  4464. * @param right right vector to minimize
  4465. * @returns a new vector with the minimum of the left and right vector values
  4466. */
  4467. Vector4.Minimize = function (left, right) {
  4468. var min = left.clone();
  4469. min.minimizeInPlace(right);
  4470. return min;
  4471. };
  4472. /**
  4473. * Returns a vector with the maximum values from the left and right vectors
  4474. * @param left left vector to maximize
  4475. * @param right right vector to maximize
  4476. * @returns a new vector with the maximum of the left and right vector values
  4477. */
  4478. Vector4.Maximize = function (left, right) {
  4479. var max = left.clone();
  4480. max.maximizeInPlace(right);
  4481. return max;
  4482. };
  4483. /**
  4484. * Returns the distance (float) between the vectors "value1" and "value2".
  4485. * @param value1 value to calulate the distance between
  4486. * @param value2 value to calulate the distance between
  4487. * @return the distance between the two vectors
  4488. */
  4489. Vector4.Distance = function (value1, value2) {
  4490. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4491. };
  4492. /**
  4493. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4494. * @param value1 value to calulate the distance between
  4495. * @param value2 value to calulate the distance between
  4496. * @return the distance between the two vectors squared
  4497. */
  4498. Vector4.DistanceSquared = function (value1, value2) {
  4499. var x = value1.x - value2.x;
  4500. var y = value1.y - value2.y;
  4501. var z = value1.z - value2.z;
  4502. var w = value1.w - value2.w;
  4503. return (x * x) + (y * y) + (z * z) + (w * w);
  4504. };
  4505. /**
  4506. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4507. * @param value1 value to calulate the center between
  4508. * @param value2 value to calulate the center between
  4509. * @return the center between the two vectors
  4510. */
  4511. Vector4.Center = function (value1, value2) {
  4512. var center = value1.add(value2);
  4513. center.scaleInPlace(0.5);
  4514. return center;
  4515. };
  4516. /**
  4517. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4518. * This methods computes transformed normalized direction vectors only.
  4519. * @param vector the vector to transform
  4520. * @param transformation the transformation matrix to apply
  4521. * @returns the new vector
  4522. */
  4523. Vector4.TransformNormal = function (vector, transformation) {
  4524. var result = Vector4.Zero();
  4525. Vector4.TransformNormalToRef(vector, transformation, result);
  4526. return result;
  4527. };
  4528. /**
  4529. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4530. * This methods computes transformed normalized direction vectors only.
  4531. * @param vector the vector to transform
  4532. * @param transformation the transformation matrix to apply
  4533. * @param result the vector to store the result in
  4534. */
  4535. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4536. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4537. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4538. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4539. result.x = x;
  4540. result.y = y;
  4541. result.z = z;
  4542. result.w = vector.w;
  4543. };
  4544. /**
  4545. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4546. * This methods computes transformed normalized direction vectors only.
  4547. * @param x value to transform
  4548. * @param y value to transform
  4549. * @param z value to transform
  4550. * @param w value to transform
  4551. * @param transformation the transformation matrix to apply
  4552. * @param result the vector to store the results in
  4553. */
  4554. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4555. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4556. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4557. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4558. result.w = w;
  4559. };
  4560. return Vector4;
  4561. }());
  4562. BABYLON.Vector4 = Vector4;
  4563. /**
  4564. * Size containing widht and height
  4565. */
  4566. var Size = /** @class */ (function () {
  4567. /**
  4568. * Creates a Size object from the given width and height (floats).
  4569. * @param width width of the new size
  4570. * @param height height of the new size
  4571. */
  4572. function Size(width, height) {
  4573. this.width = width;
  4574. this.height = height;
  4575. }
  4576. /**
  4577. * Returns a string with the Size width and height
  4578. * @returns a string with the Size width and height
  4579. */
  4580. Size.prototype.toString = function () {
  4581. return "{W: " + this.width + ", H: " + this.height + "}";
  4582. };
  4583. /**
  4584. * "Size"
  4585. * @returns the string "Size"
  4586. */
  4587. Size.prototype.getClassName = function () {
  4588. return "Size";
  4589. };
  4590. /**
  4591. * Returns the Size hash code.
  4592. * @returns a hash code for a unique width and height
  4593. */
  4594. Size.prototype.getHashCode = function () {
  4595. var hash = this.width || 0;
  4596. hash = (hash * 397) ^ (this.height || 0);
  4597. return hash;
  4598. };
  4599. /**
  4600. * Updates the current size from the given one.
  4601. * @param src the given size
  4602. */
  4603. Size.prototype.copyFrom = function (src) {
  4604. this.width = src.width;
  4605. this.height = src.height;
  4606. };
  4607. /**
  4608. * Updates in place the current Size from the given floats.
  4609. * @param width width of the new size
  4610. * @param height height of the new size
  4611. * @returns the updated Size.
  4612. */
  4613. Size.prototype.copyFromFloats = function (width, height) {
  4614. this.width = width;
  4615. this.height = height;
  4616. return this;
  4617. };
  4618. /**
  4619. * Updates in place the current Size from the given floats.
  4620. * @param width width to set
  4621. * @param height height to set
  4622. * @returns the updated Size.
  4623. */
  4624. Size.prototype.set = function (width, height) {
  4625. return this.copyFromFloats(width, height);
  4626. };
  4627. /**
  4628. * Multiplies the width and height by numbers
  4629. * @param w factor to multiple the width by
  4630. * @param h factor to multiple the height by
  4631. * @returns a new Size set with the multiplication result of the current Size and the given floats.
  4632. */
  4633. Size.prototype.multiplyByFloats = function (w, h) {
  4634. return new Size(this.width * w, this.height * h);
  4635. };
  4636. /**
  4637. * Clones the size
  4638. * @returns a new Size copied from the given one.
  4639. */
  4640. Size.prototype.clone = function () {
  4641. return new Size(this.width, this.height);
  4642. };
  4643. /**
  4644. * True if the current Size and the given one width and height are strictly equal.
  4645. * @param other the other size to compare against
  4646. * @returns True if the current Size and the given one width and height are strictly equal.
  4647. */
  4648. Size.prototype.equals = function (other) {
  4649. if (!other) {
  4650. return false;
  4651. }
  4652. return (this.width === other.width) && (this.height === other.height);
  4653. };
  4654. Object.defineProperty(Size.prototype, "surface", {
  4655. /**
  4656. * The surface of the Size : width * height (float).
  4657. */
  4658. get: function () {
  4659. return this.width * this.height;
  4660. },
  4661. enumerable: true,
  4662. configurable: true
  4663. });
  4664. /**
  4665. * Create a new size of zero
  4666. * @returns a new Size set to (0.0, 0.0)
  4667. */
  4668. Size.Zero = function () {
  4669. return new Size(0.0, 0.0);
  4670. };
  4671. /**
  4672. * Sums the width and height of two sizes
  4673. * @param otherSize size to add to this size
  4674. * @returns a new Size set as the addition result of the current Size and the given one.
  4675. */
  4676. Size.prototype.add = function (otherSize) {
  4677. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4678. return r;
  4679. };
  4680. /**
  4681. * Subtracts the width and height of two
  4682. * @param otherSize size to subtract to this size
  4683. * @returns a new Size set as the subtraction result of the given one from the current Size.
  4684. */
  4685. Size.prototype.subtract = function (otherSize) {
  4686. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4687. return r;
  4688. };
  4689. /**
  4690. * Creates a new Size set at the linear interpolation "amount" between "start" and "end"
  4691. * @param start starting size to lerp between
  4692. * @param end end size to lerp between
  4693. * @param amount amount to lerp between the start and end values
  4694. * @returns a new Size set at the linear interpolation "amount" between "start" and "end"
  4695. */
  4696. Size.Lerp = function (start, end, amount) {
  4697. var w = start.width + ((end.width - start.width) * amount);
  4698. var h = start.height + ((end.height - start.height) * amount);
  4699. return new Size(w, h);
  4700. };
  4701. return Size;
  4702. }());
  4703. BABYLON.Size = Size;
  4704. /**
  4705. * Class used to store quaternion data
  4706. * @see https://en.wikipedia.org/wiki/Quaternion
  4707. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4708. */
  4709. var Quaternion = /** @class */ (function () {
  4710. /**
  4711. * Creates a new Quaternion from the given floats
  4712. * @param x defines the first component (0 by default)
  4713. * @param y defines the second component (0 by default)
  4714. * @param z defines the third component (0 by default)
  4715. * @param w defines the fourth component (1.0 by default)
  4716. */
  4717. function Quaternion(
  4718. /** defines the first component (0 by default) */
  4719. x,
  4720. /** defines the second component (0 by default) */
  4721. y,
  4722. /** defines the third component (0 by default) */
  4723. z,
  4724. /** defines the fourth component (1.0 by default) */
  4725. w) {
  4726. if (x === void 0) { x = 0.0; }
  4727. if (y === void 0) { y = 0.0; }
  4728. if (z === void 0) { z = 0.0; }
  4729. if (w === void 0) { w = 1.0; }
  4730. this.x = x;
  4731. this.y = y;
  4732. this.z = z;
  4733. this.w = w;
  4734. }
  4735. /**
  4736. * Gets a string representation for the current quaternion
  4737. * @returns a string with the Quaternion coordinates
  4738. */
  4739. Quaternion.prototype.toString = function () {
  4740. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4741. };
  4742. /**
  4743. * Gets the class name of the quaternion
  4744. * @returns the string "Quaternion"
  4745. */
  4746. Quaternion.prototype.getClassName = function () {
  4747. return "Quaternion";
  4748. };
  4749. /**
  4750. * Gets a hash code for this quaternion
  4751. * @returns the quaternion hash code
  4752. */
  4753. Quaternion.prototype.getHashCode = function () {
  4754. var hash = this.x || 0;
  4755. hash = (hash * 397) ^ (this.y || 0);
  4756. hash = (hash * 397) ^ (this.z || 0);
  4757. hash = (hash * 397) ^ (this.w || 0);
  4758. return hash;
  4759. };
  4760. /**
  4761. * Copy the quaternion to an array
  4762. * @returns a new array populated with 4 elements from the quaternion coordinates
  4763. */
  4764. Quaternion.prototype.asArray = function () {
  4765. return [this.x, this.y, this.z, this.w];
  4766. };
  4767. /**
  4768. * Check if two quaternions are equals
  4769. * @param otherQuaternion defines the second operand
  4770. * @return true if the current quaternion and the given one coordinates are strictly equals
  4771. */
  4772. Quaternion.prototype.equals = function (otherQuaternion) {
  4773. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4774. };
  4775. /**
  4776. * Clone the current quaternion
  4777. * @returns a new quaternion copied from the current one
  4778. */
  4779. Quaternion.prototype.clone = function () {
  4780. return new Quaternion(this.x, this.y, this.z, this.w);
  4781. };
  4782. /**
  4783. * Copy a quaternion to the current one
  4784. * @param other defines the other quaternion
  4785. * @returns the updated current quaternion
  4786. */
  4787. Quaternion.prototype.copyFrom = function (other) {
  4788. this.x = other.x;
  4789. this.y = other.y;
  4790. this.z = other.z;
  4791. this.w = other.w;
  4792. return this;
  4793. };
  4794. /**
  4795. * Updates the current quaternion with the given float coordinates
  4796. * @param x defines the x coordinate
  4797. * @param y defines the y coordinate
  4798. * @param z defines the z coordinate
  4799. * @param w defines the w coordinate
  4800. * @returns the updated current quaternion
  4801. */
  4802. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4803. this.x = x;
  4804. this.y = y;
  4805. this.z = z;
  4806. this.w = w;
  4807. return this;
  4808. };
  4809. /**
  4810. * Updates the current quaternion from the given float coordinates
  4811. * @param x defines the x coordinate
  4812. * @param y defines the y coordinate
  4813. * @param z defines the z coordinate
  4814. * @param w defines the w coordinate
  4815. * @returns the updated current quaternion
  4816. */
  4817. Quaternion.prototype.set = function (x, y, z, w) {
  4818. return this.copyFromFloats(x, y, z, w);
  4819. };
  4820. /**
  4821. * Adds two quaternions
  4822. * @param other defines the second operand
  4823. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4824. */
  4825. Quaternion.prototype.add = function (other) {
  4826. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4827. };
  4828. /**
  4829. * Add a quaternion to the current one
  4830. * @param other defines the quaternion to add
  4831. * @returns the current quaternion
  4832. */
  4833. Quaternion.prototype.addInPlace = function (other) {
  4834. this.x += other.x;
  4835. this.y += other.y;
  4836. this.z += other.z;
  4837. this.w += other.w;
  4838. return this;
  4839. };
  4840. /**
  4841. * Subtract two quaternions
  4842. * @param other defines the second operand
  4843. * @returns a new quaternion as the subtraction result of the given one from the current one
  4844. */
  4845. Quaternion.prototype.subtract = function (other) {
  4846. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4847. };
  4848. /**
  4849. * Multiplies the current quaternion by a scale factor
  4850. * @param value defines the scale factor
  4851. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4852. */
  4853. Quaternion.prototype.scale = function (value) {
  4854. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4855. };
  4856. /**
  4857. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4858. * @param scale defines the scale factor
  4859. * @param result defines the Quaternion object where to store the result
  4860. * @returns the unmodified current quaternion
  4861. */
  4862. Quaternion.prototype.scaleToRef = function (scale, result) {
  4863. result.x = this.x * scale;
  4864. result.y = this.y * scale;
  4865. result.z = this.z * scale;
  4866. result.w = this.w * scale;
  4867. return this;
  4868. };
  4869. /**
  4870. * Multiplies in place the current quaternion by a scale factor
  4871. * @param value defines the scale factor
  4872. * @returns the current modified quaternion
  4873. */
  4874. Quaternion.prototype.scaleInPlace = function (value) {
  4875. this.x *= value;
  4876. this.y *= value;
  4877. this.z *= value;
  4878. this.w *= value;
  4879. return this;
  4880. };
  4881. /**
  4882. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4883. * @param scale defines the scale factor
  4884. * @param result defines the Quaternion object where to store the result
  4885. * @returns the unmodified current quaternion
  4886. */
  4887. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4888. result.x += this.x * scale;
  4889. result.y += this.y * scale;
  4890. result.z += this.z * scale;
  4891. result.w += this.w * scale;
  4892. return this;
  4893. };
  4894. /**
  4895. * Multiplies two quaternions
  4896. * @param q1 defines the second operand
  4897. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4898. */
  4899. Quaternion.prototype.multiply = function (q1) {
  4900. var result = new Quaternion(0, 0, 0, 1.0);
  4901. this.multiplyToRef(q1, result);
  4902. return result;
  4903. };
  4904. /**
  4905. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4906. * @param q1 defines the second operand
  4907. * @param result defines the target quaternion
  4908. * @returns the current quaternion
  4909. */
  4910. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4911. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4912. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4913. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4914. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4915. result.copyFromFloats(x, y, z, w);
  4916. return this;
  4917. };
  4918. /**
  4919. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4920. * @param q1 defines the second operand
  4921. * @returns the currentupdated quaternion
  4922. */
  4923. Quaternion.prototype.multiplyInPlace = function (q1) {
  4924. this.multiplyToRef(q1, this);
  4925. return this;
  4926. };
  4927. /**
  4928. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4929. * @param ref defines the target quaternion
  4930. * @returns the current quaternion
  4931. */
  4932. Quaternion.prototype.conjugateToRef = function (ref) {
  4933. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4934. return this;
  4935. };
  4936. /**
  4937. * Conjugates in place (1-q) the current quaternion
  4938. * @returns the current updated quaternion
  4939. */
  4940. Quaternion.prototype.conjugateInPlace = function () {
  4941. this.x *= -1;
  4942. this.y *= -1;
  4943. this.z *= -1;
  4944. return this;
  4945. };
  4946. /**
  4947. * Conjugates in place (1-q) the current quaternion
  4948. * @returns a new quaternion
  4949. */
  4950. Quaternion.prototype.conjugate = function () {
  4951. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4952. return result;
  4953. };
  4954. /**
  4955. * Gets length of current quaternion
  4956. * @returns the quaternion length (float)
  4957. */
  4958. Quaternion.prototype.length = function () {
  4959. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4960. };
  4961. /**
  4962. * Normalize in place the current quaternion
  4963. * @returns the current updated quaternion
  4964. */
  4965. Quaternion.prototype.normalize = function () {
  4966. var length = 1.0 / this.length();
  4967. this.x *= length;
  4968. this.y *= length;
  4969. this.z *= length;
  4970. this.w *= length;
  4971. return this;
  4972. };
  4973. /**
  4974. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4975. * @param order is a reserved parameter and is ignore for now
  4976. * @returns a new Vector3 containing the Euler angles
  4977. */
  4978. Quaternion.prototype.toEulerAngles = function (order) {
  4979. if (order === void 0) { order = "YZX"; }
  4980. var result = Vector3.Zero();
  4981. this.toEulerAnglesToRef(result, order);
  4982. return result;
  4983. };
  4984. /**
  4985. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4986. * @param result defines the vector which will be filled with the Euler angles
  4987. * @param order is a reserved parameter and is ignore for now
  4988. * @returns the current unchanged quaternion
  4989. */
  4990. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4991. if (order === void 0) { order = "YZX"; }
  4992. var qz = this.z;
  4993. var qx = this.x;
  4994. var qy = this.y;
  4995. var qw = this.w;
  4996. var sqw = qw * qw;
  4997. var sqz = qz * qz;
  4998. var sqx = qx * qx;
  4999. var sqy = qy * qy;
  5000. var zAxisY = qy * qz - qx * qw;
  5001. var limit = .4999999;
  5002. if (zAxisY < -limit) {
  5003. result.y = 2 * Math.atan2(qy, qw);
  5004. result.x = Math.PI / 2;
  5005. result.z = 0;
  5006. }
  5007. else if (zAxisY > limit) {
  5008. result.y = 2 * Math.atan2(qy, qw);
  5009. result.x = -Math.PI / 2;
  5010. result.z = 0;
  5011. }
  5012. else {
  5013. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  5014. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  5015. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  5016. }
  5017. return this;
  5018. };
  5019. /**
  5020. * Updates the given rotation matrix with the current quaternion values
  5021. * @param result defines the target matrix
  5022. * @returns the current unchanged quaternion
  5023. */
  5024. Quaternion.prototype.toRotationMatrix = function (result) {
  5025. var xx = this.x * this.x;
  5026. var yy = this.y * this.y;
  5027. var zz = this.z * this.z;
  5028. var xy = this.x * this.y;
  5029. var zw = this.z * this.w;
  5030. var zx = this.z * this.x;
  5031. var yw = this.y * this.w;
  5032. var yz = this.y * this.z;
  5033. var xw = this.x * this.w;
  5034. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5035. result.m[1] = 2.0 * (xy + zw);
  5036. result.m[2] = 2.0 * (zx - yw);
  5037. result.m[3] = 0;
  5038. result.m[4] = 2.0 * (xy - zw);
  5039. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5040. result.m[6] = 2.0 * (yz + xw);
  5041. result.m[7] = 0;
  5042. result.m[8] = 2.0 * (zx + yw);
  5043. result.m[9] = 2.0 * (yz - xw);
  5044. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5045. result.m[11] = 0;
  5046. result.m[12] = 0;
  5047. result.m[13] = 0;
  5048. result.m[14] = 0;
  5049. result.m[15] = 1.0;
  5050. result._markAsUpdated();
  5051. return this;
  5052. };
  5053. /**
  5054. * Updates the current quaternion from the given rotation matrix values
  5055. * @param matrix defines the source matrix
  5056. * @returns the current updated quaternion
  5057. */
  5058. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  5059. Quaternion.FromRotationMatrixToRef(matrix, this);
  5060. return this;
  5061. };
  5062. // Statics
  5063. /**
  5064. * Creates a new quaternion from a rotation matrix
  5065. * @param matrix defines the source matrix
  5066. * @returns a new quaternion created from the given rotation matrix values
  5067. */
  5068. Quaternion.FromRotationMatrix = function (matrix) {
  5069. var result = new Quaternion();
  5070. Quaternion.FromRotationMatrixToRef(matrix, result);
  5071. return result;
  5072. };
  5073. /**
  5074. * Updates the given quaternion with the given rotation matrix values
  5075. * @param matrix defines the source matrix
  5076. * @param result defines the target quaternion
  5077. */
  5078. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  5079. var data = matrix.m;
  5080. var m11 = data[0], m12 = data[4], m13 = data[8];
  5081. var m21 = data[1], m22 = data[5], m23 = data[9];
  5082. var m31 = data[2], m32 = data[6], m33 = data[10];
  5083. var trace = m11 + m22 + m33;
  5084. var s;
  5085. if (trace > 0) {
  5086. s = 0.5 / Math.sqrt(trace + 1.0);
  5087. result.w = 0.25 / s;
  5088. result.x = (m32 - m23) * s;
  5089. result.y = (m13 - m31) * s;
  5090. result.z = (m21 - m12) * s;
  5091. }
  5092. else if (m11 > m22 && m11 > m33) {
  5093. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  5094. result.w = (m32 - m23) / s;
  5095. result.x = 0.25 * s;
  5096. result.y = (m12 + m21) / s;
  5097. result.z = (m13 + m31) / s;
  5098. }
  5099. else if (m22 > m33) {
  5100. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  5101. result.w = (m13 - m31) / s;
  5102. result.x = (m12 + m21) / s;
  5103. result.y = 0.25 * s;
  5104. result.z = (m23 + m32) / s;
  5105. }
  5106. else {
  5107. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  5108. result.w = (m21 - m12) / s;
  5109. result.x = (m13 + m31) / s;
  5110. result.y = (m23 + m32) / s;
  5111. result.z = 0.25 * s;
  5112. }
  5113. };
  5114. /**
  5115. * Returns the dot product (float) between the quaternions "left" and "right"
  5116. * @param left defines the left operand
  5117. * @param right defines the right operand
  5118. * @returns the dot product
  5119. */
  5120. Quaternion.Dot = function (left, right) {
  5121. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  5122. };
  5123. /**
  5124. * Checks if the two quaternions are close to each other
  5125. * @param quat0 defines the first quaternion to check
  5126. * @param quat1 defines the second quaternion to check
  5127. * @returns true if the two quaternions are close to each other
  5128. */
  5129. Quaternion.AreClose = function (quat0, quat1) {
  5130. var dot = Quaternion.Dot(quat0, quat1);
  5131. return dot >= 0;
  5132. };
  5133. /**
  5134. * Creates an empty quaternion
  5135. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  5136. */
  5137. Quaternion.Zero = function () {
  5138. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  5139. };
  5140. /**
  5141. * Inverse a given quaternion
  5142. * @param q defines the source quaternion
  5143. * @returns a new quaternion as the inverted current quaternion
  5144. */
  5145. Quaternion.Inverse = function (q) {
  5146. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  5147. };
  5148. /**
  5149. * Creates an identity quaternion
  5150. * @returns the identity quaternion
  5151. */
  5152. Quaternion.Identity = function () {
  5153. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  5154. };
  5155. /**
  5156. * Gets a boolean indicating if the given quaternion is identity
  5157. * @param quaternion defines the quaternion to check
  5158. * @returns true if the quaternion is identity
  5159. */
  5160. Quaternion.IsIdentity = function (quaternion) {
  5161. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  5162. };
  5163. /**
  5164. * Creates a quaternion from a rotation around an axis
  5165. * @param axis defines the axis to use
  5166. * @param angle defines the angle to use
  5167. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  5168. */
  5169. Quaternion.RotationAxis = function (axis, angle) {
  5170. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  5171. };
  5172. /**
  5173. * Creates a rotation around an axis and stores it into the given quaternion
  5174. * @param axis defines the axis to use
  5175. * @param angle defines the angle to use
  5176. * @param result defines the target quaternion
  5177. * @returns the target quaternion
  5178. */
  5179. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  5180. var sin = Math.sin(angle / 2);
  5181. axis.normalize();
  5182. result.w = Math.cos(angle / 2);
  5183. result.x = axis.x * sin;
  5184. result.y = axis.y * sin;
  5185. result.z = axis.z * sin;
  5186. return result;
  5187. };
  5188. /**
  5189. * Creates a new quaternion from data stored into an array
  5190. * @param array defines the data source
  5191. * @param offset defines the offset in the source array where the data starts
  5192. * @returns a new quaternion
  5193. */
  5194. Quaternion.FromArray = function (array, offset) {
  5195. if (!offset) {
  5196. offset = 0;
  5197. }
  5198. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  5199. };
  5200. /**
  5201. * Creates a new quaternion from the given Euler float angles (y, x, z)
  5202. * @param yaw defines the rotation around Y axis
  5203. * @param pitch defines the rotation around X axis
  5204. * @param roll defines the rotation around Z axis
  5205. * @returns the new quaternion
  5206. */
  5207. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5208. var q = new Quaternion();
  5209. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  5210. return q;
  5211. };
  5212. /**
  5213. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  5214. * @param yaw defines the rotation around Y axis
  5215. * @param pitch defines the rotation around X axis
  5216. * @param roll defines the rotation around Z axis
  5217. * @param result defines the target quaternion
  5218. */
  5219. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5220. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  5221. var halfRoll = roll * 0.5;
  5222. var halfPitch = pitch * 0.5;
  5223. var halfYaw = yaw * 0.5;
  5224. var sinRoll = Math.sin(halfRoll);
  5225. var cosRoll = Math.cos(halfRoll);
  5226. var sinPitch = Math.sin(halfPitch);
  5227. var cosPitch = Math.cos(halfPitch);
  5228. var sinYaw = Math.sin(halfYaw);
  5229. var cosYaw = Math.cos(halfYaw);
  5230. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  5231. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  5232. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  5233. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  5234. };
  5235. /**
  5236. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  5237. * @param alpha defines the rotation around first axis
  5238. * @param beta defines the rotation around second axis
  5239. * @param gamma defines the rotation around third axis
  5240. * @returns the new quaternion
  5241. */
  5242. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  5243. var result = new Quaternion();
  5244. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  5245. return result;
  5246. };
  5247. /**
  5248. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  5249. * @param alpha defines the rotation around first axis
  5250. * @param beta defines the rotation around second axis
  5251. * @param gamma defines the rotation around third axis
  5252. * @param result defines the target quaternion
  5253. */
  5254. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  5255. // Produces a quaternion from Euler angles in the z-x-z orientation
  5256. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  5257. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  5258. var halfBeta = beta * 0.5;
  5259. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5260. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5261. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5262. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5263. };
  5264. /**
  5265. * 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)
  5266. * @param axis1 defines the first axis
  5267. * @param axis2 defines the second axis
  5268. * @param axis3 defines the third axis
  5269. * @returns the new quaternion
  5270. */
  5271. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5272. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5273. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5274. return quat;
  5275. };
  5276. /**
  5277. * 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
  5278. * @param axis1 defines the first axis
  5279. * @param axis2 defines the second axis
  5280. * @param axis3 defines the third axis
  5281. * @param ref defines the target quaternion
  5282. */
  5283. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5284. var rotMat = MathTmp.Matrix[0];
  5285. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5286. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5287. };
  5288. /**
  5289. * Interpolates between two quaternions
  5290. * @param left defines first quaternion
  5291. * @param right defines second quaternion
  5292. * @param amount defines the gradient to use
  5293. * @returns the new interpolated quaternion
  5294. */
  5295. Quaternion.Slerp = function (left, right, amount) {
  5296. var result = Quaternion.Identity();
  5297. Quaternion.SlerpToRef(left, right, amount, result);
  5298. return result;
  5299. };
  5300. /**
  5301. * Interpolates between two quaternions and stores it into a target quaternion
  5302. * @param left defines first quaternion
  5303. * @param right defines second quaternion
  5304. * @param amount defines the gradient to use
  5305. * @param result defines the target quaternion
  5306. */
  5307. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5308. var num2;
  5309. var num3;
  5310. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5311. var flag = false;
  5312. if (num4 < 0) {
  5313. flag = true;
  5314. num4 = -num4;
  5315. }
  5316. if (num4 > 0.999999) {
  5317. num3 = 1 - amount;
  5318. num2 = flag ? -amount : amount;
  5319. }
  5320. else {
  5321. var num5 = Math.acos(num4);
  5322. var num6 = (1.0 / Math.sin(num5));
  5323. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5324. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5325. }
  5326. result.x = (num3 * left.x) + (num2 * right.x);
  5327. result.y = (num3 * left.y) + (num2 * right.y);
  5328. result.z = (num3 * left.z) + (num2 * right.z);
  5329. result.w = (num3 * left.w) + (num2 * right.w);
  5330. };
  5331. /**
  5332. * Interpolate between two quaternions using Hermite interpolation
  5333. * @param value1 defines first quaternion
  5334. * @param tangent1 defines the incoming tangent
  5335. * @param value2 defines second quaternion
  5336. * @param tangent2 defines the outgoing tangent
  5337. * @param amount defines the target quaternion
  5338. * @returns the new interpolated quaternion
  5339. */
  5340. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5341. var squared = amount * amount;
  5342. var cubed = amount * squared;
  5343. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5344. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5345. var part3 = (cubed - (2.0 * squared)) + amount;
  5346. var part4 = cubed - squared;
  5347. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5348. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5349. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5350. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5351. return new Quaternion(x, y, z, w);
  5352. };
  5353. return Quaternion;
  5354. }());
  5355. BABYLON.Quaternion = Quaternion;
  5356. /**
  5357. * Class used to store matrix data (4x4)
  5358. */
  5359. var Matrix = /** @class */ (function () {
  5360. /**
  5361. * Creates an empty matrix (filled with zeros)
  5362. */
  5363. function Matrix() {
  5364. this._isIdentity = false;
  5365. this._isIdentityDirty = true;
  5366. /**
  5367. * Gets or sets the internal data of the matrix
  5368. */
  5369. this.m = new Float32Array(16);
  5370. this._markAsUpdated();
  5371. }
  5372. /** @hidden */
  5373. Matrix.prototype._markAsUpdated = function () {
  5374. this.updateFlag = Matrix._updateFlagSeed++;
  5375. this._isIdentityDirty = true;
  5376. };
  5377. // Properties
  5378. /**
  5379. * Check if the current matrix is indentity
  5380. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5381. * @returns true is the matrix is the identity matrix
  5382. */
  5383. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5384. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5385. if (this._isIdentityDirty) {
  5386. this._isIdentityDirty = false;
  5387. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5388. this._isIdentity = false;
  5389. }
  5390. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5391. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5392. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5393. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5394. this._isIdentity = false;
  5395. }
  5396. else {
  5397. this._isIdentity = true;
  5398. }
  5399. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5400. this._isIdentity = false;
  5401. }
  5402. }
  5403. return this._isIdentity;
  5404. };
  5405. /**
  5406. * Gets the determinant of the matrix
  5407. * @returns the matrix determinant
  5408. */
  5409. Matrix.prototype.determinant = function () {
  5410. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5411. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5412. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5413. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5414. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5415. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5416. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5417. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5418. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5419. };
  5420. // Methods
  5421. /**
  5422. * Returns the matrix as a Float32Array
  5423. * @returns the matrix underlying array
  5424. */
  5425. Matrix.prototype.toArray = function () {
  5426. return this.m;
  5427. };
  5428. /**
  5429. * Returns the matrix as a Float32Array
  5430. * @returns the matrix underlying array.
  5431. */
  5432. Matrix.prototype.asArray = function () {
  5433. return this.toArray();
  5434. };
  5435. /**
  5436. * Inverts the current matrix in place
  5437. * @returns the current inverted matrix
  5438. */
  5439. Matrix.prototype.invert = function () {
  5440. this.invertToRef(this);
  5441. return this;
  5442. };
  5443. /**
  5444. * Sets all the matrix elements to zero
  5445. * @returns the current matrix
  5446. */
  5447. Matrix.prototype.reset = function () {
  5448. for (var index = 0; index < 16; index++) {
  5449. this.m[index] = 0.0;
  5450. }
  5451. this._markAsUpdated();
  5452. return this;
  5453. };
  5454. /**
  5455. * Adds the current matrix with a second one
  5456. * @param other defines the matrix to add
  5457. * @returns a new matrix as the addition of the current matrix and the given one
  5458. */
  5459. Matrix.prototype.add = function (other) {
  5460. var result = new Matrix();
  5461. this.addToRef(other, result);
  5462. return result;
  5463. };
  5464. /**
  5465. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5466. * @param other defines the matrix to add
  5467. * @param result defines the target matrix
  5468. * @returns the current matrix
  5469. */
  5470. Matrix.prototype.addToRef = function (other, result) {
  5471. for (var index = 0; index < 16; index++) {
  5472. result.m[index] = this.m[index] + other.m[index];
  5473. }
  5474. result._markAsUpdated();
  5475. return this;
  5476. };
  5477. /**
  5478. * Adds in place the given matrix to the current matrix
  5479. * @param other defines the second operand
  5480. * @returns the current updated matrix
  5481. */
  5482. Matrix.prototype.addToSelf = function (other) {
  5483. for (var index = 0; index < 16; index++) {
  5484. this.m[index] += other.m[index];
  5485. }
  5486. this._markAsUpdated();
  5487. return this;
  5488. };
  5489. /**
  5490. * Sets the given matrix to the current inverted Matrix
  5491. * @param other defines the target matrix
  5492. * @returns the unmodified current matrix
  5493. */
  5494. Matrix.prototype.invertToRef = function (other) {
  5495. var l1 = this.m[0];
  5496. var l2 = this.m[1];
  5497. var l3 = this.m[2];
  5498. var l4 = this.m[3];
  5499. var l5 = this.m[4];
  5500. var l6 = this.m[5];
  5501. var l7 = this.m[6];
  5502. var l8 = this.m[7];
  5503. var l9 = this.m[8];
  5504. var l10 = this.m[9];
  5505. var l11 = this.m[10];
  5506. var l12 = this.m[11];
  5507. var l13 = this.m[12];
  5508. var l14 = this.m[13];
  5509. var l15 = this.m[14];
  5510. var l16 = this.m[15];
  5511. var l17 = (l11 * l16) - (l12 * l15);
  5512. var l18 = (l10 * l16) - (l12 * l14);
  5513. var l19 = (l10 * l15) - (l11 * l14);
  5514. var l20 = (l9 * l16) - (l12 * l13);
  5515. var l21 = (l9 * l15) - (l11 * l13);
  5516. var l22 = (l9 * l14) - (l10 * l13);
  5517. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5518. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5519. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5520. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5521. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5522. var l28 = (l7 * l16) - (l8 * l15);
  5523. var l29 = (l6 * l16) - (l8 * l14);
  5524. var l30 = (l6 * l15) - (l7 * l14);
  5525. var l31 = (l5 * l16) - (l8 * l13);
  5526. var l32 = (l5 * l15) - (l7 * l13);
  5527. var l33 = (l5 * l14) - (l6 * l13);
  5528. var l34 = (l7 * l12) - (l8 * l11);
  5529. var l35 = (l6 * l12) - (l8 * l10);
  5530. var l36 = (l6 * l11) - (l7 * l10);
  5531. var l37 = (l5 * l12) - (l8 * l9);
  5532. var l38 = (l5 * l11) - (l7 * l9);
  5533. var l39 = (l5 * l10) - (l6 * l9);
  5534. other.m[0] = l23 * l27;
  5535. other.m[4] = l24 * l27;
  5536. other.m[8] = l25 * l27;
  5537. other.m[12] = l26 * l27;
  5538. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5539. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5540. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5541. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5542. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5543. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5544. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5545. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5546. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5547. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5548. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5549. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5550. other._markAsUpdated();
  5551. return this;
  5552. };
  5553. /**
  5554. * Inserts the translation vector (using 3 floats) in the current matrix
  5555. * @param x defines the 1st component of the translation
  5556. * @param y defines the 2nd component of the translation
  5557. * @param z defines the 3rd component of the translation
  5558. * @returns the current updated matrix
  5559. */
  5560. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5561. this.m[12] = x;
  5562. this.m[13] = y;
  5563. this.m[14] = z;
  5564. this._markAsUpdated();
  5565. return this;
  5566. };
  5567. /**
  5568. * Inserts the translation vector in the current matrix
  5569. * @param vector3 defines the translation to insert
  5570. * @returns the current updated matrix
  5571. */
  5572. Matrix.prototype.setTranslation = function (vector3) {
  5573. this.m[12] = vector3.x;
  5574. this.m[13] = vector3.y;
  5575. this.m[14] = vector3.z;
  5576. this._markAsUpdated();
  5577. return this;
  5578. };
  5579. /**
  5580. * Gets the translation value of the current matrix
  5581. * @returns a new Vector3 as the extracted translation from the matrix
  5582. */
  5583. Matrix.prototype.getTranslation = function () {
  5584. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5585. };
  5586. /**
  5587. * Fill a Vector3 with the extracted translation from the matrix
  5588. * @param result defines the Vector3 where to store the translation
  5589. * @returns the current matrix
  5590. */
  5591. Matrix.prototype.getTranslationToRef = function (result) {
  5592. result.x = this.m[12];
  5593. result.y = this.m[13];
  5594. result.z = this.m[14];
  5595. return this;
  5596. };
  5597. /**
  5598. * Remove rotation and scaling part from the matrix
  5599. * @returns the updated matrix
  5600. */
  5601. Matrix.prototype.removeRotationAndScaling = function () {
  5602. this.setRowFromFloats(0, 1, 0, 0, 0);
  5603. this.setRowFromFloats(1, 0, 1, 0, 0);
  5604. this.setRowFromFloats(2, 0, 0, 1, 0);
  5605. return this;
  5606. };
  5607. /**
  5608. * Multiply two matrices
  5609. * @param other defines the second operand
  5610. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5611. */
  5612. Matrix.prototype.multiply = function (other) {
  5613. var result = new Matrix();
  5614. this.multiplyToRef(other, result);
  5615. return result;
  5616. };
  5617. /**
  5618. * Copy the current matrix from the given one
  5619. * @param other defines the source matrix
  5620. * @returns the current updated matrix
  5621. */
  5622. Matrix.prototype.copyFrom = function (other) {
  5623. for (var index = 0; index < 16; index++) {
  5624. this.m[index] = other.m[index];
  5625. }
  5626. this._markAsUpdated();
  5627. return this;
  5628. };
  5629. /**
  5630. * Populates the given array from the starting index with the current matrix values
  5631. * @param array defines the target array
  5632. * @param offset defines the offset in the target array where to start storing values
  5633. * @returns the current matrix
  5634. */
  5635. Matrix.prototype.copyToArray = function (array, offset) {
  5636. if (offset === void 0) { offset = 0; }
  5637. for (var index = 0; index < 16; index++) {
  5638. array[offset + index] = this.m[index];
  5639. }
  5640. return this;
  5641. };
  5642. /**
  5643. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5644. * @param other defines the second operand
  5645. * @param result defines the matrix where to store the multiplication
  5646. * @returns the current matrix
  5647. */
  5648. Matrix.prototype.multiplyToRef = function (other, result) {
  5649. this.multiplyToArray(other, result.m, 0);
  5650. result._markAsUpdated();
  5651. return this;
  5652. };
  5653. /**
  5654. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5655. * @param other defines the second operand
  5656. * @param result defines the array where to store the multiplication
  5657. * @param offset defines the offset in the target array where to start storing values
  5658. * @returns the current matrix
  5659. */
  5660. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5661. var tm0 = this.m[0];
  5662. var tm1 = this.m[1];
  5663. var tm2 = this.m[2];
  5664. var tm3 = this.m[3];
  5665. var tm4 = this.m[4];
  5666. var tm5 = this.m[5];
  5667. var tm6 = this.m[6];
  5668. var tm7 = this.m[7];
  5669. var tm8 = this.m[8];
  5670. var tm9 = this.m[9];
  5671. var tm10 = this.m[10];
  5672. var tm11 = this.m[11];
  5673. var tm12 = this.m[12];
  5674. var tm13 = this.m[13];
  5675. var tm14 = this.m[14];
  5676. var tm15 = this.m[15];
  5677. var om0 = other.m[0];
  5678. var om1 = other.m[1];
  5679. var om2 = other.m[2];
  5680. var om3 = other.m[3];
  5681. var om4 = other.m[4];
  5682. var om5 = other.m[5];
  5683. var om6 = other.m[6];
  5684. var om7 = other.m[7];
  5685. var om8 = other.m[8];
  5686. var om9 = other.m[9];
  5687. var om10 = other.m[10];
  5688. var om11 = other.m[11];
  5689. var om12 = other.m[12];
  5690. var om13 = other.m[13];
  5691. var om14 = other.m[14];
  5692. var om15 = other.m[15];
  5693. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5694. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5695. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5696. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5697. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5698. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5699. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5700. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5701. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5702. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5703. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5704. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5705. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5706. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5707. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5708. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5709. return this;
  5710. };
  5711. /**
  5712. * Check equality between this matrix and a second one
  5713. * @param value defines the second matrix to compare
  5714. * @returns true is the current matrix and the given one values are strictly equal
  5715. */
  5716. Matrix.prototype.equals = function (value) {
  5717. return value &&
  5718. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5719. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5720. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5721. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5722. };
  5723. /**
  5724. * Clone the current matrix
  5725. * @returns a new matrix from the current matrix
  5726. */
  5727. Matrix.prototype.clone = function () {
  5728. 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]);
  5729. };
  5730. /**
  5731. * Returns the name of the current matrix class
  5732. * @returns the string "Matrix"
  5733. */
  5734. Matrix.prototype.getClassName = function () {
  5735. return "Matrix";
  5736. };
  5737. /**
  5738. * Gets the hash code of the current matrix
  5739. * @returns the hash code
  5740. */
  5741. Matrix.prototype.getHashCode = function () {
  5742. var hash = this.m[0] || 0;
  5743. for (var i = 1; i < 16; i++) {
  5744. hash = (hash * 397) ^ (this.m[i] || 0);
  5745. }
  5746. return hash;
  5747. };
  5748. /**
  5749. * Decomposes the current Matrix into a translation, rotation and scaling components
  5750. * @param scale defines the scale vector3 given as a reference to update
  5751. * @param rotation defines the rotation quaternion given as a reference to update
  5752. * @param translation defines the translation vector3 given as a reference to update
  5753. * @returns true if operation was successful
  5754. */
  5755. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5756. if (translation) {
  5757. translation.x = this.m[12];
  5758. translation.y = this.m[13];
  5759. translation.z = this.m[14];
  5760. }
  5761. scale = scale || MathTmp.Vector3[0];
  5762. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5763. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5764. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5765. if (this.determinant() <= 0) {
  5766. scale.y *= -1;
  5767. }
  5768. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5769. if (rotation) {
  5770. rotation.x = 0;
  5771. rotation.y = 0;
  5772. rotation.z = 0;
  5773. rotation.w = 1;
  5774. }
  5775. return false;
  5776. }
  5777. if (rotation) {
  5778. 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]);
  5779. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5780. }
  5781. return true;
  5782. };
  5783. /**
  5784. * Gets specific row of the matrix
  5785. * @param index defines the number of the row to get
  5786. * @returns the index-th row of the current matrix as a new Vector4
  5787. */
  5788. Matrix.prototype.getRow = function (index) {
  5789. if (index < 0 || index > 3) {
  5790. return null;
  5791. }
  5792. var i = index * 4;
  5793. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5794. };
  5795. /**
  5796. * Sets the index-th row of the current matrix to the vector4 values
  5797. * @param index defines the number of the row to set
  5798. * @param row defines the target vector4
  5799. * @returns the updated current matrix
  5800. */
  5801. Matrix.prototype.setRow = function (index, row) {
  5802. if (index < 0 || index > 3) {
  5803. return this;
  5804. }
  5805. var i = index * 4;
  5806. this.m[i + 0] = row.x;
  5807. this.m[i + 1] = row.y;
  5808. this.m[i + 2] = row.z;
  5809. this.m[i + 3] = row.w;
  5810. this._markAsUpdated();
  5811. return this;
  5812. };
  5813. /**
  5814. * Compute the transpose of the matrix
  5815. * @returns the new transposed matrix
  5816. */
  5817. Matrix.prototype.transpose = function () {
  5818. return Matrix.Transpose(this);
  5819. };
  5820. /**
  5821. * Compute the transpose of the matrix and store it in a given matrix
  5822. * @param result defines the target matrix
  5823. * @returns the current matrix
  5824. */
  5825. Matrix.prototype.transposeToRef = function (result) {
  5826. Matrix.TransposeToRef(this, result);
  5827. return this;
  5828. };
  5829. /**
  5830. * Sets the index-th row of the current matrix with the given 4 x float values
  5831. * @param index defines the row index
  5832. * @param x defines the x component to set
  5833. * @param y defines the y component to set
  5834. * @param z defines the z component to set
  5835. * @param w defines the w component to set
  5836. * @returns the updated current matrix
  5837. */
  5838. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5839. if (index < 0 || index > 3) {
  5840. return this;
  5841. }
  5842. var i = index * 4;
  5843. this.m[i + 0] = x;
  5844. this.m[i + 1] = y;
  5845. this.m[i + 2] = z;
  5846. this.m[i + 3] = w;
  5847. this._markAsUpdated();
  5848. return this;
  5849. };
  5850. /**
  5851. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5852. * @param scale defines the scale factor
  5853. * @returns a new matrix
  5854. */
  5855. Matrix.prototype.scale = function (scale) {
  5856. var result = new Matrix();
  5857. this.scaleToRef(scale, result);
  5858. return result;
  5859. };
  5860. /**
  5861. * Scale the current matrix values by a factor to a given result matrix
  5862. * @param scale defines the scale factor
  5863. * @param result defines the matrix to store the result
  5864. * @returns the current matrix
  5865. */
  5866. Matrix.prototype.scaleToRef = function (scale, result) {
  5867. for (var index = 0; index < 16; index++) {
  5868. result.m[index] = this.m[index] * scale;
  5869. }
  5870. result._markAsUpdated();
  5871. return this;
  5872. };
  5873. /**
  5874. * Scale the current matrix values by a factor and add the result to a given matrix
  5875. * @param scale defines the scale factor
  5876. * @param result defines the Matrix to store the result
  5877. * @returns the current matrix
  5878. */
  5879. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5880. for (var index = 0; index < 16; index++) {
  5881. result.m[index] += this.m[index] * scale;
  5882. }
  5883. result._markAsUpdated();
  5884. return this;
  5885. };
  5886. /**
  5887. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5888. * @param ref matrix to store the result
  5889. */
  5890. Matrix.prototype.toNormalMatrix = function (ref) {
  5891. this.invertToRef(ref);
  5892. ref.transpose();
  5893. var m = ref.m;
  5894. 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);
  5895. };
  5896. /**
  5897. * Gets only rotation part of the current matrix
  5898. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5899. */
  5900. Matrix.prototype.getRotationMatrix = function () {
  5901. var result = Matrix.Identity();
  5902. this.getRotationMatrixToRef(result);
  5903. return result;
  5904. };
  5905. /**
  5906. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5907. * @param result defines the target matrix to store data to
  5908. * @returns the current matrix
  5909. */
  5910. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5911. var m = this.m;
  5912. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5913. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5914. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5915. if (this.determinant() <= 0) {
  5916. sy *= -1;
  5917. }
  5918. if (sx === 0 || sy === 0 || sz === 0) {
  5919. Matrix.IdentityToRef(result);
  5920. }
  5921. else {
  5922. 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);
  5923. }
  5924. return this;
  5925. };
  5926. // Statics
  5927. /**
  5928. * Creates a matrix from an array
  5929. * @param array defines the source array
  5930. * @param offset defines an offset in the source array
  5931. * @returns a new Matrix set from the starting index of the given array
  5932. */
  5933. Matrix.FromArray = function (array, offset) {
  5934. var result = new Matrix();
  5935. if (!offset) {
  5936. offset = 0;
  5937. }
  5938. Matrix.FromArrayToRef(array, offset, result);
  5939. return result;
  5940. };
  5941. /**
  5942. * Copy the content of an array into a given matrix
  5943. * @param array defines the source array
  5944. * @param offset defines an offset in the source array
  5945. * @param result defines the target matrix
  5946. */
  5947. Matrix.FromArrayToRef = function (array, offset, result) {
  5948. for (var index = 0; index < 16; index++) {
  5949. result.m[index] = array[index + offset];
  5950. }
  5951. result._markAsUpdated();
  5952. };
  5953. /**
  5954. * Stores an array into a matrix after having multiplied each component by a given factor
  5955. * @param array defines the source array
  5956. * @param offset defines the offset in the source array
  5957. * @param scale defines the scaling factor
  5958. * @param result defines the target matrix
  5959. */
  5960. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5961. for (var index = 0; index < 16; index++) {
  5962. result.m[index] = array[index + offset] * scale;
  5963. }
  5964. result._markAsUpdated();
  5965. };
  5966. /**
  5967. * Stores a list of values (16) inside a given matrix
  5968. * @param initialM11 defines 1st value of 1st row
  5969. * @param initialM12 defines 2nd value of 1st row
  5970. * @param initialM13 defines 3rd value of 1st row
  5971. * @param initialM14 defines 4th value of 1st row
  5972. * @param initialM21 defines 1st value of 2nd row
  5973. * @param initialM22 defines 2nd value of 2nd row
  5974. * @param initialM23 defines 3rd value of 2nd row
  5975. * @param initialM24 defines 4th value of 2nd row
  5976. * @param initialM31 defines 1st value of 3rd row
  5977. * @param initialM32 defines 2nd value of 3rd row
  5978. * @param initialM33 defines 3rd value of 3rd row
  5979. * @param initialM34 defines 4th value of 3rd row
  5980. * @param initialM41 defines 1st value of 4th row
  5981. * @param initialM42 defines 2nd value of 4th row
  5982. * @param initialM43 defines 3rd value of 4th row
  5983. * @param initialM44 defines 4th value of 4th row
  5984. * @param result defines the target matrix
  5985. */
  5986. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5987. result.m[0] = initialM11;
  5988. result.m[1] = initialM12;
  5989. result.m[2] = initialM13;
  5990. result.m[3] = initialM14;
  5991. result.m[4] = initialM21;
  5992. result.m[5] = initialM22;
  5993. result.m[6] = initialM23;
  5994. result.m[7] = initialM24;
  5995. result.m[8] = initialM31;
  5996. result.m[9] = initialM32;
  5997. result.m[10] = initialM33;
  5998. result.m[11] = initialM34;
  5999. result.m[12] = initialM41;
  6000. result.m[13] = initialM42;
  6001. result.m[14] = initialM43;
  6002. result.m[15] = initialM44;
  6003. result._markAsUpdated();
  6004. };
  6005. Object.defineProperty(Matrix, "IdentityReadOnly", {
  6006. /**
  6007. * Gets an identity matrix that must not be updated
  6008. */
  6009. get: function () {
  6010. return Matrix._identityReadOnly;
  6011. },
  6012. enumerable: true,
  6013. configurable: true
  6014. });
  6015. /**
  6016. * Creates new matrix from a list of values (16)
  6017. * @param initialM11 defines 1st value of 1st row
  6018. * @param initialM12 defines 2nd value of 1st row
  6019. * @param initialM13 defines 3rd value of 1st row
  6020. * @param initialM14 defines 4th value of 1st row
  6021. * @param initialM21 defines 1st value of 2nd row
  6022. * @param initialM22 defines 2nd value of 2nd row
  6023. * @param initialM23 defines 3rd value of 2nd row
  6024. * @param initialM24 defines 4th value of 2nd row
  6025. * @param initialM31 defines 1st value of 3rd row
  6026. * @param initialM32 defines 2nd value of 3rd row
  6027. * @param initialM33 defines 3rd value of 3rd row
  6028. * @param initialM34 defines 4th value of 3rd row
  6029. * @param initialM41 defines 1st value of 4th row
  6030. * @param initialM42 defines 2nd value of 4th row
  6031. * @param initialM43 defines 3rd value of 4th row
  6032. * @param initialM44 defines 4th value of 4th row
  6033. * @returns the new matrix
  6034. */
  6035. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  6036. var result = new Matrix();
  6037. result.m[0] = initialM11;
  6038. result.m[1] = initialM12;
  6039. result.m[2] = initialM13;
  6040. result.m[3] = initialM14;
  6041. result.m[4] = initialM21;
  6042. result.m[5] = initialM22;
  6043. result.m[6] = initialM23;
  6044. result.m[7] = initialM24;
  6045. result.m[8] = initialM31;
  6046. result.m[9] = initialM32;
  6047. result.m[10] = initialM33;
  6048. result.m[11] = initialM34;
  6049. result.m[12] = initialM41;
  6050. result.m[13] = initialM42;
  6051. result.m[14] = initialM43;
  6052. result.m[15] = initialM44;
  6053. return result;
  6054. };
  6055. /**
  6056. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  6057. * @param scale defines the scale vector3
  6058. * @param rotation defines the rotation quaternion
  6059. * @param translation defines the translation vector3
  6060. * @returns a new matrix
  6061. */
  6062. Matrix.Compose = function (scale, rotation, translation) {
  6063. var result = Matrix.Identity();
  6064. Matrix.ComposeToRef(scale, rotation, translation, result);
  6065. return result;
  6066. };
  6067. /**
  6068. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  6069. * @param scale defines the scale vector3
  6070. * @param rotation defines the rotation quaternion
  6071. * @param translation defines the translation vector3
  6072. * @param result defines the target matrix
  6073. */
  6074. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  6075. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  6076. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  6077. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  6078. result.setTranslation(translation);
  6079. };
  6080. /**
  6081. * Creates a new identity matrix
  6082. * @returns a new identity matrix
  6083. */
  6084. Matrix.Identity = function () {
  6085. 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);
  6086. };
  6087. /**
  6088. * Creates a new identity matrix and stores the result in a given matrix
  6089. * @param result defines the target matrix
  6090. */
  6091. Matrix.IdentityToRef = function (result) {
  6092. 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);
  6093. };
  6094. /**
  6095. * Creates a new zero matrix
  6096. * @returns a new zero matrix
  6097. */
  6098. Matrix.Zero = function () {
  6099. 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);
  6100. };
  6101. /**
  6102. * Creates a new rotation matrix for "angle" radians around the X axis
  6103. * @param angle defines the angle (in radians) to use
  6104. * @return the new matrix
  6105. */
  6106. Matrix.RotationX = function (angle) {
  6107. var result = new Matrix();
  6108. Matrix.RotationXToRef(angle, result);
  6109. return result;
  6110. };
  6111. /**
  6112. * Creates a new matrix as the invert of a given matrix
  6113. * @param source defines the source matrix
  6114. * @returns the new matrix
  6115. */
  6116. Matrix.Invert = function (source) {
  6117. var result = new Matrix();
  6118. source.invertToRef(result);
  6119. return result;
  6120. };
  6121. /**
  6122. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  6123. * @param angle defines the angle (in radians) to use
  6124. * @param result defines the target matrix
  6125. */
  6126. Matrix.RotationXToRef = function (angle, result) {
  6127. var s = Math.sin(angle);
  6128. var c = Math.cos(angle);
  6129. result.m[0] = 1.0;
  6130. result.m[15] = 1.0;
  6131. result.m[5] = c;
  6132. result.m[10] = c;
  6133. result.m[9] = -s;
  6134. result.m[6] = s;
  6135. result.m[1] = 0.0;
  6136. result.m[2] = 0.0;
  6137. result.m[3] = 0.0;
  6138. result.m[4] = 0.0;
  6139. result.m[7] = 0.0;
  6140. result.m[8] = 0.0;
  6141. result.m[11] = 0.0;
  6142. result.m[12] = 0.0;
  6143. result.m[13] = 0.0;
  6144. result.m[14] = 0.0;
  6145. result._markAsUpdated();
  6146. };
  6147. /**
  6148. * Creates a new rotation matrix for "angle" radians around the Y axis
  6149. * @param angle defines the angle (in radians) to use
  6150. * @return the new matrix
  6151. */
  6152. Matrix.RotationY = function (angle) {
  6153. var result = new Matrix();
  6154. Matrix.RotationYToRef(angle, result);
  6155. return result;
  6156. };
  6157. /**
  6158. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  6159. * @param angle defines the angle (in radians) to use
  6160. * @param result defines the target matrix
  6161. */
  6162. Matrix.RotationYToRef = function (angle, result) {
  6163. var s = Math.sin(angle);
  6164. var c = Math.cos(angle);
  6165. result.m[5] = 1.0;
  6166. result.m[15] = 1.0;
  6167. result.m[0] = c;
  6168. result.m[2] = -s;
  6169. result.m[8] = s;
  6170. result.m[10] = c;
  6171. result.m[1] = 0.0;
  6172. result.m[3] = 0.0;
  6173. result.m[4] = 0.0;
  6174. result.m[6] = 0.0;
  6175. result.m[7] = 0.0;
  6176. result.m[9] = 0.0;
  6177. result.m[11] = 0.0;
  6178. result.m[12] = 0.0;
  6179. result.m[13] = 0.0;
  6180. result.m[14] = 0.0;
  6181. result._markAsUpdated();
  6182. };
  6183. /**
  6184. * Creates a new rotation matrix for "angle" radians around the Z axis
  6185. * @param angle defines the angle (in radians) to use
  6186. * @return the new matrix
  6187. */
  6188. Matrix.RotationZ = function (angle) {
  6189. var result = new Matrix();
  6190. Matrix.RotationZToRef(angle, result);
  6191. return result;
  6192. };
  6193. /**
  6194. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  6195. * @param angle defines the angle (in radians) to use
  6196. * @param result defines the target matrix
  6197. */
  6198. Matrix.RotationZToRef = function (angle, result) {
  6199. var s = Math.sin(angle);
  6200. var c = Math.cos(angle);
  6201. result.m[10] = 1.0;
  6202. result.m[15] = 1.0;
  6203. result.m[0] = c;
  6204. result.m[1] = s;
  6205. result.m[4] = -s;
  6206. result.m[5] = c;
  6207. result.m[2] = 0.0;
  6208. result.m[3] = 0.0;
  6209. result.m[6] = 0.0;
  6210. result.m[7] = 0.0;
  6211. result.m[8] = 0.0;
  6212. result.m[9] = 0.0;
  6213. result.m[11] = 0.0;
  6214. result.m[12] = 0.0;
  6215. result.m[13] = 0.0;
  6216. result.m[14] = 0.0;
  6217. result._markAsUpdated();
  6218. };
  6219. /**
  6220. * Creates a new rotation matrix for "angle" radians around the given axis
  6221. * @param axis defines the axis to use
  6222. * @param angle defines the angle (in radians) to use
  6223. * @return the new matrix
  6224. */
  6225. Matrix.RotationAxis = function (axis, angle) {
  6226. var result = Matrix.Zero();
  6227. Matrix.RotationAxisToRef(axis, angle, result);
  6228. return result;
  6229. };
  6230. /**
  6231. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  6232. * @param axis defines the axis to use
  6233. * @param angle defines the angle (in radians) to use
  6234. * @param result defines the target matrix
  6235. */
  6236. Matrix.RotationAxisToRef = function (axis, angle, result) {
  6237. var s = Math.sin(-angle);
  6238. var c = Math.cos(-angle);
  6239. var c1 = 1 - c;
  6240. axis.normalize();
  6241. result.m[0] = (axis.x * axis.x) * c1 + c;
  6242. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  6243. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  6244. result.m[3] = 0.0;
  6245. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  6246. result.m[5] = (axis.y * axis.y) * c1 + c;
  6247. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  6248. result.m[7] = 0.0;
  6249. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  6250. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  6251. result.m[10] = (axis.z * axis.z) * c1 + c;
  6252. result.m[11] = 0.0;
  6253. result.m[15] = 1.0;
  6254. result._markAsUpdated();
  6255. };
  6256. /**
  6257. * Creates a rotation matrix
  6258. * @param yaw defines the yaw angle in radians (Y axis)
  6259. * @param pitch defines the pitch angle in radians (X axis)
  6260. * @param roll defines the roll angle in radians (X axis)
  6261. * @returns the new rotation matrix
  6262. */
  6263. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6264. var result = new Matrix();
  6265. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6266. return result;
  6267. };
  6268. /**
  6269. * Creates a rotation matrix and stores it in a given matrix
  6270. * @param yaw defines the yaw angle in radians (Y axis)
  6271. * @param pitch defines the pitch angle in radians (X axis)
  6272. * @param roll defines the roll angle in radians (X axis)
  6273. * @param result defines the target matrix
  6274. */
  6275. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6276. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6277. this._tempQuaternion.toRotationMatrix(result);
  6278. };
  6279. /**
  6280. * Creates a scaling matrix
  6281. * @param x defines the scale factor on X axis
  6282. * @param y defines the scale factor on Y axis
  6283. * @param z defines the scale factor on Z axis
  6284. * @returns the new matrix
  6285. */
  6286. Matrix.Scaling = function (x, y, z) {
  6287. var result = Matrix.Zero();
  6288. Matrix.ScalingToRef(x, y, z, result);
  6289. return result;
  6290. };
  6291. /**
  6292. * Creates a scaling matrix and stores it in a given matrix
  6293. * @param x defines the scale factor on X axis
  6294. * @param y defines the scale factor on Y axis
  6295. * @param z defines the scale factor on Z axis
  6296. * @param result defines the target matrix
  6297. */
  6298. Matrix.ScalingToRef = function (x, y, z, result) {
  6299. result.m[0] = x;
  6300. result.m[1] = 0.0;
  6301. result.m[2] = 0.0;
  6302. result.m[3] = 0.0;
  6303. result.m[4] = 0.0;
  6304. result.m[5] = y;
  6305. result.m[6] = 0.0;
  6306. result.m[7] = 0.0;
  6307. result.m[8] = 0.0;
  6308. result.m[9] = 0.0;
  6309. result.m[10] = z;
  6310. result.m[11] = 0.0;
  6311. result.m[12] = 0.0;
  6312. result.m[13] = 0.0;
  6313. result.m[14] = 0.0;
  6314. result.m[15] = 1.0;
  6315. result._markAsUpdated();
  6316. };
  6317. /**
  6318. * Creates a translation matrix
  6319. * @param x defines the translation on X axis
  6320. * @param y defines the translation on Y axis
  6321. * @param z defines the translationon Z axis
  6322. * @returns the new matrix
  6323. */
  6324. Matrix.Translation = function (x, y, z) {
  6325. var result = Matrix.Identity();
  6326. Matrix.TranslationToRef(x, y, z, result);
  6327. return result;
  6328. };
  6329. /**
  6330. * Creates a translation matrix and stores it in a given matrix
  6331. * @param x defines the translation on X axis
  6332. * @param y defines the translation on Y axis
  6333. * @param z defines the translationon Z axis
  6334. * @param result defines the target matrix
  6335. */
  6336. Matrix.TranslationToRef = function (x, y, z, result) {
  6337. 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);
  6338. };
  6339. /**
  6340. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6341. * @param startValue defines the start value
  6342. * @param endValue defines the end value
  6343. * @param gradient defines the gradient factor
  6344. * @returns the new matrix
  6345. */
  6346. Matrix.Lerp = function (startValue, endValue, gradient) {
  6347. var result = Matrix.Zero();
  6348. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6349. return result;
  6350. };
  6351. /**
  6352. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6353. * @param startValue defines the start value
  6354. * @param endValue defines the end value
  6355. * @param gradient defines the gradient factor
  6356. * @param result defines the Matrix object where to store data
  6357. */
  6358. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6359. for (var index = 0; index < 16; index++) {
  6360. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6361. }
  6362. result._markAsUpdated();
  6363. };
  6364. /**
  6365. * Builds a new matrix whose values are computed by:
  6366. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6367. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6368. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6369. * @param startValue defines the first matrix
  6370. * @param endValue defines the second matrix
  6371. * @param gradient defines the gradient between the two matrices
  6372. * @returns the new matrix
  6373. */
  6374. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6375. var result = Matrix.Zero();
  6376. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6377. return result;
  6378. };
  6379. /**
  6380. * Update a matrix to values which are computed by:
  6381. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6382. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6383. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6384. * @param startValue defines the first matrix
  6385. * @param endValue defines the second matrix
  6386. * @param gradient defines the gradient between the two matrices
  6387. * @param result defines the target matrix
  6388. */
  6389. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6390. var startScale = MathTmp.Vector3[0];
  6391. var startRotation = MathTmp.Quaternion[0];
  6392. var startTranslation = MathTmp.Vector3[1];
  6393. startValue.decompose(startScale, startRotation, startTranslation);
  6394. var endScale = MathTmp.Vector3[2];
  6395. var endRotation = MathTmp.Quaternion[1];
  6396. var endTranslation = MathTmp.Vector3[3];
  6397. endValue.decompose(endScale, endRotation, endTranslation);
  6398. var resultScale = MathTmp.Vector3[4];
  6399. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6400. var resultRotation = MathTmp.Quaternion[2];
  6401. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6402. var resultTranslation = MathTmp.Vector3[5];
  6403. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6404. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6405. };
  6406. /**
  6407. * 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"
  6408. * This function works in left handed mode
  6409. * @param eye defines the final position of the entity
  6410. * @param target defines where the entity should look at
  6411. * @param up defines the up vector for the entity
  6412. * @returns the new matrix
  6413. */
  6414. Matrix.LookAtLH = function (eye, target, up) {
  6415. var result = Matrix.Zero();
  6416. Matrix.LookAtLHToRef(eye, target, up, result);
  6417. return result;
  6418. };
  6419. /**
  6420. * 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".
  6421. * This function works in left handed mode
  6422. * @param eye defines the final position of the entity
  6423. * @param target defines where the entity should look at
  6424. * @param up defines the up vector for the entity
  6425. * @param result defines the target matrix
  6426. */
  6427. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6428. // Z axis
  6429. target.subtractToRef(eye, this._zAxis);
  6430. this._zAxis.normalize();
  6431. // X axis
  6432. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6433. if (this._xAxis.lengthSquared() === 0) {
  6434. this._xAxis.x = 1.0;
  6435. }
  6436. else {
  6437. this._xAxis.normalize();
  6438. }
  6439. // Y axis
  6440. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6441. this._yAxis.normalize();
  6442. // Eye angles
  6443. var ex = -Vector3.Dot(this._xAxis, eye);
  6444. var ey = -Vector3.Dot(this._yAxis, eye);
  6445. var ez = -Vector3.Dot(this._zAxis, eye);
  6446. 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);
  6447. };
  6448. /**
  6449. * 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"
  6450. * This function works in right handed mode
  6451. * @param eye defines the final position of the entity
  6452. * @param target defines where the entity should look at
  6453. * @param up defines the up vector for the entity
  6454. * @returns the new matrix
  6455. */
  6456. Matrix.LookAtRH = function (eye, target, up) {
  6457. var result = Matrix.Zero();
  6458. Matrix.LookAtRHToRef(eye, target, up, result);
  6459. return result;
  6460. };
  6461. /**
  6462. * 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".
  6463. * This function works in right handed mode
  6464. * @param eye defines the final position of the entity
  6465. * @param target defines where the entity should look at
  6466. * @param up defines the up vector for the entity
  6467. * @param result defines the target matrix
  6468. */
  6469. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6470. // Z axis
  6471. eye.subtractToRef(target, this._zAxis);
  6472. this._zAxis.normalize();
  6473. // X axis
  6474. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6475. if (this._xAxis.lengthSquared() === 0) {
  6476. this._xAxis.x = 1.0;
  6477. }
  6478. else {
  6479. this._xAxis.normalize();
  6480. }
  6481. // Y axis
  6482. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6483. this._yAxis.normalize();
  6484. // Eye angles
  6485. var ex = -Vector3.Dot(this._xAxis, eye);
  6486. var ey = -Vector3.Dot(this._yAxis, eye);
  6487. var ez = -Vector3.Dot(this._zAxis, eye);
  6488. 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);
  6489. };
  6490. /**
  6491. * Create a left-handed orthographic projection matrix
  6492. * @param width defines the viewport width
  6493. * @param height defines the viewport height
  6494. * @param znear defines the near clip plane
  6495. * @param zfar defines the far clip plane
  6496. * @returns a new matrix as a left-handed orthographic projection matrix
  6497. */
  6498. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6499. var matrix = Matrix.Zero();
  6500. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6501. return matrix;
  6502. };
  6503. /**
  6504. * Store a left-handed orthographic projection to a given matrix
  6505. * @param width defines the viewport width
  6506. * @param height defines the viewport height
  6507. * @param znear defines the near clip plane
  6508. * @param zfar defines the far clip plane
  6509. * @param result defines the target matrix
  6510. */
  6511. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6512. var n = znear;
  6513. var f = zfar;
  6514. var a = 2.0 / width;
  6515. var b = 2.0 / height;
  6516. var c = 2.0 / (f - n);
  6517. var d = -(f + n) / (f - n);
  6518. 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);
  6519. };
  6520. /**
  6521. * Create a left-handed orthographic projection matrix
  6522. * @param left defines the viewport left coordinate
  6523. * @param right defines the viewport right coordinate
  6524. * @param bottom defines the viewport bottom coordinate
  6525. * @param top defines the viewport top coordinate
  6526. * @param znear defines the near clip plane
  6527. * @param zfar defines the far clip plane
  6528. * @returns a new matrix as a left-handed orthographic projection matrix
  6529. */
  6530. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6531. var matrix = Matrix.Zero();
  6532. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6533. return matrix;
  6534. };
  6535. /**
  6536. * Stores a left-handed orthographic projection into a given matrix
  6537. * @param left defines the viewport left coordinate
  6538. * @param right defines the viewport right coordinate
  6539. * @param bottom defines the viewport bottom coordinate
  6540. * @param top defines the viewport top coordinate
  6541. * @param znear defines the near clip plane
  6542. * @param zfar defines the far clip plane
  6543. * @param result defines the target matrix
  6544. */
  6545. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6546. var n = znear;
  6547. var f = zfar;
  6548. var a = 2.0 / (right - left);
  6549. var b = 2.0 / (top - bottom);
  6550. var c = 2.0 / (f - n);
  6551. var d = -(f + n) / (f - n);
  6552. var i0 = (left + right) / (left - right);
  6553. var i1 = (top + bottom) / (bottom - top);
  6554. 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);
  6555. };
  6556. /**
  6557. * Creates a right-handed orthographic projection matrix
  6558. * @param left defines the viewport left coordinate
  6559. * @param right defines the viewport right coordinate
  6560. * @param bottom defines the viewport bottom coordinate
  6561. * @param top defines the viewport top coordinate
  6562. * @param znear defines the near clip plane
  6563. * @param zfar defines the far clip plane
  6564. * @returns a new matrix as a right-handed orthographic projection matrix
  6565. */
  6566. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6567. var matrix = Matrix.Zero();
  6568. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6569. return matrix;
  6570. };
  6571. /**
  6572. * Stores a right-handed orthographic projection into a given matrix
  6573. * @param left defines the viewport left coordinate
  6574. * @param right defines the viewport right coordinate
  6575. * @param bottom defines the viewport bottom coordinate
  6576. * @param top defines the viewport top coordinate
  6577. * @param znear defines the near clip plane
  6578. * @param zfar defines the far clip plane
  6579. * @param result defines the target matrix
  6580. */
  6581. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6582. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6583. result.m[10] *= -1.0;
  6584. };
  6585. /**
  6586. * Creates a left-handed perspective projection matrix
  6587. * @param width defines the viewport width
  6588. * @param height defines the viewport height
  6589. * @param znear defines the near clip plane
  6590. * @param zfar defines the far clip plane
  6591. * @returns a new matrix as a left-handed perspective projection matrix
  6592. */
  6593. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6594. var matrix = Matrix.Zero();
  6595. var n = znear;
  6596. var f = zfar;
  6597. var a = 2.0 * n / width;
  6598. var b = 2.0 * n / height;
  6599. var c = (f + n) / (f - n);
  6600. var d = -2.0 * f * n / (f - n);
  6601. 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);
  6602. return matrix;
  6603. };
  6604. /**
  6605. * Creates a left-handed perspective projection matrix
  6606. * @param fov defines the horizontal field of view
  6607. * @param aspect defines the aspect ratio
  6608. * @param znear defines the near clip plane
  6609. * @param zfar defines the far clip plane
  6610. * @returns a new matrix as a left-handed perspective projection matrix
  6611. */
  6612. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6613. var matrix = Matrix.Zero();
  6614. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6615. return matrix;
  6616. };
  6617. /**
  6618. * Stores a left-handed perspective projection into a given matrix
  6619. * @param fov defines the horizontal field of view
  6620. * @param aspect defines the aspect ratio
  6621. * @param znear defines the near clip plane
  6622. * @param zfar defines the far clip plane
  6623. * @param result defines the target matrix
  6624. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6625. */
  6626. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6627. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6628. var n = znear;
  6629. var f = zfar;
  6630. var t = 1.0 / (Math.tan(fov * 0.5));
  6631. var a = isVerticalFovFixed ? (t / aspect) : t;
  6632. var b = isVerticalFovFixed ? t : (t * aspect);
  6633. var c = (f + n) / (f - n);
  6634. var d = -2.0 * f * n / (f - n);
  6635. 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);
  6636. };
  6637. /**
  6638. * Creates a right-handed perspective projection matrix
  6639. * @param fov defines the horizontal field of view
  6640. * @param aspect defines the aspect ratio
  6641. * @param znear defines the near clip plane
  6642. * @param zfar defines the far clip plane
  6643. * @returns a new matrix as a right-handed perspective projection matrix
  6644. */
  6645. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6646. var matrix = Matrix.Zero();
  6647. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6648. return matrix;
  6649. };
  6650. /**
  6651. * Stores a right-handed perspective projection into a given matrix
  6652. * @param fov defines the horizontal field of view
  6653. * @param aspect defines the aspect ratio
  6654. * @param znear defines the near clip plane
  6655. * @param zfar defines the far clip plane
  6656. * @param result defines the target matrix
  6657. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6658. */
  6659. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6660. //alternatively this could be expressed as:
  6661. // m = PerspectiveFovLHToRef
  6662. // m[10] *= -1.0;
  6663. // m[11] *= -1.0;
  6664. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6665. var n = znear;
  6666. var f = zfar;
  6667. var t = 1.0 / (Math.tan(fov * 0.5));
  6668. var a = isVerticalFovFixed ? (t / aspect) : t;
  6669. var b = isVerticalFovFixed ? t : (t * aspect);
  6670. var c = -(f + n) / (f - n);
  6671. var d = -2 * f * n / (f - n);
  6672. 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);
  6673. };
  6674. /**
  6675. * Stores a perspective projection for WebVR info a given matrix
  6676. * @param fov defines the field of view
  6677. * @param znear defines the near clip plane
  6678. * @param zfar defines the far clip plane
  6679. * @param result defines the target matrix
  6680. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6681. */
  6682. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6683. if (rightHanded === void 0) { rightHanded = false; }
  6684. var rightHandedFactor = rightHanded ? -1 : 1;
  6685. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6686. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6687. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6688. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6689. var xScale = 2.0 / (leftTan + rightTan);
  6690. var yScale = 2.0 / (upTan + downTan);
  6691. result.m[0] = xScale;
  6692. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6693. result.m[5] = yScale;
  6694. result.m[6] = result.m[7] = 0.0;
  6695. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6696. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6697. result.m[10] = -zfar / (znear - zfar);
  6698. result.m[11] = 1.0 * rightHandedFactor;
  6699. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6700. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6701. result._markAsUpdated();
  6702. };
  6703. /**
  6704. * Computes a complete transformation matrix
  6705. * @param viewport defines the viewport to use
  6706. * @param world defines the world matrix
  6707. * @param view defines the view matrix
  6708. * @param projection defines the projection matrix
  6709. * @param zmin defines the near clip plane
  6710. * @param zmax defines the far clip plane
  6711. * @returns the transformation matrix
  6712. */
  6713. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6714. var cw = viewport.width;
  6715. var ch = viewport.height;
  6716. var cx = viewport.x;
  6717. var cy = viewport.y;
  6718. 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);
  6719. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6720. };
  6721. /**
  6722. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6723. * @param matrix defines the matrix to use
  6724. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6725. */
  6726. Matrix.GetAsMatrix2x2 = function (matrix) {
  6727. return new Float32Array([
  6728. matrix.m[0], matrix.m[1],
  6729. matrix.m[4], matrix.m[5]
  6730. ]);
  6731. };
  6732. /**
  6733. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6734. * @param matrix defines the matrix to use
  6735. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6736. */
  6737. Matrix.GetAsMatrix3x3 = function (matrix) {
  6738. return new Float32Array([
  6739. matrix.m[0], matrix.m[1], matrix.m[2],
  6740. matrix.m[4], matrix.m[5], matrix.m[6],
  6741. matrix.m[8], matrix.m[9], matrix.m[10]
  6742. ]);
  6743. };
  6744. /**
  6745. * Compute the transpose of a given matrix
  6746. * @param matrix defines the matrix to transpose
  6747. * @returns the new matrix
  6748. */
  6749. Matrix.Transpose = function (matrix) {
  6750. var result = new Matrix();
  6751. Matrix.TransposeToRef(matrix, result);
  6752. return result;
  6753. };
  6754. /**
  6755. * Compute the transpose of a matrix and store it in a target matrix
  6756. * @param matrix defines the matrix to transpose
  6757. * @param result defines the target matrix
  6758. */
  6759. Matrix.TransposeToRef = function (matrix, result) {
  6760. result.m[0] = matrix.m[0];
  6761. result.m[1] = matrix.m[4];
  6762. result.m[2] = matrix.m[8];
  6763. result.m[3] = matrix.m[12];
  6764. result.m[4] = matrix.m[1];
  6765. result.m[5] = matrix.m[5];
  6766. result.m[6] = matrix.m[9];
  6767. result.m[7] = matrix.m[13];
  6768. result.m[8] = matrix.m[2];
  6769. result.m[9] = matrix.m[6];
  6770. result.m[10] = matrix.m[10];
  6771. result.m[11] = matrix.m[14];
  6772. result.m[12] = matrix.m[3];
  6773. result.m[13] = matrix.m[7];
  6774. result.m[14] = matrix.m[11];
  6775. result.m[15] = matrix.m[15];
  6776. };
  6777. /**
  6778. * Computes a reflection matrix from a plane
  6779. * @param plane defines the reflection plane
  6780. * @returns a new matrix
  6781. */
  6782. Matrix.Reflection = function (plane) {
  6783. var matrix = new Matrix();
  6784. Matrix.ReflectionToRef(plane, matrix);
  6785. return matrix;
  6786. };
  6787. /**
  6788. * Computes a reflection matrix from a plane
  6789. * @param plane defines the reflection plane
  6790. * @param result defines the target matrix
  6791. */
  6792. Matrix.ReflectionToRef = function (plane, result) {
  6793. plane.normalize();
  6794. var x = plane.normal.x;
  6795. var y = plane.normal.y;
  6796. var z = plane.normal.z;
  6797. var temp = -2 * x;
  6798. var temp2 = -2 * y;
  6799. var temp3 = -2 * z;
  6800. result.m[0] = (temp * x) + 1;
  6801. result.m[1] = temp2 * x;
  6802. result.m[2] = temp3 * x;
  6803. result.m[3] = 0.0;
  6804. result.m[4] = temp * y;
  6805. result.m[5] = (temp2 * y) + 1;
  6806. result.m[6] = temp3 * y;
  6807. result.m[7] = 0.0;
  6808. result.m[8] = temp * z;
  6809. result.m[9] = temp2 * z;
  6810. result.m[10] = (temp3 * z) + 1;
  6811. result.m[11] = 0.0;
  6812. result.m[12] = temp * plane.d;
  6813. result.m[13] = temp2 * plane.d;
  6814. result.m[14] = temp3 * plane.d;
  6815. result.m[15] = 1.0;
  6816. result._markAsUpdated();
  6817. };
  6818. /**
  6819. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6820. * @param xaxis defines the value of the 1st axis
  6821. * @param yaxis defines the value of the 2nd axis
  6822. * @param zaxis defines the value of the 3rd axis
  6823. * @param result defines the target matrix
  6824. */
  6825. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6826. result.m[0] = xaxis.x;
  6827. result.m[1] = xaxis.y;
  6828. result.m[2] = xaxis.z;
  6829. result.m[3] = 0.0;
  6830. result.m[4] = yaxis.x;
  6831. result.m[5] = yaxis.y;
  6832. result.m[6] = yaxis.z;
  6833. result.m[7] = 0.0;
  6834. result.m[8] = zaxis.x;
  6835. result.m[9] = zaxis.y;
  6836. result.m[10] = zaxis.z;
  6837. result.m[11] = 0.0;
  6838. result.m[12] = 0.0;
  6839. result.m[13] = 0.0;
  6840. result.m[14] = 0.0;
  6841. result.m[15] = 1.0;
  6842. result._markAsUpdated();
  6843. };
  6844. /**
  6845. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6846. * @param quat defines the quaternion to use
  6847. * @param result defines the target matrix
  6848. */
  6849. Matrix.FromQuaternionToRef = function (quat, result) {
  6850. var xx = quat.x * quat.x;
  6851. var yy = quat.y * quat.y;
  6852. var zz = quat.z * quat.z;
  6853. var xy = quat.x * quat.y;
  6854. var zw = quat.z * quat.w;
  6855. var zx = quat.z * quat.x;
  6856. var yw = quat.y * quat.w;
  6857. var yz = quat.y * quat.z;
  6858. var xw = quat.x * quat.w;
  6859. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6860. result.m[1] = 2.0 * (xy + zw);
  6861. result.m[2] = 2.0 * (zx - yw);
  6862. result.m[3] = 0.0;
  6863. result.m[4] = 2.0 * (xy - zw);
  6864. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6865. result.m[6] = 2.0 * (yz + xw);
  6866. result.m[7] = 0.0;
  6867. result.m[8] = 2.0 * (zx + yw);
  6868. result.m[9] = 2.0 * (yz - xw);
  6869. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6870. result.m[11] = 0.0;
  6871. result.m[12] = 0.0;
  6872. result.m[13] = 0.0;
  6873. result.m[14] = 0.0;
  6874. result.m[15] = 1.0;
  6875. result._markAsUpdated();
  6876. };
  6877. Matrix._tempQuaternion = new Quaternion();
  6878. Matrix._xAxis = Vector3.Zero();
  6879. Matrix._yAxis = Vector3.Zero();
  6880. Matrix._zAxis = Vector3.Zero();
  6881. Matrix._updateFlagSeed = 0;
  6882. Matrix._identityReadOnly = Matrix.Identity();
  6883. return Matrix;
  6884. }());
  6885. BABYLON.Matrix = Matrix;
  6886. /**
  6887. * Represens a plane by the equation ax + by + cz + d = 0
  6888. */
  6889. var Plane = /** @class */ (function () {
  6890. /**
  6891. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6892. * @param a a component of the plane
  6893. * @param b b component of the plane
  6894. * @param c c component of the plane
  6895. * @param d d component of the plane
  6896. */
  6897. function Plane(a, b, c, d) {
  6898. this.normal = new Vector3(a, b, c);
  6899. this.d = d;
  6900. }
  6901. /**
  6902. * @returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6903. */
  6904. Plane.prototype.asArray = function () {
  6905. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6906. };
  6907. // Methods
  6908. /**
  6909. * @returns a new plane copied from the current Plane.
  6910. */
  6911. Plane.prototype.clone = function () {
  6912. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6913. };
  6914. /**
  6915. * @returns the string "Plane".
  6916. */
  6917. Plane.prototype.getClassName = function () {
  6918. return "Plane";
  6919. };
  6920. /**
  6921. * @returns the Plane hash code.
  6922. */
  6923. Plane.prototype.getHashCode = function () {
  6924. var hash = this.normal.getHashCode();
  6925. hash = (hash * 397) ^ (this.d || 0);
  6926. return hash;
  6927. };
  6928. /**
  6929. * Normalize the current Plane in place.
  6930. * @returns the updated Plane.
  6931. */
  6932. Plane.prototype.normalize = function () {
  6933. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6934. var magnitude = 0.0;
  6935. if (norm !== 0) {
  6936. magnitude = 1.0 / norm;
  6937. }
  6938. this.normal.x *= magnitude;
  6939. this.normal.y *= magnitude;
  6940. this.normal.z *= magnitude;
  6941. this.d *= magnitude;
  6942. return this;
  6943. };
  6944. /**
  6945. * Applies a transformation the plane and returns the result
  6946. * @param transformation the transformation matrix to be applied to the plane
  6947. * @returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6948. */
  6949. Plane.prototype.transform = function (transformation) {
  6950. var transposedMatrix = Matrix.Transpose(transformation);
  6951. var x = this.normal.x;
  6952. var y = this.normal.y;
  6953. var z = this.normal.z;
  6954. var d = this.d;
  6955. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6956. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6957. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6958. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6959. return new Plane(normalX, normalY, normalZ, finalD);
  6960. };
  6961. /**
  6962. * Calcualtte the dot product between the point and the plane normal
  6963. * @param point point to calculate the dot product with
  6964. * @returns the dot product (float) of the point coordinates and the plane normal.
  6965. */
  6966. Plane.prototype.dotCoordinate = function (point) {
  6967. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6968. };
  6969. /**
  6970. * Updates the current Plane from the plane defined by the three given points.
  6971. * @param point1 one of the points used to contruct the plane
  6972. * @param point2 one of the points used to contruct the plane
  6973. * @param point3 one of the points used to contruct the plane
  6974. * @returns the updated Plane.
  6975. */
  6976. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6977. var x1 = point2.x - point1.x;
  6978. var y1 = point2.y - point1.y;
  6979. var z1 = point2.z - point1.z;
  6980. var x2 = point3.x - point1.x;
  6981. var y2 = point3.y - point1.y;
  6982. var z2 = point3.z - point1.z;
  6983. var yz = (y1 * z2) - (z1 * y2);
  6984. var xz = (z1 * x2) - (x1 * z2);
  6985. var xy = (x1 * y2) - (y1 * x2);
  6986. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6987. var invPyth;
  6988. if (pyth !== 0) {
  6989. invPyth = 1.0 / pyth;
  6990. }
  6991. else {
  6992. invPyth = 0.0;
  6993. }
  6994. this.normal.x = yz * invPyth;
  6995. this.normal.y = xz * invPyth;
  6996. this.normal.z = xy * invPyth;
  6997. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6998. return this;
  6999. };
  7000. /**
  7001. * Checks if the plane is facing a given direction
  7002. * @param direction the direction to check if the plane is facing
  7003. * @param epsilon value the dot product is compared against (returns true if dot <= epsilon)
  7004. * @returns True is the vector "direction" is the same side than the plane normal.
  7005. */
  7006. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  7007. var dot = Vector3.Dot(this.normal, direction);
  7008. return (dot <= epsilon);
  7009. };
  7010. /**
  7011. * Calculates the distance to a point
  7012. * @param point point to calculate distance to
  7013. * @returns the signed distance (float) from the given point to the Plane.
  7014. */
  7015. Plane.prototype.signedDistanceTo = function (point) {
  7016. return Vector3.Dot(point, this.normal) + this.d;
  7017. };
  7018. // Statics
  7019. /**
  7020. * Creates a plane from an array
  7021. * @param array the array to create a plane from
  7022. * @returns a new Plane from the given array.
  7023. */
  7024. Plane.FromArray = function (array) {
  7025. return new Plane(array[0], array[1], array[2], array[3]);
  7026. };
  7027. /**
  7028. * Creates a plane from three points
  7029. * @param point1 point used to create the plane
  7030. * @param point2 point used to create the plane
  7031. * @param point3 point used to create the plane
  7032. * @returns a new Plane defined by the three given points.
  7033. */
  7034. Plane.FromPoints = function (point1, point2, point3) {
  7035. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  7036. result.copyFromPoints(point1, point2, point3);
  7037. return result;
  7038. };
  7039. /**
  7040. * Creates a plane from an origin point and a normal
  7041. * @param origin origin of the plane to be constructed
  7042. * @param normal normal of the plane to be constructed
  7043. * @returns a new Plane the normal vector to this plane at the given origin point.
  7044. * Note : the vector "normal" is updated because normalized.
  7045. */
  7046. Plane.FromPositionAndNormal = function (origin, normal) {
  7047. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  7048. normal.normalize();
  7049. result.normal = normal;
  7050. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  7051. return result;
  7052. };
  7053. /**
  7054. * Calculates the distance from a plane and a point
  7055. * @param origin origin of the plane to be constructed
  7056. * @param normal normal of the plane to be constructed
  7057. * @param point point to calculate distance to
  7058. * @returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  7059. */
  7060. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  7061. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  7062. return Vector3.Dot(point, normal) + d;
  7063. };
  7064. return Plane;
  7065. }());
  7066. BABYLON.Plane = Plane;
  7067. /**
  7068. * Class used to represent a viewport on screen
  7069. */
  7070. var Viewport = /** @class */ (function () {
  7071. /**
  7072. * Creates a Viewport object located at (x, y) and sized (width, height)
  7073. * @param x defines viewport left coordinate
  7074. * @param y defines viewport top coordinate
  7075. * @param width defines the viewport width
  7076. * @param height defines the viewport height
  7077. */
  7078. function Viewport(
  7079. /** viewport left coordinate */
  7080. x,
  7081. /** viewport top coordinate */
  7082. y,
  7083. /**viewport width */
  7084. width,
  7085. /** viewport height */
  7086. height) {
  7087. this.x = x;
  7088. this.y = y;
  7089. this.width = width;
  7090. this.height = height;
  7091. }
  7092. /**
  7093. * Creates a new viewport using absolute sizing (from 0-> width, 0-> height instead of 0->1)
  7094. * @param renderWidthOrEngine defines either an engine or the rendering width
  7095. * @param renderHeight defines the rendering height
  7096. * @returns a new Viewport
  7097. */
  7098. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  7099. if (renderWidthOrEngine.getRenderWidth) {
  7100. var engine = renderWidthOrEngine;
  7101. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  7102. }
  7103. var renderWidth = renderWidthOrEngine;
  7104. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  7105. };
  7106. /**
  7107. * Returns a new Viewport copied from the current one
  7108. * @returns a new Viewport
  7109. */
  7110. Viewport.prototype.clone = function () {
  7111. return new Viewport(this.x, this.y, this.width, this.height);
  7112. };
  7113. return Viewport;
  7114. }());
  7115. BABYLON.Viewport = Viewport;
  7116. /**
  7117. * Reprasents a camera frustum
  7118. */
  7119. var Frustum = /** @class */ (function () {
  7120. function Frustum() {
  7121. }
  7122. /**
  7123. * Gets the planes representing the frustum
  7124. * @param transform matrix to be applied to the returned planes
  7125. * @returns a new array of 6 Frustum planes computed by the given transformation matrix.
  7126. */
  7127. Frustum.GetPlanes = function (transform) {
  7128. var frustumPlanes = [];
  7129. for (var index = 0; index < 6; index++) {
  7130. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  7131. }
  7132. Frustum.GetPlanesToRef(transform, frustumPlanes);
  7133. return frustumPlanes;
  7134. };
  7135. /**
  7136. * Gets the near frustum plane transformed by the transform matrix
  7137. * @param transform transformation matrix to be applied to the resulting frustum plane
  7138. * @param frustumPlane the resuling frustum plane
  7139. */
  7140. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  7141. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  7142. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  7143. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  7144. frustumPlane.d = transform.m[15] + transform.m[14];
  7145. frustumPlane.normalize();
  7146. };
  7147. /**
  7148. * Gets the far frustum plane transformed by the transform matrix
  7149. * @param transform transformation matrix to be applied to the resulting frustum plane
  7150. * @param frustumPlane the resuling frustum plane
  7151. */
  7152. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  7153. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  7154. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  7155. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  7156. frustumPlane.d = transform.m[15] - transform.m[14];
  7157. frustumPlane.normalize();
  7158. };
  7159. /**
  7160. * Gets the left frustum plane transformed by the transform matrix
  7161. * @param transform transformation matrix to be applied to the resulting frustum plane
  7162. * @param frustumPlane the resuling frustum plane
  7163. */
  7164. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  7165. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  7166. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  7167. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  7168. frustumPlane.d = transform.m[15] + transform.m[12];
  7169. frustumPlane.normalize();
  7170. };
  7171. /**
  7172. * Gets the right frustum plane transformed by the transform matrix
  7173. * @param transform transformation matrix to be applied to the resulting frustum plane
  7174. * @param frustumPlane the resuling frustum plane
  7175. */
  7176. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  7177. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  7178. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  7179. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  7180. frustumPlane.d = transform.m[15] - transform.m[12];
  7181. frustumPlane.normalize();
  7182. };
  7183. /**
  7184. * Gets the top frustum plane transformed by the transform matrix
  7185. * @param transform transformation matrix to be applied to the resulting frustum plane
  7186. * @param frustumPlane the resuling frustum plane
  7187. */
  7188. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  7189. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  7190. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  7191. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  7192. frustumPlane.d = transform.m[15] - transform.m[13];
  7193. frustumPlane.normalize();
  7194. };
  7195. /**
  7196. * Gets the bottom frustum plane transformed by the transform matrix
  7197. * @param transform transformation matrix to be applied to the resulting frustum plane
  7198. * @param frustumPlane the resuling frustum plane
  7199. */
  7200. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  7201. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  7202. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  7203. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  7204. frustumPlane.d = transform.m[15] + transform.m[13];
  7205. frustumPlane.normalize();
  7206. };
  7207. /**
  7208. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  7209. * @param transform transformation matrix to be applied to the resulting frustum planes
  7210. * @param frustumPlanes the resuling frustum planes
  7211. */
  7212. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  7213. // Near
  7214. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  7215. // Far
  7216. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  7217. // Left
  7218. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  7219. // Right
  7220. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  7221. // Top
  7222. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  7223. // Bottom
  7224. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  7225. };
  7226. return Frustum;
  7227. }());
  7228. BABYLON.Frustum = Frustum;
  7229. /** Defines supported spaces */
  7230. var Space;
  7231. (function (Space) {
  7232. /** Local (object) space */
  7233. Space[Space["LOCAL"] = 0] = "LOCAL";
  7234. /** World space */
  7235. Space[Space["WORLD"] = 1] = "WORLD";
  7236. /** Bone space */
  7237. Space[Space["BONE"] = 2] = "BONE";
  7238. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  7239. /** Defines the 3 main axes */
  7240. var Axis = /** @class */ (function () {
  7241. function Axis() {
  7242. }
  7243. /** X axis */
  7244. Axis.X = new Vector3(1.0, 0.0, 0.0);
  7245. /** Y axis */
  7246. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  7247. /** Z axis */
  7248. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  7249. return Axis;
  7250. }());
  7251. BABYLON.Axis = Axis;
  7252. ;
  7253. /** Class used to represent a Bezier curve */
  7254. var BezierCurve = /** @class */ (function () {
  7255. function BezierCurve() {
  7256. }
  7257. /**
  7258. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats
  7259. * @param t defines the time
  7260. * @param x1 defines the left coordinate on X axis
  7261. * @param y1 defines the left coordinate on Y axis
  7262. * @param x2 defines the right coordinate on X axis
  7263. * @param y2 defines the right coordinate on Y axis
  7264. * @returns the interpolated value
  7265. */
  7266. BezierCurve.Interpolate = function (t, x1, y1, x2, y2) {
  7267. // Extract X (which is equal to time here)
  7268. var f0 = 1 - 3 * x2 + 3 * x1;
  7269. var f1 = 3 * x2 - 6 * x1;
  7270. var f2 = 3 * x1;
  7271. var refinedT = t;
  7272. for (var i = 0; i < 5; i++) {
  7273. var refinedT2 = refinedT * refinedT;
  7274. var refinedT3 = refinedT2 * refinedT;
  7275. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  7276. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  7277. refinedT -= (x - t) * slope;
  7278. refinedT = Math.min(1, Math.max(0, refinedT));
  7279. }
  7280. // Resolve cubic bezier for the given x
  7281. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  7282. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  7283. Math.pow(refinedT, 3);
  7284. };
  7285. return BezierCurve;
  7286. }());
  7287. BABYLON.BezierCurve = BezierCurve;
  7288. /**
  7289. * Defines potential orientation for back face culling
  7290. */
  7291. var Orientation;
  7292. (function (Orientation) {
  7293. /**
  7294. * Clockwise
  7295. */
  7296. Orientation[Orientation["CW"] = 0] = "CW";
  7297. /** Counter clockwise */
  7298. Orientation[Orientation["CCW"] = 1] = "CCW";
  7299. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  7300. /**
  7301. * Defines angle representation
  7302. */
  7303. var Angle = /** @class */ (function () {
  7304. /**
  7305. * Creates an Angle object of "radians" radians (float).
  7306. */
  7307. function Angle(radians) {
  7308. this._radians = radians;
  7309. if (this._radians < 0.0)
  7310. this._radians += (2.0 * Math.PI);
  7311. }
  7312. /**
  7313. * Get value in degrees
  7314. * @returns the Angle value in degrees (float)
  7315. */
  7316. Angle.prototype.degrees = function () {
  7317. return this._radians * 180.0 / Math.PI;
  7318. };
  7319. /**
  7320. * Get value in radians
  7321. * @returns the Angle value in radians (float)
  7322. */
  7323. Angle.prototype.radians = function () {
  7324. return this._radians;
  7325. };
  7326. /**
  7327. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  7328. * @param a defines first vector
  7329. * @param b defines second vector
  7330. * @returns a new Angle
  7331. */
  7332. Angle.BetweenTwoPoints = function (a, b) {
  7333. var delta = b.subtract(a);
  7334. var theta = Math.atan2(delta.y, delta.x);
  7335. return new Angle(theta);
  7336. };
  7337. /**
  7338. * Gets a new Angle object from the given float in radians
  7339. * @param radians defines the angle value in radians
  7340. * @returns a new Angle
  7341. */
  7342. Angle.FromRadians = function (radians) {
  7343. return new Angle(radians);
  7344. };
  7345. /**
  7346. * Gets a new Angle object from the given float in degrees
  7347. * @param degrees defines the angle value in degrees
  7348. * @returns a new Angle
  7349. */
  7350. Angle.FromDegrees = function (degrees) {
  7351. return new Angle(degrees * Math.PI / 180.0);
  7352. };
  7353. return Angle;
  7354. }());
  7355. BABYLON.Angle = Angle;
  7356. /**
  7357. * This represents an arc in a 2d space.
  7358. */
  7359. var Arc2 = /** @class */ (function () {
  7360. /**
  7361. * Creates an Arc object from the three given points : start, middle and end.
  7362. * @param startPoint Defines the start point of the arc
  7363. * @param midPoint Defines the midlle point of the arc
  7364. * @param endPoint Defines the end point of the arc
  7365. */
  7366. function Arc2(
  7367. /** Defines the start point of the arc */
  7368. startPoint,
  7369. /** Defines the mid point of the arc */
  7370. midPoint,
  7371. /** Defines the end point of the arc */
  7372. endPoint) {
  7373. this.startPoint = startPoint;
  7374. this.midPoint = midPoint;
  7375. this.endPoint = endPoint;
  7376. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7377. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7378. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7379. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7380. 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);
  7381. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7382. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7383. var a1 = this.startAngle.degrees();
  7384. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7385. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7386. // angles correction
  7387. if (a2 - a1 > +180.0)
  7388. a2 -= 360.0;
  7389. if (a2 - a1 < -180.0)
  7390. a2 += 360.0;
  7391. if (a3 - a2 > +180.0)
  7392. a3 -= 360.0;
  7393. if (a3 - a2 < -180.0)
  7394. a3 += 360.0;
  7395. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7396. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7397. }
  7398. return Arc2;
  7399. }());
  7400. BABYLON.Arc2 = Arc2;
  7401. /**
  7402. * Represents a 2D path made up of multiple 2D points
  7403. */
  7404. var Path2 = /** @class */ (function () {
  7405. /**
  7406. * Creates a Path2 object from the starting 2D coordinates x and y.
  7407. * @param x the starting points x value
  7408. * @param y the starting points y value
  7409. */
  7410. function Path2(x, y) {
  7411. this._points = new Array();
  7412. this._length = 0.0;
  7413. /**
  7414. * If the path start and end point are the same
  7415. */
  7416. this.closed = false;
  7417. this._points.push(new Vector2(x, y));
  7418. }
  7419. /**
  7420. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7421. * @param x the added points x value
  7422. * @param y the added points y value
  7423. * @returns the updated Path2.
  7424. */
  7425. Path2.prototype.addLineTo = function (x, y) {
  7426. if (this.closed) {
  7427. return this;
  7428. }
  7429. var newPoint = new Vector2(x, y);
  7430. var previousPoint = this._points[this._points.length - 1];
  7431. this._points.push(newPoint);
  7432. this._length += newPoint.subtract(previousPoint).length();
  7433. return this;
  7434. };
  7435. /**
  7436. * 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.
  7437. * @param midX middle point x value
  7438. * @param midY middle point y value
  7439. * @param endX end point x value
  7440. * @param endY end point y value
  7441. * @param numberOfSegments (default: 36)
  7442. * @returns the updated Path2.
  7443. */
  7444. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7445. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7446. if (this.closed) {
  7447. return this;
  7448. }
  7449. var startPoint = this._points[this._points.length - 1];
  7450. var midPoint = new Vector2(midX, midY);
  7451. var endPoint = new Vector2(endX, endY);
  7452. var arc = new Arc2(startPoint, midPoint, endPoint);
  7453. var increment = arc.angle.radians() / numberOfSegments;
  7454. if (arc.orientation === Orientation.CW)
  7455. increment *= -1;
  7456. var currentAngle = arc.startAngle.radians() + increment;
  7457. for (var i = 0; i < numberOfSegments; i++) {
  7458. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7459. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7460. this.addLineTo(x, y);
  7461. currentAngle += increment;
  7462. }
  7463. return this;
  7464. };
  7465. /**
  7466. * Closes the Path2.
  7467. * @returns the Path2.
  7468. */
  7469. Path2.prototype.close = function () {
  7470. this.closed = true;
  7471. return this;
  7472. };
  7473. /**
  7474. * Gets the sum of the distance between each sequential point in the path
  7475. * @returns the Path2 total length (float).
  7476. */
  7477. Path2.prototype.length = function () {
  7478. var result = this._length;
  7479. if (!this.closed) {
  7480. var lastPoint = this._points[this._points.length - 1];
  7481. var firstPoint = this._points[0];
  7482. result += (firstPoint.subtract(lastPoint).length());
  7483. }
  7484. return result;
  7485. };
  7486. /**
  7487. * Gets the points which construct the path
  7488. * @returns the Path2 internal array of points.
  7489. */
  7490. Path2.prototype.getPoints = function () {
  7491. return this._points;
  7492. };
  7493. /**
  7494. * Retreives the point at the distance aways from the starting point
  7495. * @param normalizedLengthPosition the length along the path to retreive the point from
  7496. * @returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7497. */
  7498. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7499. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7500. return Vector2.Zero();
  7501. }
  7502. var lengthPosition = normalizedLengthPosition * this.length();
  7503. var previousOffset = 0;
  7504. for (var i = 0; i < this._points.length; i++) {
  7505. var j = (i + 1) % this._points.length;
  7506. var a = this._points[i];
  7507. var b = this._points[j];
  7508. var bToA = b.subtract(a);
  7509. var nextOffset = (bToA.length() + previousOffset);
  7510. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7511. var dir = bToA.normalize();
  7512. var localOffset = lengthPosition - previousOffset;
  7513. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7514. }
  7515. previousOffset = nextOffset;
  7516. }
  7517. return Vector2.Zero();
  7518. };
  7519. /**
  7520. * Creates a new path starting from an x and y position
  7521. * @param x starting x value
  7522. * @param y starting y value
  7523. * @returns a new Path2 starting at the coordinates (x, y).
  7524. */
  7525. Path2.StartingAt = function (x, y) {
  7526. return new Path2(x, y);
  7527. };
  7528. return Path2;
  7529. }());
  7530. BABYLON.Path2 = Path2;
  7531. /**
  7532. * Represents a 3D path made up of multiple 3D points
  7533. */
  7534. var Path3D = /** @class */ (function () {
  7535. /**
  7536. * new Path3D(path, normal, raw)
  7537. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7538. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7539. * @param path an array of Vector3, the curve axis of the Path3D
  7540. * @param normal (options) Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7541. * @param raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7542. */
  7543. function Path3D(
  7544. /**
  7545. * an array of Vector3, the curve axis of the Path3D
  7546. */
  7547. path, firstNormal, raw) {
  7548. if (firstNormal === void 0) { firstNormal = null; }
  7549. this.path = path;
  7550. this._curve = new Array();
  7551. this._distances = new Array();
  7552. this._tangents = new Array();
  7553. this._normals = new Array();
  7554. this._binormals = new Array();
  7555. for (var p = 0; p < path.length; p++) {
  7556. this._curve[p] = path[p].clone(); // hard copy
  7557. }
  7558. this._raw = raw || false;
  7559. this._compute(firstNormal);
  7560. }
  7561. /**
  7562. * Returns the Path3D array of successive Vector3 designing its curve.
  7563. * @returns the Path3D array of successive Vector3 designing its curve.
  7564. */
  7565. Path3D.prototype.getCurve = function () {
  7566. return this._curve;
  7567. };
  7568. /**
  7569. * Returns an array populated with tangent vectors on each Path3D curve point.
  7570. * @returns an array populated with tangent vectors on each Path3D curve point.
  7571. */
  7572. Path3D.prototype.getTangents = function () {
  7573. return this._tangents;
  7574. };
  7575. /**
  7576. * Returns an array populated with normal vectors on each Path3D curve point.
  7577. * @returns an array populated with normal vectors on each Path3D curve point.
  7578. */
  7579. Path3D.prototype.getNormals = function () {
  7580. return this._normals;
  7581. };
  7582. /**
  7583. * Returns an array populated with binormal vectors on each Path3D curve point.
  7584. * @returns an array populated with binormal vectors on each Path3D curve point.
  7585. */
  7586. Path3D.prototype.getBinormals = function () {
  7587. return this._binormals;
  7588. };
  7589. /**
  7590. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7591. * @returns an array populated with distances (float) of the i-th point from the first curve point.
  7592. */
  7593. Path3D.prototype.getDistances = function () {
  7594. return this._distances;
  7595. };
  7596. /**
  7597. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7598. * @param path path which all values are copied into the curves points
  7599. * @param firstNormal which should be projected onto the curve
  7600. * @returns the same object updated.
  7601. */
  7602. Path3D.prototype.update = function (path, firstNormal) {
  7603. if (firstNormal === void 0) { firstNormal = null; }
  7604. for (var p = 0; p < path.length; p++) {
  7605. this._curve[p].x = path[p].x;
  7606. this._curve[p].y = path[p].y;
  7607. this._curve[p].z = path[p].z;
  7608. }
  7609. this._compute(firstNormal);
  7610. return this;
  7611. };
  7612. // private function compute() : computes tangents, normals and binormals
  7613. Path3D.prototype._compute = function (firstNormal) {
  7614. var l = this._curve.length;
  7615. // first and last tangents
  7616. this._tangents[0] = this._getFirstNonNullVector(0);
  7617. if (!this._raw) {
  7618. this._tangents[0].normalize();
  7619. }
  7620. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7621. if (!this._raw) {
  7622. this._tangents[l - 1].normalize();
  7623. }
  7624. // normals and binormals at first point : arbitrary vector with _normalVector()
  7625. var tg0 = this._tangents[0];
  7626. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7627. this._normals[0] = pp0;
  7628. if (!this._raw) {
  7629. this._normals[0].normalize();
  7630. }
  7631. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7632. if (!this._raw) {
  7633. this._binormals[0].normalize();
  7634. }
  7635. this._distances[0] = 0.0;
  7636. // normals and binormals : next points
  7637. var prev; // previous vector (segment)
  7638. var cur; // current vector (segment)
  7639. var curTang; // current tangent
  7640. // previous normal
  7641. var prevBinor; // previous binormal
  7642. for (var i = 1; i < l; i++) {
  7643. // tangents
  7644. prev = this._getLastNonNullVector(i);
  7645. if (i < l - 1) {
  7646. cur = this._getFirstNonNullVector(i);
  7647. this._tangents[i] = prev.add(cur);
  7648. this._tangents[i].normalize();
  7649. }
  7650. this._distances[i] = this._distances[i - 1] + prev.length();
  7651. // normals and binormals
  7652. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7653. curTang = this._tangents[i];
  7654. prevBinor = this._binormals[i - 1];
  7655. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7656. if (!this._raw) {
  7657. this._normals[i].normalize();
  7658. }
  7659. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7660. if (!this._raw) {
  7661. this._binormals[i].normalize();
  7662. }
  7663. }
  7664. };
  7665. // private function getFirstNonNullVector(index)
  7666. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7667. Path3D.prototype._getFirstNonNullVector = function (index) {
  7668. var i = 1;
  7669. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7670. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7671. i++;
  7672. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7673. }
  7674. return nNVector;
  7675. };
  7676. // private function getLastNonNullVector(index)
  7677. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7678. Path3D.prototype._getLastNonNullVector = function (index) {
  7679. var i = 1;
  7680. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7681. while (nLVector.length() === 0 && index > i + 1) {
  7682. i++;
  7683. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7684. }
  7685. return nLVector;
  7686. };
  7687. // private function normalVector(v0, vt, va) :
  7688. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7689. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7690. Path3D.prototype._normalVector = function (v0, vt, va) {
  7691. var normal0;
  7692. var tgl = vt.length();
  7693. if (tgl === 0.0) {
  7694. tgl = 1.0;
  7695. }
  7696. if (va === undefined || va === null) {
  7697. var point;
  7698. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7699. point = new Vector3(0.0, -1.0, 0.0);
  7700. }
  7701. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7702. point = new Vector3(1.0, 0.0, 0.0);
  7703. }
  7704. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7705. point = new Vector3(0.0, 0.0, 1.0);
  7706. }
  7707. else {
  7708. point = Vector3.Zero();
  7709. }
  7710. normal0 = Vector3.Cross(vt, point);
  7711. }
  7712. else {
  7713. normal0 = Vector3.Cross(vt, va);
  7714. Vector3.CrossToRef(normal0, vt, normal0);
  7715. }
  7716. normal0.normalize();
  7717. return normal0;
  7718. };
  7719. return Path3D;
  7720. }());
  7721. BABYLON.Path3D = Path3D;
  7722. /**
  7723. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7724. * A Curve3 is designed from a series of successive Vector3.
  7725. * @see https://doc.babylonjs.com/how_to/how_to_use_curve3
  7726. */
  7727. var Curve3 = /** @class */ (function () {
  7728. /**
  7729. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7730. * A Curve3 is designed from a series of successive Vector3.
  7731. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7732. * @param points points which make up the curve
  7733. */
  7734. function Curve3(points) {
  7735. this._length = 0.0;
  7736. this._points = points;
  7737. this._length = this._computeLength(points);
  7738. }
  7739. /**
  7740. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7741. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7742. * @param v1 (Vector3) the control point
  7743. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7744. * @param nbPoints (integer) the wanted number of points in the curve
  7745. * @returns the created Curve3
  7746. */
  7747. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7748. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7749. var bez = new Array();
  7750. var equation = function (t, val0, val1, val2) {
  7751. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7752. return res;
  7753. };
  7754. for (var i = 0; i <= nbPoints; i++) {
  7755. 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)));
  7756. }
  7757. return new Curve3(bez);
  7758. };
  7759. /**
  7760. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7761. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7762. * @param v1 (Vector3) the first control point
  7763. * @param v2 (Vector3) the second control point
  7764. * @param v3 (Vector3) the end point of the Cubic Bezier
  7765. * @param nbPoints (integer) the wanted number of points in the curve
  7766. * @returns the created Curve3
  7767. */
  7768. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7769. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7770. var bez = new Array();
  7771. var equation = function (t, val0, val1, val2, val3) {
  7772. 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;
  7773. return res;
  7774. };
  7775. for (var i = 0; i <= nbPoints; i++) {
  7776. 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)));
  7777. }
  7778. return new Curve3(bez);
  7779. };
  7780. /**
  7781. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7782. * @param p1 (Vector3) the origin point of the Hermite Spline
  7783. * @param t1 (Vector3) the tangent vector at the origin point
  7784. * @param p2 (Vector3) the end point of the Hermite Spline
  7785. * @param t2 (Vector3) the tangent vector at the end point
  7786. * @param nbPoints (integer) the wanted number of points in the curve
  7787. * @returns the created Curve3
  7788. */
  7789. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7790. var hermite = new Array();
  7791. var step = 1.0 / nbPoints;
  7792. for (var i = 0; i <= nbPoints; i++) {
  7793. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7794. }
  7795. return new Curve3(hermite);
  7796. };
  7797. /**
  7798. * Returns a Curve3 object along a CatmullRom Spline curve :
  7799. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7800. * @param nbPoints (integer) the wanted number of points between each curve control points
  7801. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7802. * @returns the created Curve3
  7803. */
  7804. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7805. var catmullRom = new Array();
  7806. var step = 1.0 / nbPoints;
  7807. var amount = 0.0;
  7808. if (closed) {
  7809. var pointsCount = points.length;
  7810. for (var i = 0; i < pointsCount; i++) {
  7811. amount = 0;
  7812. for (var c = 0; c < nbPoints; c++) {
  7813. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7814. amount += step;
  7815. }
  7816. }
  7817. catmullRom.push(catmullRom[0]);
  7818. }
  7819. else {
  7820. var totalPoints = new Array();
  7821. totalPoints.push(points[0].clone());
  7822. Array.prototype.push.apply(totalPoints, points);
  7823. totalPoints.push(points[points.length - 1].clone());
  7824. for (var i = 0; i < totalPoints.length - 3; i++) {
  7825. amount = 0;
  7826. for (var c = 0; c < nbPoints; c++) {
  7827. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7828. amount += step;
  7829. }
  7830. }
  7831. i--;
  7832. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7833. }
  7834. return new Curve3(catmullRom);
  7835. };
  7836. /**
  7837. * @returns the Curve3 stored array of successive Vector3
  7838. */
  7839. Curve3.prototype.getPoints = function () {
  7840. return this._points;
  7841. };
  7842. /**
  7843. * @returns the computed length (float) of the curve.
  7844. */
  7845. Curve3.prototype.length = function () {
  7846. return this._length;
  7847. };
  7848. /**
  7849. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7850. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7851. * curveA and curveB keep unchanged.
  7852. * @param curve the curve to continue from this curve
  7853. * @returns the newly constructed curve
  7854. */
  7855. Curve3.prototype.continue = function (curve) {
  7856. var lastPoint = this._points[this._points.length - 1];
  7857. var continuedPoints = this._points.slice();
  7858. var curvePoints = curve.getPoints();
  7859. for (var i = 1; i < curvePoints.length; i++) {
  7860. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7861. }
  7862. var continuedCurve = new Curve3(continuedPoints);
  7863. return continuedCurve;
  7864. };
  7865. Curve3.prototype._computeLength = function (path) {
  7866. var l = 0;
  7867. for (var i = 1; i < path.length; i++) {
  7868. l += (path[i].subtract(path[i - 1])).length();
  7869. }
  7870. return l;
  7871. };
  7872. return Curve3;
  7873. }());
  7874. BABYLON.Curve3 = Curve3;
  7875. // Vertex formats
  7876. /**
  7877. * Contains position and normal vectors for a vertex
  7878. */
  7879. var PositionNormalVertex = /** @class */ (function () {
  7880. /**
  7881. * Creates a PositionNormalVertex
  7882. * @param position the position of the vertex (defaut: 0,0,0)
  7883. * @param normal the normal of the vertex (defaut: 0,1,0)
  7884. */
  7885. function PositionNormalVertex(
  7886. /** the position of the vertex (defaut: 0,0,0) */
  7887. position,
  7888. /** the normal of the vertex (defaut: 0,1,0) */
  7889. normal) {
  7890. if (position === void 0) { position = Vector3.Zero(); }
  7891. if (normal === void 0) { normal = Vector3.Up(); }
  7892. this.position = position;
  7893. this.normal = normal;
  7894. }
  7895. /**
  7896. * Clones the PositionNormalVertex
  7897. * @returns the cloned PositionNormalVertex
  7898. */
  7899. PositionNormalVertex.prototype.clone = function () {
  7900. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7901. };
  7902. return PositionNormalVertex;
  7903. }());
  7904. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7905. /**
  7906. * Contains position, normal and uv vectors for a vertex
  7907. */
  7908. var PositionNormalTextureVertex = /** @class */ (function () {
  7909. /**
  7910. * Creates a PositionNormalTextureVertex
  7911. * @param position the position of the vertex (defaut: 0,0,0)
  7912. * @param normal the normal of the vertex (defaut: 0,1,0)
  7913. * @param uv the uv of the vertex (default: 0,0)
  7914. */
  7915. function PositionNormalTextureVertex(
  7916. /** the position of the vertex (defaut: 0,0,0) */
  7917. position,
  7918. /** the normal of the vertex (defaut: 0,1,0) */
  7919. normal,
  7920. /** the uv of the vertex (default: 0,0) */
  7921. uv) {
  7922. if (position === void 0) { position = Vector3.Zero(); }
  7923. if (normal === void 0) { normal = Vector3.Up(); }
  7924. if (uv === void 0) { uv = Vector2.Zero(); }
  7925. this.position = position;
  7926. this.normal = normal;
  7927. this.uv = uv;
  7928. }
  7929. /**
  7930. * Clones the PositionNormalTextureVertex
  7931. * @returns the cloned PositionNormalTextureVertex
  7932. */
  7933. PositionNormalTextureVertex.prototype.clone = function () {
  7934. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7935. };
  7936. return PositionNormalTextureVertex;
  7937. }());
  7938. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7939. // Temporary pre-allocated objects for engine internal use
  7940. // usage in any internal function :
  7941. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7942. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7943. /**
  7944. * @hidden
  7945. */
  7946. var Tmp = /** @class */ (function () {
  7947. function Tmp() {
  7948. }
  7949. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7950. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7951. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7952. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7953. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7954. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7955. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7956. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7957. Matrix.Zero(), Matrix.Zero(),
  7958. Matrix.Zero(), Matrix.Zero(),
  7959. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7960. return Tmp;
  7961. }());
  7962. BABYLON.Tmp = Tmp;
  7963. /**
  7964. * @hidden
  7965. * Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7966. */
  7967. var MathTmp = /** @class */ (function () {
  7968. function MathTmp() {
  7969. }
  7970. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7971. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7972. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7973. return MathTmp;
  7974. }());
  7975. })(BABYLON || (BABYLON = {}));
  7976. //# sourceMappingURL=babylon.math.js.map
  7977. var BABYLON;
  7978. (function (BABYLON) {
  7979. var Scalar = /** @class */ (function () {
  7980. function Scalar() {
  7981. }
  7982. /**
  7983. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7984. */
  7985. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7986. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7987. var num = a - b;
  7988. return -epsilon <= num && num <= epsilon;
  7989. };
  7990. /**
  7991. * Returns a string : the upper case translation of the number i to hexadecimal.
  7992. */
  7993. Scalar.ToHex = function (i) {
  7994. var str = i.toString(16);
  7995. if (i <= 15) {
  7996. return ("0" + str).toUpperCase();
  7997. }
  7998. return str.toUpperCase();
  7999. };
  8000. /**
  8001. * Returns -1 if value is negative and +1 is value is positive.
  8002. * Returns the value itself if it's equal to zero.
  8003. */
  8004. Scalar.Sign = function (value) {
  8005. value = +value; // convert to a number
  8006. if (value === 0 || isNaN(value))
  8007. return value;
  8008. return value > 0 ? 1 : -1;
  8009. };
  8010. /**
  8011. * Returns the value itself if it's between min and max.
  8012. * Returns min if the value is lower than min.
  8013. * Returns max if the value is greater than max.
  8014. */
  8015. Scalar.Clamp = function (value, min, max) {
  8016. if (min === void 0) { min = 0; }
  8017. if (max === void 0) { max = 1; }
  8018. return Math.min(max, Math.max(min, value));
  8019. };
  8020. /**
  8021. * Returns the log2 of value.
  8022. */
  8023. Scalar.Log2 = function (value) {
  8024. return Math.log(value) * Math.LOG2E;
  8025. };
  8026. /**
  8027. * Loops the value, so that it is never larger than length and never smaller than 0.
  8028. *
  8029. * This is similar to the modulo operator but it works with floating point numbers.
  8030. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  8031. * With t = 5 and length = 2.5, the result would be 0.0.
  8032. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  8033. */
  8034. Scalar.Repeat = function (value, length) {
  8035. return value - Math.floor(value / length) * length;
  8036. };
  8037. /**
  8038. * Normalize the value between 0.0 and 1.0 using min and max values
  8039. */
  8040. Scalar.Normalize = function (value, min, max) {
  8041. return (value - min) / (max - min);
  8042. };
  8043. /**
  8044. * Denormalize the value from 0.0 and 1.0 using min and max values
  8045. */
  8046. Scalar.Denormalize = function (normalized, min, max) {
  8047. return (normalized * (max - min) + min);
  8048. };
  8049. /**
  8050. * Calculates the shortest difference between two given angles given in degrees.
  8051. */
  8052. Scalar.DeltaAngle = function (current, target) {
  8053. var num = Scalar.Repeat(target - current, 360.0);
  8054. if (num > 180.0) {
  8055. num -= 360.0;
  8056. }
  8057. return num;
  8058. };
  8059. /**
  8060. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  8061. *
  8062. * The returned value will move back and forth between 0 and length
  8063. */
  8064. Scalar.PingPong = function (tx, length) {
  8065. var t = Scalar.Repeat(tx, length * 2.0);
  8066. return length - Math.abs(t - length);
  8067. };
  8068. /**
  8069. * Interpolates between min and max with smoothing at the limits.
  8070. *
  8071. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  8072. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  8073. */
  8074. Scalar.SmoothStep = function (from, to, tx) {
  8075. var t = Scalar.Clamp(tx);
  8076. t = -2.0 * t * t * t + 3.0 * t * t;
  8077. return to * t + from * (1.0 - t);
  8078. };
  8079. /**
  8080. * Moves a value current towards target.
  8081. *
  8082. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  8083. * Negative values of maxDelta pushes the value away from target.
  8084. */
  8085. Scalar.MoveTowards = function (current, target, maxDelta) {
  8086. var result = 0;
  8087. if (Math.abs(target - current) <= maxDelta) {
  8088. result = target;
  8089. }
  8090. else {
  8091. result = current + Scalar.Sign(target - current) * maxDelta;
  8092. }
  8093. return result;
  8094. };
  8095. /**
  8096. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  8097. *
  8098. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  8099. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  8100. */
  8101. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  8102. var num = Scalar.DeltaAngle(current, target);
  8103. var result = 0;
  8104. if (-maxDelta < num && num < maxDelta) {
  8105. result = target;
  8106. }
  8107. else {
  8108. target = current + num;
  8109. result = Scalar.MoveTowards(current, target, maxDelta);
  8110. }
  8111. return result;
  8112. };
  8113. /**
  8114. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  8115. */
  8116. Scalar.Lerp = function (start, end, amount) {
  8117. return start + ((end - start) * amount);
  8118. };
  8119. /**
  8120. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  8121. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  8122. */
  8123. Scalar.LerpAngle = function (start, end, amount) {
  8124. var num = Scalar.Repeat(end - start, 360.0);
  8125. if (num > 180.0) {
  8126. num -= 360.0;
  8127. }
  8128. return start + num * Scalar.Clamp(amount);
  8129. };
  8130. /**
  8131. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  8132. */
  8133. Scalar.InverseLerp = function (a, b, value) {
  8134. var result = 0;
  8135. if (a != b) {
  8136. result = Scalar.Clamp((value - a) / (b - a));
  8137. }
  8138. else {
  8139. result = 0.0;
  8140. }
  8141. return result;
  8142. };
  8143. /**
  8144. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  8145. */
  8146. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  8147. var squared = amount * amount;
  8148. var cubed = amount * squared;
  8149. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  8150. var part2 = (-2.0 * cubed) + (3.0 * squared);
  8151. var part3 = (cubed - (2.0 * squared)) + amount;
  8152. var part4 = cubed - squared;
  8153. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  8154. };
  8155. /**
  8156. * Returns a random float number between and min and max values
  8157. */
  8158. Scalar.RandomRange = function (min, max) {
  8159. if (min === max)
  8160. return min;
  8161. return ((Math.random() * (max - min)) + min);
  8162. };
  8163. /**
  8164. * This function returns percentage of a number in a given range.
  8165. *
  8166. * RangeToPercent(40,20,60) will return 0.5 (50%)
  8167. * RangeToPercent(34,0,100) will return 0.34 (34%)
  8168. */
  8169. Scalar.RangeToPercent = function (number, min, max) {
  8170. return ((number - min) / (max - min));
  8171. };
  8172. /**
  8173. * This function returns number that corresponds to the percentage in a given range.
  8174. *
  8175. * PercentToRange(0.34,0,100) will return 34.
  8176. */
  8177. Scalar.PercentToRange = function (percent, min, max) {
  8178. return ((max - min) * percent + min);
  8179. };
  8180. /**
  8181. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  8182. * @param angle The angle to normalize in radian.
  8183. * @return The converted angle.
  8184. */
  8185. Scalar.NormalizeRadians = function (angle) {
  8186. // More precise but slower version kept for reference.
  8187. // angle = angle % Tools.TwoPi;
  8188. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  8189. //if (angle > Math.PI) {
  8190. // angle -= Tools.TwoPi;
  8191. //}
  8192. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  8193. return angle;
  8194. };
  8195. /**
  8196. * Two pi constants convenient for computation.
  8197. */
  8198. Scalar.TwoPi = Math.PI * 2;
  8199. return Scalar;
  8200. }());
  8201. BABYLON.Scalar = Scalar;
  8202. })(BABYLON || (BABYLON = {}));
  8203. //# sourceMappingURL=babylon.math.scalar.js.map
  8204. //# sourceMappingURL=babylon.mixins.js.map
  8205. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  8206. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  8207. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  8208. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  8209. //# sourceMappingURL=babylon.webgl2.js.map
  8210. var BABYLON;
  8211. (function (BABYLON) {
  8212. var __decoratorInitialStore = {};
  8213. var __mergedStore = {};
  8214. var _copySource = function (creationFunction, source, instanciate) {
  8215. var destination = creationFunction();
  8216. // Tags
  8217. if (BABYLON.Tags) {
  8218. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8219. }
  8220. var classStore = getMergedStore(destination);
  8221. // Properties
  8222. for (var property in classStore) {
  8223. var propertyDescriptor = classStore[property];
  8224. var sourceProperty = source[property];
  8225. var propertyType = propertyDescriptor.type;
  8226. if (sourceProperty !== undefined && sourceProperty !== null) {
  8227. switch (propertyType) {
  8228. case 0: // Value
  8229. case 6: // Mesh reference
  8230. case 11: // Camera reference
  8231. destination[property] = sourceProperty;
  8232. break;
  8233. case 1: // Texture
  8234. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  8235. break;
  8236. case 2: // Color3
  8237. case 3: // FresnelParameters
  8238. case 4: // Vector2
  8239. case 5: // Vector3
  8240. case 7: // Color Curves
  8241. case 10: // Quaternion
  8242. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  8243. break;
  8244. }
  8245. }
  8246. }
  8247. return destination;
  8248. };
  8249. function getDirectStore(target) {
  8250. var classKey = target.getClassName();
  8251. if (!__decoratorInitialStore[classKey]) {
  8252. __decoratorInitialStore[classKey] = {};
  8253. }
  8254. return __decoratorInitialStore[classKey];
  8255. }
  8256. /**
  8257. * Return the list of properties flagged as serializable
  8258. * @param target: host object
  8259. */
  8260. function getMergedStore(target) {
  8261. var classKey = target.getClassName();
  8262. if (__mergedStore[classKey]) {
  8263. return __mergedStore[classKey];
  8264. }
  8265. __mergedStore[classKey] = {};
  8266. var store = __mergedStore[classKey];
  8267. var currentTarget = target;
  8268. var currentKey = classKey;
  8269. while (currentKey) {
  8270. var initialStore = __decoratorInitialStore[currentKey];
  8271. for (var property in initialStore) {
  8272. store[property] = initialStore[property];
  8273. }
  8274. var parent_1 = void 0;
  8275. var done = false;
  8276. do {
  8277. parent_1 = Object.getPrototypeOf(currentTarget);
  8278. if (!parent_1.getClassName) {
  8279. done = true;
  8280. break;
  8281. }
  8282. if (parent_1.getClassName() !== currentKey) {
  8283. break;
  8284. }
  8285. currentTarget = parent_1;
  8286. } while (parent_1);
  8287. if (done) {
  8288. break;
  8289. }
  8290. currentKey = parent_1.getClassName();
  8291. currentTarget = parent_1;
  8292. }
  8293. return store;
  8294. }
  8295. function generateSerializableMember(type, sourceName) {
  8296. return function (target, propertyKey) {
  8297. var classStore = getDirectStore(target);
  8298. if (!classStore[propertyKey]) {
  8299. classStore[propertyKey] = { type: type, sourceName: sourceName };
  8300. }
  8301. };
  8302. }
  8303. function generateExpandMember(setCallback, targetKey) {
  8304. if (targetKey === void 0) { targetKey = null; }
  8305. return function (target, propertyKey) {
  8306. var key = targetKey || ("_" + propertyKey);
  8307. Object.defineProperty(target, propertyKey, {
  8308. get: function () {
  8309. return this[key];
  8310. },
  8311. set: function (value) {
  8312. if (this[key] === value) {
  8313. return;
  8314. }
  8315. this[key] = value;
  8316. target[setCallback].apply(this);
  8317. },
  8318. enumerable: true,
  8319. configurable: true
  8320. });
  8321. };
  8322. }
  8323. function expandToProperty(callback, targetKey) {
  8324. if (targetKey === void 0) { targetKey = null; }
  8325. return generateExpandMember(callback, targetKey);
  8326. }
  8327. BABYLON.expandToProperty = expandToProperty;
  8328. function serialize(sourceName) {
  8329. return generateSerializableMember(0, sourceName); // value member
  8330. }
  8331. BABYLON.serialize = serialize;
  8332. function serializeAsTexture(sourceName) {
  8333. return generateSerializableMember(1, sourceName); // texture member
  8334. }
  8335. BABYLON.serializeAsTexture = serializeAsTexture;
  8336. function serializeAsColor3(sourceName) {
  8337. return generateSerializableMember(2, sourceName); // color3 member
  8338. }
  8339. BABYLON.serializeAsColor3 = serializeAsColor3;
  8340. function serializeAsFresnelParameters(sourceName) {
  8341. return generateSerializableMember(3, sourceName); // fresnel parameters member
  8342. }
  8343. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  8344. function serializeAsVector2(sourceName) {
  8345. return generateSerializableMember(4, sourceName); // vector2 member
  8346. }
  8347. BABYLON.serializeAsVector2 = serializeAsVector2;
  8348. function serializeAsVector3(sourceName) {
  8349. return generateSerializableMember(5, sourceName); // vector3 member
  8350. }
  8351. BABYLON.serializeAsVector3 = serializeAsVector3;
  8352. function serializeAsMeshReference(sourceName) {
  8353. return generateSerializableMember(6, sourceName); // mesh reference member
  8354. }
  8355. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  8356. function serializeAsColorCurves(sourceName) {
  8357. return generateSerializableMember(7, sourceName); // color curves
  8358. }
  8359. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  8360. function serializeAsColor4(sourceName) {
  8361. return generateSerializableMember(8, sourceName); // color 4
  8362. }
  8363. BABYLON.serializeAsColor4 = serializeAsColor4;
  8364. function serializeAsImageProcessingConfiguration(sourceName) {
  8365. return generateSerializableMember(9, sourceName); // image processing
  8366. }
  8367. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  8368. function serializeAsQuaternion(sourceName) {
  8369. return generateSerializableMember(10, sourceName); // quaternion member
  8370. }
  8371. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  8372. /**
  8373. * Decorator used to define property that can be serialized as reference to a camera
  8374. * @param sourceName defines the name of the property to decorate
  8375. */
  8376. function serializeAsCameraReference(sourceName) {
  8377. return generateSerializableMember(11, sourceName); // camera reference member
  8378. }
  8379. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  8380. var SerializationHelper = /** @class */ (function () {
  8381. function SerializationHelper() {
  8382. }
  8383. SerializationHelper.Serialize = function (entity, serializationObject) {
  8384. if (!serializationObject) {
  8385. serializationObject = {};
  8386. }
  8387. // Tags
  8388. if (BABYLON.Tags) {
  8389. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  8390. }
  8391. var serializedProperties = getMergedStore(entity);
  8392. // Properties
  8393. for (var property in serializedProperties) {
  8394. var propertyDescriptor = serializedProperties[property];
  8395. var targetPropertyName = propertyDescriptor.sourceName || property;
  8396. var propertyType = propertyDescriptor.type;
  8397. var sourceProperty = entity[property];
  8398. if (sourceProperty !== undefined && sourceProperty !== null) {
  8399. switch (propertyType) {
  8400. case 0: // Value
  8401. serializationObject[targetPropertyName] = sourceProperty;
  8402. break;
  8403. case 1: // Texture
  8404. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8405. break;
  8406. case 2: // Color3
  8407. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8408. break;
  8409. case 3: // FresnelParameters
  8410. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8411. break;
  8412. case 4: // Vector2
  8413. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8414. break;
  8415. case 5: // Vector3
  8416. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8417. break;
  8418. case 6: // Mesh reference
  8419. serializationObject[targetPropertyName] = sourceProperty.id;
  8420. break;
  8421. case 7: // Color Curves
  8422. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8423. break;
  8424. case 8: // Color 4
  8425. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8426. break;
  8427. case 9: // Image Processing
  8428. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8429. break;
  8430. case 10: // Quaternion
  8431. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8432. break;
  8433. case 11: // Camera reference
  8434. serializationObject[targetPropertyName] = sourceProperty.id;
  8435. break;
  8436. }
  8437. }
  8438. }
  8439. return serializationObject;
  8440. };
  8441. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  8442. if (rootUrl === void 0) { rootUrl = null; }
  8443. var destination = creationFunction();
  8444. if (!rootUrl) {
  8445. rootUrl = "";
  8446. }
  8447. // Tags
  8448. if (BABYLON.Tags) {
  8449. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8450. }
  8451. var classStore = getMergedStore(destination);
  8452. // Properties
  8453. for (var property in classStore) {
  8454. var propertyDescriptor = classStore[property];
  8455. var sourceProperty = source[propertyDescriptor.sourceName || property];
  8456. var propertyType = propertyDescriptor.type;
  8457. if (sourceProperty !== undefined && sourceProperty !== null) {
  8458. var dest = destination;
  8459. switch (propertyType) {
  8460. case 0: // Value
  8461. dest[property] = sourceProperty;
  8462. break;
  8463. case 1: // Texture
  8464. if (scene) {
  8465. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8466. }
  8467. break;
  8468. case 2: // Color3
  8469. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8470. break;
  8471. case 3: // FresnelParameters
  8472. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8473. break;
  8474. case 4: // Vector2
  8475. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8476. break;
  8477. case 5: // Vector3
  8478. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8479. break;
  8480. case 6: // Mesh reference
  8481. if (scene) {
  8482. dest[property] = scene.getLastMeshByID(sourceProperty);
  8483. }
  8484. break;
  8485. case 7: // Color Curves
  8486. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8487. break;
  8488. case 8: // Color 4
  8489. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8490. break;
  8491. case 9: // Image Processing
  8492. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8493. break;
  8494. case 10: // Quaternion
  8495. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8496. break;
  8497. case 11: // Camera reference
  8498. if (scene) {
  8499. dest[property] = scene.getCameraByID(sourceProperty);
  8500. }
  8501. break;
  8502. }
  8503. }
  8504. }
  8505. return destination;
  8506. };
  8507. SerializationHelper.Clone = function (creationFunction, source) {
  8508. return _copySource(creationFunction, source, false);
  8509. };
  8510. SerializationHelper.Instanciate = function (creationFunction, source) {
  8511. return _copySource(creationFunction, source, true);
  8512. };
  8513. return SerializationHelper;
  8514. }());
  8515. BABYLON.SerializationHelper = SerializationHelper;
  8516. })(BABYLON || (BABYLON = {}));
  8517. //# sourceMappingURL=babylon.decorators.js.map
  8518. var BABYLON;
  8519. (function (BABYLON) {
  8520. /**
  8521. * Wrapper class for promise with external resolve and reject.
  8522. */
  8523. var Deferred = /** @class */ (function () {
  8524. /**
  8525. * Constructor for this deferred object.
  8526. */
  8527. function Deferred() {
  8528. var _this = this;
  8529. this.promise = new Promise(function (resolve, reject) {
  8530. _this._resolve = resolve;
  8531. _this._reject = reject;
  8532. });
  8533. }
  8534. Object.defineProperty(Deferred.prototype, "resolve", {
  8535. /**
  8536. * The resolve method of the promise associated with this deferred object.
  8537. */
  8538. get: function () {
  8539. return this._resolve;
  8540. },
  8541. enumerable: true,
  8542. configurable: true
  8543. });
  8544. Object.defineProperty(Deferred.prototype, "reject", {
  8545. /**
  8546. * The reject method of the promise associated with this deferred object.
  8547. */
  8548. get: function () {
  8549. return this._reject;
  8550. },
  8551. enumerable: true,
  8552. configurable: true
  8553. });
  8554. return Deferred;
  8555. }());
  8556. BABYLON.Deferred = Deferred;
  8557. })(BABYLON || (BABYLON = {}));
  8558. //# sourceMappingURL=babylon.deferred.js.map
  8559. var BABYLON;
  8560. (function (BABYLON) {
  8561. /**
  8562. * A class serves as a medium between the observable and its observers
  8563. */
  8564. var EventState = /** @class */ (function () {
  8565. /**
  8566. * Create a new EventState
  8567. * @param mask defines the mask associated with this state
  8568. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8569. * @param target defines the original target of the state
  8570. * @param currentTarget defines the current target of the state
  8571. */
  8572. function EventState(mask, skipNextObservers, target, currentTarget) {
  8573. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8574. this.initalize(mask, skipNextObservers, target, currentTarget);
  8575. }
  8576. /**
  8577. * Initialize the current event state
  8578. * @param mask defines the mask associated with this state
  8579. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8580. * @param target defines the original target of the state
  8581. * @param currentTarget defines the current target of the state
  8582. * @returns the current event state
  8583. */
  8584. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8585. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8586. this.mask = mask;
  8587. this.skipNextObservers = skipNextObservers;
  8588. this.target = target;
  8589. this.currentTarget = currentTarget;
  8590. return this;
  8591. };
  8592. return EventState;
  8593. }());
  8594. BABYLON.EventState = EventState;
  8595. /**
  8596. * Represent an Observer registered to a given Observable object.
  8597. */
  8598. var Observer = /** @class */ (function () {
  8599. /**
  8600. * Creates a new observer
  8601. * @param callback defines the callback to call when the observer is notified
  8602. * @param mask defines the mask of the observer (used to filter notifications)
  8603. * @param scope defines the current scope used to restore the JS context
  8604. */
  8605. function Observer(
  8606. /**
  8607. * Defines the callback to call when the observer is notified
  8608. */
  8609. callback,
  8610. /**
  8611. * Defines the mask of the observer (used to filter notifications)
  8612. */
  8613. mask,
  8614. /**
  8615. * Defines the current scope used to restore the JS context
  8616. */
  8617. scope) {
  8618. if (scope === void 0) { scope = null; }
  8619. this.callback = callback;
  8620. this.mask = mask;
  8621. this.scope = scope;
  8622. /** @hidden */
  8623. this._willBeUnregistered = false;
  8624. /**
  8625. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8626. */
  8627. this.unregisterOnNextCall = false;
  8628. }
  8629. return Observer;
  8630. }());
  8631. BABYLON.Observer = Observer;
  8632. /**
  8633. * Represent a list of observers registered to multiple Observables object.
  8634. */
  8635. var MultiObserver = /** @class */ (function () {
  8636. function MultiObserver() {
  8637. }
  8638. /**
  8639. * Release associated resources
  8640. */
  8641. MultiObserver.prototype.dispose = function () {
  8642. if (this._observers && this._observables) {
  8643. for (var index = 0; index < this._observers.length; index++) {
  8644. this._observables[index].remove(this._observers[index]);
  8645. }
  8646. }
  8647. this._observers = null;
  8648. this._observables = null;
  8649. };
  8650. /**
  8651. * Raise a callback when one of the observable will notify
  8652. * @param observables defines a list of observables to watch
  8653. * @param callback defines the callback to call on notification
  8654. * @param mask defines the mask used to filter notifications
  8655. * @param scope defines the current scope used to restore the JS context
  8656. * @returns the new MultiObserver
  8657. */
  8658. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8659. if (mask === void 0) { mask = -1; }
  8660. if (scope === void 0) { scope = null; }
  8661. var result = new MultiObserver();
  8662. result._observers = new Array();
  8663. result._observables = observables;
  8664. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8665. var observable = observables_1[_i];
  8666. var observer = observable.add(callback, mask, false, scope);
  8667. if (observer) {
  8668. result._observers.push(observer);
  8669. }
  8670. }
  8671. return result;
  8672. };
  8673. return MultiObserver;
  8674. }());
  8675. BABYLON.MultiObserver = MultiObserver;
  8676. /**
  8677. * The Observable class is a simple implementation of the Observable pattern.
  8678. *
  8679. * 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.
  8680. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8681. * 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).
  8682. * 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.
  8683. */
  8684. var Observable = /** @class */ (function () {
  8685. /**
  8686. * Creates a new observable
  8687. * @param onObserverAdded defines a callback to call when a new observer is added
  8688. */
  8689. function Observable(onObserverAdded) {
  8690. this._observers = new Array();
  8691. this._eventState = new EventState(0);
  8692. if (onObserverAdded) {
  8693. this._onObserverAdded = onObserverAdded;
  8694. }
  8695. }
  8696. /**
  8697. * Create a new Observer with the specified callback
  8698. * @param callback the callback that will be executed for that Observer
  8699. * @param mask the mask used to filter observers
  8700. * @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.
  8701. * @param scope optional scope for the callback to be called from
  8702. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8703. * @returns the new observer created for the callback
  8704. */
  8705. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8706. if (mask === void 0) { mask = -1; }
  8707. if (insertFirst === void 0) { insertFirst = false; }
  8708. if (scope === void 0) { scope = null; }
  8709. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8710. if (!callback) {
  8711. return null;
  8712. }
  8713. var observer = new Observer(callback, mask, scope);
  8714. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8715. if (insertFirst) {
  8716. this._observers.unshift(observer);
  8717. }
  8718. else {
  8719. this._observers.push(observer);
  8720. }
  8721. if (this._onObserverAdded) {
  8722. this._onObserverAdded(observer);
  8723. }
  8724. return observer;
  8725. };
  8726. /**
  8727. * Create a new Observer with the specified callback and unregisters after the next notification
  8728. * @param callback the callback that will be executed for that Observer
  8729. * @returns the new observer created for the callback
  8730. */
  8731. Observable.prototype.addOnce = function (callback) {
  8732. return this.add(callback, undefined, undefined, undefined, true);
  8733. };
  8734. /**
  8735. * Remove an Observer from the Observable object
  8736. * @param observer the instance of the Observer to remove
  8737. * @returns false if it doesn't belong to this Observable
  8738. */
  8739. Observable.prototype.remove = function (observer) {
  8740. if (!observer) {
  8741. return false;
  8742. }
  8743. var index = this._observers.indexOf(observer);
  8744. if (index !== -1) {
  8745. this._deferUnregister(observer);
  8746. return true;
  8747. }
  8748. return false;
  8749. };
  8750. /**
  8751. * Remove a callback from the Observable object
  8752. * @param callback the callback to remove
  8753. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8754. * @returns false if it doesn't belong to this Observable
  8755. */
  8756. Observable.prototype.removeCallback = function (callback, scope) {
  8757. for (var index = 0; index < this._observers.length; index++) {
  8758. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8759. this._deferUnregister(this._observers[index]);
  8760. return true;
  8761. }
  8762. }
  8763. return false;
  8764. };
  8765. Observable.prototype._deferUnregister = function (observer) {
  8766. var _this = this;
  8767. observer.unregisterOnNextCall = false;
  8768. observer._willBeUnregistered = true;
  8769. BABYLON.Tools.SetImmediate(function () {
  8770. _this._remove(observer);
  8771. });
  8772. };
  8773. // This should only be called when not iterating over _observers to avoid callback skipping.
  8774. // Removes an observer from the _observer Array.
  8775. Observable.prototype._remove = function (observer) {
  8776. if (!observer) {
  8777. return false;
  8778. }
  8779. var index = this._observers.indexOf(observer);
  8780. if (index !== -1) {
  8781. this._observers.splice(index, 1);
  8782. return true;
  8783. }
  8784. return false;
  8785. };
  8786. /**
  8787. * Notify all Observers by calling their respective callback with the given data
  8788. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8789. * @param eventData defines the data to send to all observers
  8790. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8791. * @param target defines the original target of the state
  8792. * @param currentTarget defines the current target of the state
  8793. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8794. */
  8795. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8796. if (mask === void 0) { mask = -1; }
  8797. if (!this._observers.length) {
  8798. return true;
  8799. }
  8800. var state = this._eventState;
  8801. state.mask = mask;
  8802. state.target = target;
  8803. state.currentTarget = currentTarget;
  8804. state.skipNextObservers = false;
  8805. state.lastReturnValue = eventData;
  8806. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8807. var obs = _a[_i];
  8808. if (obs._willBeUnregistered) {
  8809. continue;
  8810. }
  8811. if (obs.mask & mask) {
  8812. if (obs.scope) {
  8813. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8814. }
  8815. else {
  8816. state.lastReturnValue = obs.callback(eventData, state);
  8817. }
  8818. if (obs.unregisterOnNextCall) {
  8819. this._deferUnregister(obs);
  8820. }
  8821. }
  8822. if (state.skipNextObservers) {
  8823. return false;
  8824. }
  8825. }
  8826. return true;
  8827. };
  8828. /**
  8829. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8830. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8831. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8832. * and it is crucial that all callbacks will be executed.
  8833. * The order of the callbacks is kept, callbacks are not executed parallel.
  8834. *
  8835. * @param eventData The data to be sent to each callback
  8836. * @param mask is used to filter observers defaults to -1
  8837. * @param target defines the callback target (see EventState)
  8838. * @param currentTarget defines he current object in the bubbling phase
  8839. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8840. */
  8841. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8842. var _this = this;
  8843. if (mask === void 0) { mask = -1; }
  8844. // create an empty promise
  8845. var p = Promise.resolve(eventData);
  8846. // no observers? return this promise.
  8847. if (!this._observers.length) {
  8848. return p;
  8849. }
  8850. var state = this._eventState;
  8851. state.mask = mask;
  8852. state.target = target;
  8853. state.currentTarget = currentTarget;
  8854. state.skipNextObservers = false;
  8855. // execute one callback after another (not using Promise.all, the order is important)
  8856. this._observers.forEach(function (obs) {
  8857. if (state.skipNextObservers) {
  8858. return;
  8859. }
  8860. if (obs._willBeUnregistered) {
  8861. return;
  8862. }
  8863. if (obs.mask & mask) {
  8864. if (obs.scope) {
  8865. p = p.then(function (lastReturnedValue) {
  8866. state.lastReturnValue = lastReturnedValue;
  8867. return obs.callback.apply(obs.scope, [eventData, state]);
  8868. });
  8869. }
  8870. else {
  8871. p = p.then(function (lastReturnedValue) {
  8872. state.lastReturnValue = lastReturnedValue;
  8873. return obs.callback(eventData, state);
  8874. });
  8875. }
  8876. if (obs.unregisterOnNextCall) {
  8877. _this._deferUnregister(obs);
  8878. }
  8879. }
  8880. });
  8881. // return the eventData
  8882. return p.then(function () { return eventData; });
  8883. };
  8884. /**
  8885. * Notify a specific observer
  8886. * @param observer defines the observer to notify
  8887. * @param eventData defines the data to be sent to each callback
  8888. * @param mask is used to filter observers defaults to -1
  8889. */
  8890. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8891. if (mask === void 0) { mask = -1; }
  8892. var state = this._eventState;
  8893. state.mask = mask;
  8894. state.skipNextObservers = false;
  8895. observer.callback(eventData, state);
  8896. };
  8897. /**
  8898. * Gets a boolean indicating if the observable has at least one observer
  8899. * @returns true is the Observable has at least one Observer registered
  8900. */
  8901. Observable.prototype.hasObservers = function () {
  8902. return this._observers.length > 0;
  8903. };
  8904. /**
  8905. * Clear the list of observers
  8906. */
  8907. Observable.prototype.clear = function () {
  8908. this._observers = new Array();
  8909. this._onObserverAdded = null;
  8910. };
  8911. /**
  8912. * Clone the current observable
  8913. * @returns a new observable
  8914. */
  8915. Observable.prototype.clone = function () {
  8916. var result = new Observable();
  8917. result._observers = this._observers.slice(0);
  8918. return result;
  8919. };
  8920. /**
  8921. * Does this observable handles observer registered with a given mask
  8922. * @param mask defines the mask to be tested
  8923. * @return whether or not one observer registered with the given mask is handeled
  8924. **/
  8925. Observable.prototype.hasSpecificMask = function (mask) {
  8926. if (mask === void 0) { mask = -1; }
  8927. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8928. var obs = _a[_i];
  8929. if (obs.mask & mask || obs.mask === mask) {
  8930. return true;
  8931. }
  8932. }
  8933. return false;
  8934. };
  8935. return Observable;
  8936. }());
  8937. BABYLON.Observable = Observable;
  8938. })(BABYLON || (BABYLON = {}));
  8939. //# sourceMappingURL=babylon.observable.js.map
  8940. var BABYLON;
  8941. (function (BABYLON) {
  8942. /**
  8943. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8944. */
  8945. var SmartArray = /** @class */ (function () {
  8946. /**
  8947. * Instantiates a Smart Array.
  8948. * @param capacity defines the default capacity of the array.
  8949. */
  8950. function SmartArray(capacity) {
  8951. /**
  8952. * The active length of the array.
  8953. */
  8954. this.length = 0;
  8955. this.data = new Array(capacity);
  8956. this._id = SmartArray._GlobalId++;
  8957. }
  8958. /**
  8959. * Pushes a value at the end of the active data.
  8960. * @param value defines the object to push in the array.
  8961. */
  8962. SmartArray.prototype.push = function (value) {
  8963. this.data[this.length++] = value;
  8964. if (this.length > this.data.length) {
  8965. this.data.length *= 2;
  8966. }
  8967. };
  8968. /**
  8969. * Iterates over the active data and apply the lambda to them.
  8970. * @param func defines the action to apply on each value.
  8971. */
  8972. SmartArray.prototype.forEach = function (func) {
  8973. for (var index = 0; index < this.length; index++) {
  8974. func(this.data[index]);
  8975. }
  8976. };
  8977. /**
  8978. * Sorts the full sets of data.
  8979. * @param compareFn defines the comparison function to apply.
  8980. */
  8981. SmartArray.prototype.sort = function (compareFn) {
  8982. this.data.sort(compareFn);
  8983. };
  8984. /**
  8985. * Resets the active data to an empty array.
  8986. */
  8987. SmartArray.prototype.reset = function () {
  8988. this.length = 0;
  8989. };
  8990. /**
  8991. * Releases all the data from the array as well as the array.
  8992. */
  8993. SmartArray.prototype.dispose = function () {
  8994. this.reset();
  8995. if (this.data) {
  8996. this.data.length = 0;
  8997. this.data = [];
  8998. }
  8999. };
  9000. /**
  9001. * Concats the active data with a given array.
  9002. * @param array defines the data to concatenate with.
  9003. */
  9004. SmartArray.prototype.concat = function (array) {
  9005. if (array.length === 0) {
  9006. return;
  9007. }
  9008. if (this.length + array.length > this.data.length) {
  9009. this.data.length = (this.length + array.length) * 2;
  9010. }
  9011. for (var index = 0; index < array.length; index++) {
  9012. this.data[this.length++] = (array.data || array)[index];
  9013. }
  9014. };
  9015. /**
  9016. * Returns the position of a value in the active data.
  9017. * @param value defines the value to find the index for
  9018. * @returns the index if found in the active data otherwise -1
  9019. */
  9020. SmartArray.prototype.indexOf = function (value) {
  9021. var position = this.data.indexOf(value);
  9022. if (position >= this.length) {
  9023. return -1;
  9024. }
  9025. return position;
  9026. };
  9027. /**
  9028. * Returns whether an element is part of the active data.
  9029. * @param value defines the value to look for
  9030. * @returns true if found in the active data otherwise false
  9031. */
  9032. SmartArray.prototype.contains = function (value) {
  9033. return this.indexOf(value) !== -1;
  9034. };
  9035. // Statics
  9036. SmartArray._GlobalId = 0;
  9037. return SmartArray;
  9038. }());
  9039. BABYLON.SmartArray = SmartArray;
  9040. /**
  9041. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  9042. * The data in this array can only be present once
  9043. */
  9044. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  9045. __extends(SmartArrayNoDuplicate, _super);
  9046. function SmartArrayNoDuplicate() {
  9047. var _this = _super !== null && _super.apply(this, arguments) || this;
  9048. _this._duplicateId = 0;
  9049. return _this;
  9050. }
  9051. /**
  9052. * Pushes a value at the end of the active data.
  9053. * THIS DOES NOT PREVENT DUPPLICATE DATA
  9054. * @param value defines the object to push in the array.
  9055. */
  9056. SmartArrayNoDuplicate.prototype.push = function (value) {
  9057. _super.prototype.push.call(this, value);
  9058. if (!value.__smartArrayFlags) {
  9059. value.__smartArrayFlags = {};
  9060. }
  9061. value.__smartArrayFlags[this._id] = this._duplicateId;
  9062. };
  9063. /**
  9064. * Pushes a value at the end of the active data.
  9065. * If the data is already present, it won t be added again
  9066. * @param value defines the object to push in the array.
  9067. * @returns true if added false if it was already present
  9068. */
  9069. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  9070. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  9071. return false;
  9072. }
  9073. this.push(value);
  9074. return true;
  9075. };
  9076. /**
  9077. * Resets the active data to an empty array.
  9078. */
  9079. SmartArrayNoDuplicate.prototype.reset = function () {
  9080. _super.prototype.reset.call(this);
  9081. this._duplicateId++;
  9082. };
  9083. /**
  9084. * Concats the active data with a given array.
  9085. * This ensures no dupplicate will be present in the result.
  9086. * @param array defines the data to concatenate with.
  9087. */
  9088. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  9089. if (array.length === 0) {
  9090. return;
  9091. }
  9092. if (this.length + array.length > this.data.length) {
  9093. this.data.length = (this.length + array.length) * 2;
  9094. }
  9095. for (var index = 0; index < array.length; index++) {
  9096. var item = (array.data || array)[index];
  9097. this.pushNoDuplicate(item);
  9098. }
  9099. };
  9100. return SmartArrayNoDuplicate;
  9101. }(SmartArray));
  9102. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  9103. })(BABYLON || (BABYLON = {}));
  9104. //# sourceMappingURL=babylon.smartArray.js.map
  9105. var BABYLON;
  9106. (function (BABYLON) {
  9107. /** Class used to store color4 gradient */
  9108. var ColorGradient = /** @class */ (function () {
  9109. function ColorGradient() {
  9110. }
  9111. /**
  9112. * Will get a color picked randomly between color1 and color2.
  9113. * If color2 is undefined then color1 will be used
  9114. * @param result defines the target Color4 to store the result in
  9115. */
  9116. ColorGradient.prototype.getColorToRef = function (result) {
  9117. if (!this.color2) {
  9118. result.copyFrom(this.color1);
  9119. return;
  9120. }
  9121. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  9122. };
  9123. return ColorGradient;
  9124. }());
  9125. BABYLON.ColorGradient = ColorGradient;
  9126. /** Class used to store color 3 gradient */
  9127. var Color3Gradient = /** @class */ (function () {
  9128. function Color3Gradient() {
  9129. }
  9130. return Color3Gradient;
  9131. }());
  9132. BABYLON.Color3Gradient = Color3Gradient;
  9133. /** Class used to store factor gradient */
  9134. var FactorGradient = /** @class */ (function () {
  9135. function FactorGradient() {
  9136. }
  9137. /**
  9138. * Will get a number picked randomly between factor1 and factor2.
  9139. * If factor2 is undefined then factor1 will be used
  9140. * @returns the picked number
  9141. */
  9142. FactorGradient.prototype.getFactor = function () {
  9143. if (this.factor2 === undefined) {
  9144. return this.factor1;
  9145. }
  9146. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  9147. };
  9148. return FactorGradient;
  9149. }());
  9150. BABYLON.FactorGradient = FactorGradient;
  9151. /**
  9152. * Application error to support additional information when loading a file
  9153. */
  9154. var LoadFileError = /** @class */ (function (_super) {
  9155. __extends(LoadFileError, _super);
  9156. /**
  9157. * Creates a new LoadFileError
  9158. * @param message defines the message of the error
  9159. * @param request defines the optional XHR request
  9160. */
  9161. function LoadFileError(message, request) {
  9162. var _this = _super.call(this, message) || this;
  9163. _this.request = request;
  9164. _this.name = "LoadFileError";
  9165. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  9166. return _this;
  9167. }
  9168. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  9169. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  9170. // Polyfill for Object.setPrototypeOf if necessary.
  9171. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  9172. return LoadFileError;
  9173. }(Error));
  9174. BABYLON.LoadFileError = LoadFileError;
  9175. /**
  9176. * Class used to define a retry strategy when error happens while loading assets
  9177. */
  9178. var RetryStrategy = /** @class */ (function () {
  9179. function RetryStrategy() {
  9180. }
  9181. /**
  9182. * Function used to defines an exponential back off strategy
  9183. * @param maxRetries defines the maximum number of retries (3 by default)
  9184. * @param baseInterval defines the interval between retries
  9185. * @returns the strategy function to use
  9186. */
  9187. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  9188. if (maxRetries === void 0) { maxRetries = 3; }
  9189. if (baseInterval === void 0) { baseInterval = 500; }
  9190. return function (url, request, retryIndex) {
  9191. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  9192. return -1;
  9193. }
  9194. return Math.pow(2, retryIndex) * baseInterval;
  9195. };
  9196. };
  9197. return RetryStrategy;
  9198. }());
  9199. BABYLON.RetryStrategy = RetryStrategy;
  9200. // Screenshots
  9201. var screenshotCanvas;
  9202. var cloneValue = function (source, destinationObject) {
  9203. if (!source)
  9204. return null;
  9205. if (source instanceof BABYLON.Mesh) {
  9206. return null;
  9207. }
  9208. if (source instanceof BABYLON.SubMesh) {
  9209. return source.clone(destinationObject);
  9210. }
  9211. else if (source.clone) {
  9212. return source.clone();
  9213. }
  9214. return null;
  9215. };
  9216. /**
  9217. * Class containing a set of static utilities functions
  9218. */
  9219. var Tools = /** @class */ (function () {
  9220. function Tools() {
  9221. }
  9222. /**
  9223. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  9224. * @param u defines the coordinate on X axis
  9225. * @param v defines the coordinate on Y axis
  9226. * @param width defines the width of the source data
  9227. * @param height defines the height of the source data
  9228. * @param pixels defines the source byte array
  9229. * @param color defines the output color
  9230. */
  9231. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  9232. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  9233. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  9234. var position = (wrappedU + wrappedV * width) * 4;
  9235. color.r = pixels[position] / 255;
  9236. color.g = pixels[position + 1] / 255;
  9237. color.b = pixels[position + 2] / 255;
  9238. color.a = pixels[position + 3] / 255;
  9239. };
  9240. /**
  9241. * Interpolates between a and b via alpha
  9242. * @param a The lower value (returned when alpha = 0)
  9243. * @param b The upper value (returned when alpha = 1)
  9244. * @param alpha The interpolation-factor
  9245. * @return The mixed value
  9246. */
  9247. Tools.Mix = function (a, b, alpha) {
  9248. return a * (1 - alpha) + b * alpha;
  9249. };
  9250. /**
  9251. * Tries to instantiate a new object from a given class name
  9252. * @param className defines the class name to instantiate
  9253. * @returns the new object or null if the system was not able to do the instantiation
  9254. */
  9255. Tools.Instantiate = function (className) {
  9256. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  9257. return Tools.RegisteredExternalClasses[className];
  9258. }
  9259. var arr = className.split(".");
  9260. var fn = (window || this);
  9261. for (var i = 0, len = arr.length; i < len; i++) {
  9262. fn = fn[arr[i]];
  9263. }
  9264. if (typeof fn !== "function") {
  9265. return null;
  9266. }
  9267. return fn;
  9268. };
  9269. /**
  9270. * Provides a slice function that will work even on IE
  9271. * @param data defines the array to slice
  9272. * @param start defines the start of the data (optional)
  9273. * @param end defines the end of the data (optional)
  9274. * @returns the new sliced array
  9275. */
  9276. Tools.Slice = function (data, start, end) {
  9277. if (data.slice) {
  9278. return data.slice(start, end);
  9279. }
  9280. return Array.prototype.slice.call(data, start, end);
  9281. };
  9282. /**
  9283. * Polyfill for setImmediate
  9284. * @param action defines the action to execute after the current execution block
  9285. */
  9286. Tools.SetImmediate = function (action) {
  9287. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  9288. window.setImmediate(action);
  9289. }
  9290. else {
  9291. setTimeout(action, 1);
  9292. }
  9293. };
  9294. /**
  9295. * Function indicating if a number is an exponent of 2
  9296. * @param value defines the value to test
  9297. * @returns true if the value is an exponent of 2
  9298. */
  9299. Tools.IsExponentOfTwo = function (value) {
  9300. var count = 1;
  9301. do {
  9302. count *= 2;
  9303. } while (count < value);
  9304. return count === value;
  9305. };
  9306. /**
  9307. * Returns the nearest 32-bit single precision float representation of a Number
  9308. * @param value A Number. If the parameter is of a different type, it will get converted
  9309. * to a number or to NaN if it cannot be converted
  9310. * @returns number
  9311. */
  9312. Tools.FloatRound = function (value) {
  9313. if (Math.fround) {
  9314. return Math.fround(value);
  9315. }
  9316. return (Tools._tmpFloatArray[0] = value);
  9317. };
  9318. /**
  9319. * Find the next highest power of two.
  9320. * @param x Number to start search from.
  9321. * @return Next highest power of two.
  9322. */
  9323. Tools.CeilingPOT = function (x) {
  9324. x--;
  9325. x |= x >> 1;
  9326. x |= x >> 2;
  9327. x |= x >> 4;
  9328. x |= x >> 8;
  9329. x |= x >> 16;
  9330. x++;
  9331. return x;
  9332. };
  9333. /**
  9334. * Find the next lowest power of two.
  9335. * @param x Number to start search from.
  9336. * @return Next lowest power of two.
  9337. */
  9338. Tools.FloorPOT = function (x) {
  9339. x = x | (x >> 1);
  9340. x = x | (x >> 2);
  9341. x = x | (x >> 4);
  9342. x = x | (x >> 8);
  9343. x = x | (x >> 16);
  9344. return x - (x >> 1);
  9345. };
  9346. /**
  9347. * Find the nearest power of two.
  9348. * @param x Number to start search from.
  9349. * @return Next nearest power of two.
  9350. */
  9351. Tools.NearestPOT = function (x) {
  9352. var c = Tools.CeilingPOT(x);
  9353. var f = Tools.FloorPOT(x);
  9354. return (c - x) > (x - f) ? f : c;
  9355. };
  9356. /**
  9357. * Get the closest exponent of two
  9358. * @param value defines the value to approximate
  9359. * @param max defines the maximum value to return
  9360. * @param mode defines how to define the closest value
  9361. * @returns closest exponent of two of the given value
  9362. */
  9363. Tools.GetExponentOfTwo = function (value, max, mode) {
  9364. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  9365. var pot;
  9366. switch (mode) {
  9367. case BABYLON.Engine.SCALEMODE_FLOOR:
  9368. pot = Tools.FloorPOT(value);
  9369. break;
  9370. case BABYLON.Engine.SCALEMODE_NEAREST:
  9371. pot = Tools.NearestPOT(value);
  9372. break;
  9373. case BABYLON.Engine.SCALEMODE_CEILING:
  9374. default:
  9375. pot = Tools.CeilingPOT(value);
  9376. break;
  9377. }
  9378. return Math.min(pot, max);
  9379. };
  9380. /**
  9381. * Extracts the filename from a path
  9382. * @param path defines the path to use
  9383. * @returns the filename
  9384. */
  9385. Tools.GetFilename = function (path) {
  9386. var index = path.lastIndexOf("/");
  9387. if (index < 0)
  9388. return path;
  9389. return path.substring(index + 1);
  9390. };
  9391. /**
  9392. * Extracts the "folder" part of a path (everything before the filename).
  9393. * @param uri The URI to extract the info from
  9394. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  9395. * @returns The "folder" part of the path
  9396. */
  9397. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  9398. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  9399. var index = uri.lastIndexOf("/");
  9400. if (index < 0) {
  9401. if (returnUnchangedIfNoSlash) {
  9402. return uri;
  9403. }
  9404. return "";
  9405. }
  9406. return uri.substring(0, index + 1);
  9407. };
  9408. /**
  9409. * Extracts text content from a DOM element hierarchy
  9410. * @param element defines the root element
  9411. * @returns a string
  9412. */
  9413. Tools.GetDOMTextContent = function (element) {
  9414. var result = "";
  9415. var child = element.firstChild;
  9416. while (child) {
  9417. if (child.nodeType === 3) {
  9418. result += child.textContent;
  9419. }
  9420. child = child.nextSibling;
  9421. }
  9422. return result;
  9423. };
  9424. /**
  9425. * Convert an angle in radians to degrees
  9426. * @param angle defines the angle to convert
  9427. * @returns the angle in degrees
  9428. */
  9429. Tools.ToDegrees = function (angle) {
  9430. return angle * 180 / Math.PI;
  9431. };
  9432. /**
  9433. * Convert an angle in degrees to radians
  9434. * @param angle defines the angle to convert
  9435. * @returns the angle in radians
  9436. */
  9437. Tools.ToRadians = function (angle) {
  9438. return angle * Math.PI / 180;
  9439. };
  9440. /**
  9441. * Encode a buffer to a base64 string
  9442. * @param buffer defines the buffer to encode
  9443. * @returns the encoded string
  9444. */
  9445. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  9446. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  9447. var output = "";
  9448. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  9449. var i = 0;
  9450. var bytes = new Uint8Array(buffer);
  9451. while (i < bytes.length) {
  9452. chr1 = bytes[i++];
  9453. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  9454. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  9455. enc1 = chr1 >> 2;
  9456. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  9457. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  9458. enc4 = chr3 & 63;
  9459. if (isNaN(chr2)) {
  9460. enc3 = enc4 = 64;
  9461. }
  9462. else if (isNaN(chr3)) {
  9463. enc4 = 64;
  9464. }
  9465. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  9466. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  9467. }
  9468. return "data:image/png;base64," + output;
  9469. };
  9470. /**
  9471. * Extracts minimum and maximum values from a list of indexed positions
  9472. * @param positions defines the positions to use
  9473. * @param indices defines the indices to the positions
  9474. * @param indexStart defines the start index
  9475. * @param indexCount defines the end index
  9476. * @param bias defines bias value to add to the result
  9477. * @return minimum and maximum values
  9478. */
  9479. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  9480. if (bias === void 0) { bias = null; }
  9481. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9482. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9483. for (var index = indexStart; index < indexStart + indexCount; index++) {
  9484. var offset = indices[index] * 3;
  9485. var x = positions[offset];
  9486. var y = positions[offset + 1];
  9487. var z = positions[offset + 2];
  9488. minimum.minimizeInPlaceFromFloats(x, y, z);
  9489. maximum.maximizeInPlaceFromFloats(x, y, z);
  9490. }
  9491. if (bias) {
  9492. minimum.x -= minimum.x * bias.x + bias.y;
  9493. minimum.y -= minimum.y * bias.x + bias.y;
  9494. minimum.z -= minimum.z * bias.x + bias.y;
  9495. maximum.x += maximum.x * bias.x + bias.y;
  9496. maximum.y += maximum.y * bias.x + bias.y;
  9497. maximum.z += maximum.z * bias.x + bias.y;
  9498. }
  9499. return {
  9500. minimum: minimum,
  9501. maximum: maximum
  9502. };
  9503. };
  9504. /**
  9505. * Extracts minimum and maximum values from a list of positions
  9506. * @param positions defines the positions to use
  9507. * @param start defines the start index in the positions array
  9508. * @param count defines the number of positions to handle
  9509. * @param bias defines bias value to add to the result
  9510. * @param stride defines the stride size to use (distance between two positions in the positions array)
  9511. * @return minimum and maximum values
  9512. */
  9513. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  9514. if (bias === void 0) { bias = null; }
  9515. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9516. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9517. if (!stride) {
  9518. stride = 3;
  9519. }
  9520. for (var index = start, offset = start * stride; index < start + count; index++, offset += stride) {
  9521. var x = positions[offset];
  9522. var y = positions[offset + 1];
  9523. var z = positions[offset + 2];
  9524. minimum.minimizeInPlaceFromFloats(x, y, z);
  9525. maximum.maximizeInPlaceFromFloats(x, y, z);
  9526. }
  9527. if (bias) {
  9528. minimum.x -= minimum.x * bias.x + bias.y;
  9529. minimum.y -= minimum.y * bias.x + bias.y;
  9530. minimum.z -= minimum.z * bias.x + bias.y;
  9531. maximum.x += maximum.x * bias.x + bias.y;
  9532. maximum.y += maximum.y * bias.x + bias.y;
  9533. maximum.z += maximum.z * bias.x + bias.y;
  9534. }
  9535. return {
  9536. minimum: minimum,
  9537. maximum: maximum
  9538. };
  9539. };
  9540. /**
  9541. * Returns an array if obj is not an array
  9542. * @param obj defines the object to evaluate as an array
  9543. * @param allowsNullUndefined defines a boolean indicating if obj is allowed to be null or undefined
  9544. * @returns either obj directly if obj is an array or a new array containing obj
  9545. */
  9546. Tools.MakeArray = function (obj, allowsNullUndefined) {
  9547. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  9548. return null;
  9549. return Array.isArray(obj) ? obj : [obj];
  9550. };
  9551. /**
  9552. * Gets the pointer prefix to use
  9553. * @returns "pointer" if touch is enabled. Else returns "mouse"
  9554. */
  9555. Tools.GetPointerPrefix = function () {
  9556. var eventPrefix = "pointer";
  9557. // Check if pointer events are supported
  9558. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  9559. eventPrefix = "mouse";
  9560. }
  9561. return eventPrefix;
  9562. };
  9563. /**
  9564. * Queue a new function into the requested animation frame pool (ie. this function will be executed byt the browser for the next frame)
  9565. * @param func - the function to be called
  9566. * @param requester - the object that will request the next frame. Falls back to window.
  9567. * @returns frame number
  9568. */
  9569. Tools.QueueNewFrame = function (func, requester) {
  9570. if (!Tools.IsWindowObjectExist()) {
  9571. return setTimeout(func, 16);
  9572. }
  9573. if (!requester) {
  9574. requester = window;
  9575. }
  9576. if (requester.requestAnimationFrame) {
  9577. return requester.requestAnimationFrame(func);
  9578. }
  9579. else if (requester.msRequestAnimationFrame) {
  9580. return requester.msRequestAnimationFrame(func);
  9581. }
  9582. else if (requester.webkitRequestAnimationFrame) {
  9583. return requester.webkitRequestAnimationFrame(func);
  9584. }
  9585. else if (requester.mozRequestAnimationFrame) {
  9586. return requester.mozRequestAnimationFrame(func);
  9587. }
  9588. else if (requester.oRequestAnimationFrame) {
  9589. return requester.oRequestAnimationFrame(func);
  9590. }
  9591. else {
  9592. return window.setTimeout(func, 16);
  9593. }
  9594. };
  9595. /**
  9596. * Ask the browser to promote the current element to fullscreen rendering mode
  9597. * @param element defines the DOM element to promote
  9598. */
  9599. Tools.RequestFullscreen = function (element) {
  9600. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9601. if (!requestFunction)
  9602. return;
  9603. requestFunction.call(element);
  9604. };
  9605. /**
  9606. * Asks the browser to exit fullscreen mode
  9607. */
  9608. Tools.ExitFullscreen = function () {
  9609. if (document.exitFullscreen) {
  9610. document.exitFullscreen();
  9611. }
  9612. else if (document.mozCancelFullScreen) {
  9613. document.mozCancelFullScreen();
  9614. }
  9615. else if (document.webkitCancelFullScreen) {
  9616. document.webkitCancelFullScreen();
  9617. }
  9618. else if (document.msCancelFullScreen) {
  9619. document.msCancelFullScreen();
  9620. }
  9621. };
  9622. /**
  9623. * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element.
  9624. * @param url define the url we are trying
  9625. * @param element define the dom element where to configure the cors policy
  9626. */
  9627. Tools.SetCorsBehavior = function (url, element) {
  9628. if (url && url.indexOf("data:") === 0) {
  9629. return;
  9630. }
  9631. if (Tools.CorsBehavior) {
  9632. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9633. element.crossOrigin = Tools.CorsBehavior;
  9634. }
  9635. else {
  9636. var result = Tools.CorsBehavior(url);
  9637. if (result) {
  9638. element.crossOrigin = result;
  9639. }
  9640. }
  9641. }
  9642. };
  9643. // External files
  9644. /**
  9645. * Removes unwanted characters from an url
  9646. * @param url defines the url to clean
  9647. * @returns the cleaned url
  9648. */
  9649. Tools.CleanUrl = function (url) {
  9650. url = url.replace(/#/mg, "%23");
  9651. return url;
  9652. };
  9653. /**
  9654. * Loads an image as an HTMLImageElement.
  9655. * @param input url string, ArrayBuffer, or Blob to load
  9656. * @param onLoad callback called when the image successfully loads
  9657. * @param onError callback called when the image fails to load
  9658. * @param database database for caching
  9659. * @returns the HTMLImageElement of the loaded image
  9660. */
  9661. Tools.LoadImage = function (input, onLoad, onError, database) {
  9662. var url;
  9663. var usingObjectURL = false;
  9664. if (input instanceof ArrayBuffer) {
  9665. url = URL.createObjectURL(new Blob([input]));
  9666. usingObjectURL = true;
  9667. }
  9668. else if (input instanceof Blob) {
  9669. url = URL.createObjectURL(input);
  9670. usingObjectURL = true;
  9671. }
  9672. else {
  9673. url = Tools.CleanUrl(input);
  9674. url = Tools.PreprocessUrl(input);
  9675. }
  9676. var img = new Image();
  9677. Tools.SetCorsBehavior(url, img);
  9678. var loadHandler = function () {
  9679. if (usingObjectURL && img.src) {
  9680. URL.revokeObjectURL(img.src);
  9681. }
  9682. img.removeEventListener("load", loadHandler);
  9683. img.removeEventListener("error", errorHandler);
  9684. onLoad(img);
  9685. };
  9686. var errorHandler = function (err) {
  9687. if (usingObjectURL && img.src) {
  9688. URL.revokeObjectURL(img.src);
  9689. }
  9690. img.removeEventListener("load", loadHandler);
  9691. img.removeEventListener("error", errorHandler);
  9692. Tools.Error("Error while trying to load image: " + input);
  9693. if (onError) {
  9694. onError("Error while trying to load image: " + input, err);
  9695. }
  9696. };
  9697. img.addEventListener("load", loadHandler);
  9698. img.addEventListener("error", errorHandler);
  9699. var noIndexedDB = function () {
  9700. img.src = url;
  9701. };
  9702. var loadFromIndexedDB = function () {
  9703. if (database) {
  9704. database.loadImageFromDB(url, img);
  9705. }
  9706. };
  9707. //ANY database to do!
  9708. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9709. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9710. }
  9711. else {
  9712. if (url.indexOf("file:") !== -1) {
  9713. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9714. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9715. try {
  9716. var blobURL;
  9717. try {
  9718. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9719. }
  9720. catch (ex) {
  9721. // Chrome doesn't support oneTimeOnly parameter
  9722. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9723. }
  9724. img.src = blobURL;
  9725. usingObjectURL = true;
  9726. }
  9727. catch (e) {
  9728. img.src = "";
  9729. }
  9730. return img;
  9731. }
  9732. }
  9733. noIndexedDB();
  9734. }
  9735. return img;
  9736. };
  9737. /**
  9738. * Loads a file
  9739. * @param url url string, ArrayBuffer, or Blob to load
  9740. * @param onSuccess callback called when the file successfully loads
  9741. * @param onProgress callback called while file is loading (if the server supports this mode)
  9742. * @param database database for caching
  9743. * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
  9744. * @param onError callback called when the file fails to load
  9745. * @returns a file request object
  9746. */
  9747. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9748. url = Tools.CleanUrl(url);
  9749. url = Tools.PreprocessUrl(url);
  9750. // If file and file input are set
  9751. if (url.indexOf("file:") !== -1) {
  9752. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9753. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9754. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9755. }
  9756. }
  9757. var loadUrl = Tools.BaseUrl + url;
  9758. var aborted = false;
  9759. var fileRequest = {
  9760. onCompleteObservable: new BABYLON.Observable(),
  9761. abort: function () { return aborted = true; },
  9762. };
  9763. var requestFile = function () {
  9764. var request = new XMLHttpRequest();
  9765. var retryHandle = null;
  9766. fileRequest.abort = function () {
  9767. aborted = true;
  9768. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9769. request.abort();
  9770. }
  9771. if (retryHandle !== null) {
  9772. clearTimeout(retryHandle);
  9773. retryHandle = null;
  9774. }
  9775. };
  9776. var retryLoop = function (retryIndex) {
  9777. request.open('GET', loadUrl, true);
  9778. if (useArrayBuffer) {
  9779. request.responseType = "arraybuffer";
  9780. }
  9781. if (onProgress) {
  9782. request.addEventListener("progress", onProgress);
  9783. }
  9784. var onLoadEnd = function () {
  9785. request.removeEventListener("loadend", onLoadEnd);
  9786. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9787. fileRequest.onCompleteObservable.clear();
  9788. };
  9789. request.addEventListener("loadend", onLoadEnd);
  9790. var onReadyStateChange = function () {
  9791. if (aborted) {
  9792. return;
  9793. }
  9794. // In case of undefined state in some browsers.
  9795. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9796. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9797. request.removeEventListener("readystatechange", onReadyStateChange);
  9798. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9799. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9800. return;
  9801. }
  9802. var retryStrategy = Tools.DefaultRetryStrategy;
  9803. if (retryStrategy) {
  9804. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9805. if (waitTime !== -1) {
  9806. // Prevent the request from completing for retry.
  9807. request.removeEventListener("loadend", onLoadEnd);
  9808. request = new XMLHttpRequest();
  9809. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9810. return;
  9811. }
  9812. }
  9813. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9814. if (onError) {
  9815. onError(request, e);
  9816. }
  9817. else {
  9818. throw e;
  9819. }
  9820. }
  9821. };
  9822. request.addEventListener("readystatechange", onReadyStateChange);
  9823. request.send();
  9824. };
  9825. retryLoop(0);
  9826. };
  9827. // Caching all files
  9828. if (database && database.enableSceneOffline) {
  9829. var noIndexedDB_1 = function (request) {
  9830. if (request && request.status > 400) {
  9831. if (onError) {
  9832. onError(request);
  9833. }
  9834. }
  9835. else {
  9836. if (!aborted) {
  9837. requestFile();
  9838. }
  9839. }
  9840. };
  9841. var loadFromIndexedDB = function () {
  9842. // TODO: database needs to support aborting and should return a IFileRequest
  9843. if (aborted) {
  9844. return;
  9845. }
  9846. if (database) {
  9847. database.loadFileFromDB(url, function (data) {
  9848. if (!aborted) {
  9849. onSuccess(data);
  9850. }
  9851. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9852. }, onProgress ? function (event) {
  9853. if (!aborted) {
  9854. onProgress(event);
  9855. }
  9856. } : undefined, noIndexedDB_1, useArrayBuffer);
  9857. }
  9858. };
  9859. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9860. }
  9861. else {
  9862. requestFile();
  9863. }
  9864. return fileRequest;
  9865. };
  9866. /**
  9867. * Load a script (identified by an url). When the url returns, the
  9868. * content of this file is added into a new script element, attached to the DOM (body element)
  9869. * @param scriptUrl defines the url of the script to laod
  9870. * @param onSuccess defines the callback called when the script is loaded
  9871. * @param onError defines the callback to call if an error occurs
  9872. */
  9873. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9874. if (!Tools.IsWindowObjectExist()) {
  9875. return;
  9876. }
  9877. var head = document.getElementsByTagName('head')[0];
  9878. var script = document.createElement('script');
  9879. script.type = 'text/javascript';
  9880. script.src = scriptUrl;
  9881. script.onload = function () {
  9882. if (onSuccess) {
  9883. onSuccess();
  9884. }
  9885. };
  9886. script.onerror = function (e) {
  9887. if (onError) {
  9888. onError("Unable to load script '" + scriptUrl + "'", e);
  9889. }
  9890. };
  9891. head.appendChild(script);
  9892. };
  9893. /**
  9894. * Loads a file from a blob
  9895. * @param fileToLoad defines the blob to use
  9896. * @param callback defines the callback to call when data is loaded
  9897. * @param progressCallback defines the callback to call during loading process
  9898. * @returns a file request object
  9899. */
  9900. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9901. var reader = new FileReader();
  9902. var request = {
  9903. onCompleteObservable: new BABYLON.Observable(),
  9904. abort: function () { return reader.abort(); },
  9905. };
  9906. reader.onloadend = function (e) {
  9907. request.onCompleteObservable.notifyObservers(request);
  9908. };
  9909. reader.onload = function (e) {
  9910. //target doesn't have result from ts 1.3
  9911. callback(e.target['result']);
  9912. };
  9913. reader.onprogress = progressCallback;
  9914. reader.readAsDataURL(fileToLoad);
  9915. return request;
  9916. };
  9917. /**
  9918. * Loads a file
  9919. * @param fileToLoad defines the file to load
  9920. * @param callback defines the callback to call when data is loaded
  9921. * @param progressCallBack defines the callback to call during loading process
  9922. * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer
  9923. * @returns a file request object
  9924. */
  9925. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9926. var reader = new FileReader();
  9927. var request = {
  9928. onCompleteObservable: new BABYLON.Observable(),
  9929. abort: function () { return reader.abort(); },
  9930. };
  9931. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9932. reader.onerror = function (e) {
  9933. Tools.Log("Error while reading file: " + fileToLoad.name);
  9934. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9935. };
  9936. reader.onload = function (e) {
  9937. //target doesn't have result from ts 1.3
  9938. callback(e.target['result']);
  9939. };
  9940. if (progressCallBack) {
  9941. reader.onprogress = progressCallBack;
  9942. }
  9943. if (!useArrayBuffer) {
  9944. // Asynchronous read
  9945. reader.readAsText(fileToLoad);
  9946. }
  9947. else {
  9948. reader.readAsArrayBuffer(fileToLoad);
  9949. }
  9950. return request;
  9951. };
  9952. /**
  9953. * Creates a data url from a given string content
  9954. * @param content defines the content to convert
  9955. * @returns the new data url link
  9956. */
  9957. Tools.FileAsURL = function (content) {
  9958. var fileBlob = new Blob([content]);
  9959. var url = window.URL || window.webkitURL;
  9960. var link = url.createObjectURL(fileBlob);
  9961. return link;
  9962. };
  9963. /**
  9964. * Format the given number to a specific decimal format
  9965. * @param value defines the number to format
  9966. * @param decimals defines the number of decimals to use
  9967. * @returns the formatted string
  9968. */
  9969. Tools.Format = function (value, decimals) {
  9970. if (decimals === void 0) { decimals = 2; }
  9971. return value.toFixed(decimals);
  9972. };
  9973. /**
  9974. * Checks if a given vector is inside a specific range
  9975. * @param v defines the vector to test
  9976. * @param min defines the minimum range
  9977. * @param max defines the maximum range
  9978. */
  9979. Tools.CheckExtends = function (v, min, max) {
  9980. if (v.x < min.x)
  9981. min.x = v.x;
  9982. if (v.y < min.y)
  9983. min.y = v.y;
  9984. if (v.z < min.z)
  9985. min.z = v.z;
  9986. if (v.x > max.x)
  9987. max.x = v.x;
  9988. if (v.y > max.y)
  9989. max.y = v.y;
  9990. if (v.z > max.z)
  9991. max.z = v.z;
  9992. };
  9993. /**
  9994. * Tries to copy an object by duplicating every property
  9995. * @param source defines the source object
  9996. * @param destination defines the target object
  9997. * @param doNotCopyList defines a list of properties to avoid
  9998. * @param mustCopyList defines a list of properties to copy (even if they start with _)
  9999. */
  10000. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  10001. for (var prop in source) {
  10002. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  10003. continue;
  10004. }
  10005. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  10006. continue;
  10007. }
  10008. var sourceValue = source[prop];
  10009. var typeOfSourceValue = typeof sourceValue;
  10010. if (typeOfSourceValue === "function") {
  10011. continue;
  10012. }
  10013. try {
  10014. if (typeOfSourceValue === "object") {
  10015. if (sourceValue instanceof Array) {
  10016. destination[prop] = [];
  10017. if (sourceValue.length > 0) {
  10018. if (typeof sourceValue[0] == "object") {
  10019. for (var index = 0; index < sourceValue.length; index++) {
  10020. var clonedValue = cloneValue(sourceValue[index], destination);
  10021. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  10022. destination[prop].push(clonedValue);
  10023. }
  10024. }
  10025. }
  10026. else {
  10027. destination[prop] = sourceValue.slice(0);
  10028. }
  10029. }
  10030. }
  10031. else {
  10032. destination[prop] = cloneValue(sourceValue, destination);
  10033. }
  10034. }
  10035. else {
  10036. destination[prop] = sourceValue;
  10037. }
  10038. }
  10039. catch (e) {
  10040. // Just ignore error (it could be because of a read-only property)
  10041. }
  10042. }
  10043. };
  10044. /**
  10045. * Gets a boolean indicating if the given object has no own property
  10046. * @param obj defines the object to test
  10047. * @returns true if object has no own property
  10048. */
  10049. Tools.IsEmpty = function (obj) {
  10050. for (var i in obj) {
  10051. if (obj.hasOwnProperty(i)) {
  10052. return false;
  10053. }
  10054. }
  10055. return true;
  10056. };
  10057. /**
  10058. * Function used to register events at window level
  10059. * @param events defines the events to register
  10060. */
  10061. Tools.RegisterTopRootEvents = function (events) {
  10062. for (var index = 0; index < events.length; index++) {
  10063. var event = events[index];
  10064. window.addEventListener(event.name, event.handler, false);
  10065. try {
  10066. if (window.parent) {
  10067. window.parent.addEventListener(event.name, event.handler, false);
  10068. }
  10069. }
  10070. catch (e) {
  10071. // Silently fails...
  10072. }
  10073. }
  10074. };
  10075. /**
  10076. * Function used to unregister events from window level
  10077. * @param events defines the events to unregister
  10078. */
  10079. Tools.UnregisterTopRootEvents = function (events) {
  10080. for (var index = 0; index < events.length; index++) {
  10081. var event = events[index];
  10082. window.removeEventListener(event.name, event.handler);
  10083. try {
  10084. if (window.parent) {
  10085. window.parent.removeEventListener(event.name, event.handler);
  10086. }
  10087. }
  10088. catch (e) {
  10089. // Silently fails...
  10090. }
  10091. }
  10092. };
  10093. /**
  10094. * Dumps the current bound framebuffer
  10095. * @param width defines the rendering width
  10096. * @param height defines the rendering height
  10097. * @param engine defines the hosting engine
  10098. * @param successCallback defines the callback triggered once the data are available
  10099. * @param mimeType defines the mime type of the result
  10100. * @param fileName defines the filename to download. If present, the result will automatically be downloaded
  10101. */
  10102. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  10103. if (mimeType === void 0) { mimeType = "image/png"; }
  10104. // Read the contents of the framebuffer
  10105. var numberOfChannelsByLine = width * 4;
  10106. var halfHeight = height / 2;
  10107. //Reading datas from WebGL
  10108. var data = engine.readPixels(0, 0, width, height);
  10109. //To flip image on Y axis.
  10110. for (var i = 0; i < halfHeight; i++) {
  10111. for (var j = 0; j < numberOfChannelsByLine; j++) {
  10112. var currentCell = j + i * numberOfChannelsByLine;
  10113. var targetLine = height - i - 1;
  10114. var targetCell = j + targetLine * numberOfChannelsByLine;
  10115. var temp = data[currentCell];
  10116. data[currentCell] = data[targetCell];
  10117. data[targetCell] = temp;
  10118. }
  10119. }
  10120. // Create a 2D canvas to store the result
  10121. if (!screenshotCanvas) {
  10122. screenshotCanvas = document.createElement('canvas');
  10123. }
  10124. screenshotCanvas.width = width;
  10125. screenshotCanvas.height = height;
  10126. var context = screenshotCanvas.getContext('2d');
  10127. if (context) {
  10128. // Copy the pixels to a 2D canvas
  10129. var imageData = context.createImageData(width, height);
  10130. var castData = (imageData.data);
  10131. castData.set(data);
  10132. context.putImageData(imageData, 0, 0);
  10133. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  10134. }
  10135. };
  10136. /**
  10137. * Converts the canvas data to blob.
  10138. * This acts as a polyfill for browsers not supporting the to blob function.
  10139. * @param canvas Defines the canvas to extract the data from
  10140. * @param successCallback Defines the callback triggered once the data are available
  10141. * @param mimeType Defines the mime type of the result
  10142. */
  10143. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  10144. if (mimeType === void 0) { mimeType = "image/png"; }
  10145. // We need HTMLCanvasElement.toBlob for HD screenshots
  10146. if (!canvas.toBlob) {
  10147. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  10148. canvas.toBlob = function (callback, type, quality) {
  10149. var _this = this;
  10150. setTimeout(function () {
  10151. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  10152. for (var i = 0; i < len; i++) {
  10153. arr[i] = binStr.charCodeAt(i);
  10154. }
  10155. callback(new Blob([arr]));
  10156. });
  10157. };
  10158. }
  10159. canvas.toBlob(function (blob) {
  10160. successCallback(blob);
  10161. }, mimeType);
  10162. };
  10163. /**
  10164. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  10165. * @param successCallback defines the callback triggered once the data are available
  10166. * @param mimeType defines the mime type of the result
  10167. * @param fileName defines he filename to download. If present, the result will automatically be downloaded
  10168. */
  10169. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  10170. if (mimeType === void 0) { mimeType = "image/png"; }
  10171. if (successCallback) {
  10172. var base64Image = screenshotCanvas.toDataURL(mimeType);
  10173. successCallback(base64Image);
  10174. }
  10175. else {
  10176. this.ToBlob(screenshotCanvas, function (blob) {
  10177. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  10178. if (("download" in document.createElement("a"))) {
  10179. if (!fileName) {
  10180. var date = new Date();
  10181. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  10182. fileName = "screenshot_" + stringDate + ".png";
  10183. }
  10184. Tools.Download(blob, fileName);
  10185. }
  10186. else {
  10187. var url = URL.createObjectURL(blob);
  10188. var newWindow = window.open("");
  10189. if (!newWindow)
  10190. return;
  10191. var img = newWindow.document.createElement("img");
  10192. img.onload = function () {
  10193. // no longer need to read the blob so it's revoked
  10194. URL.revokeObjectURL(url);
  10195. };
  10196. img.src = url;
  10197. newWindow.document.body.appendChild(img);
  10198. }
  10199. }, mimeType);
  10200. }
  10201. };
  10202. /**
  10203. * Downloads a blob in the browser
  10204. * @param blob defines the blob to download
  10205. * @param fileName defines the name of the downloaded file
  10206. */
  10207. Tools.Download = function (blob, fileName) {
  10208. if (navigator && navigator.msSaveBlob) {
  10209. navigator.msSaveBlob(blob, fileName);
  10210. return;
  10211. }
  10212. var url = window.URL.createObjectURL(blob);
  10213. var a = document.createElement("a");
  10214. document.body.appendChild(a);
  10215. a.style.display = "none";
  10216. a.href = url;
  10217. a.download = fileName;
  10218. a.addEventListener("click", function () {
  10219. if (a.parentElement) {
  10220. a.parentElement.removeChild(a);
  10221. }
  10222. });
  10223. a.click();
  10224. window.URL.revokeObjectURL(url);
  10225. };
  10226. /**
  10227. * Captures a screenshot of the current rendering
  10228. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  10229. * @param engine defines the rendering engine
  10230. * @param camera defines the source camera
  10231. * @param size This parameter can be set to a single number or to an object with the
  10232. * following (optional) properties: precision, width, height. If a single number is passed,
  10233. * it will be used for both width and height. If an object is passed, the screenshot size
  10234. * will be derived from the parameters. The precision property is a multiplier allowing
  10235. * rendering at a higher or lower resolution
  10236. * @param successCallback defines the callback receives a single parameter which contains the
  10237. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  10238. * src parameter of an <img> to display it
  10239. * @param mimeType defines the MIME type of the screenshot image (default: image/png).
  10240. * Check your browser for supported MIME types
  10241. */
  10242. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  10243. if (mimeType === void 0) { mimeType = "image/png"; }
  10244. var width;
  10245. var height;
  10246. // If a precision value is specified
  10247. if (size.precision) {
  10248. width = Math.round(engine.getRenderWidth() * size.precision);
  10249. height = Math.round(width / engine.getAspectRatio(camera));
  10250. }
  10251. else if (size.width && size.height) {
  10252. width = size.width;
  10253. height = size.height;
  10254. }
  10255. //If passing only width, computing height to keep display canvas ratio.
  10256. else if (size.width && !size.height) {
  10257. width = size.width;
  10258. height = Math.round(width / engine.getAspectRatio(camera));
  10259. }
  10260. //If passing only height, computing width to keep display canvas ratio.
  10261. else if (size.height && !size.width) {
  10262. height = size.height;
  10263. width = Math.round(height * engine.getAspectRatio(camera));
  10264. }
  10265. //Assuming here that "size" parameter is a number
  10266. else if (!isNaN(size)) {
  10267. height = size;
  10268. width = size;
  10269. }
  10270. else {
  10271. Tools.Error("Invalid 'size' parameter !");
  10272. return;
  10273. }
  10274. if (!screenshotCanvas) {
  10275. screenshotCanvas = document.createElement('canvas');
  10276. }
  10277. screenshotCanvas.width = width;
  10278. screenshotCanvas.height = height;
  10279. var renderContext = screenshotCanvas.getContext("2d");
  10280. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  10281. var newWidth = width;
  10282. var newHeight = newWidth / ratio;
  10283. if (newHeight > height) {
  10284. newHeight = height;
  10285. newWidth = newHeight * ratio;
  10286. }
  10287. var offsetX = Math.max(0, width - newWidth) / 2;
  10288. var offsetY = Math.max(0, height - newHeight) / 2;
  10289. var renderingCanvas = engine.getRenderingCanvas();
  10290. if (renderContext && renderingCanvas) {
  10291. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  10292. }
  10293. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  10294. };
  10295. /**
  10296. * Generates an image screenshot from the specified camera.
  10297. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  10298. * @param engine The engine to use for rendering
  10299. * @param camera The camera to use for rendering
  10300. * @param size This parameter can be set to a single number or to an object with the
  10301. * following (optional) properties: precision, width, height. If a single number is passed,
  10302. * it will be used for both width and height. If an object is passed, the screenshot size
  10303. * will be derived from the parameters. The precision property is a multiplier allowing
  10304. * rendering at a higher or lower resolution
  10305. * @param successCallback The callback receives a single parameter which contains the
  10306. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  10307. * src parameter of an <img> to display it
  10308. * @param mimeType The MIME type of the screenshot image (default: image/png).
  10309. * Check your browser for supported MIME types
  10310. * @param samples Texture samples (default: 1)
  10311. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  10312. * @param fileName A name for for the downloaded file.
  10313. */
  10314. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  10315. if (mimeType === void 0) { mimeType = "image/png"; }
  10316. if (samples === void 0) { samples = 1; }
  10317. if (antialiasing === void 0) { antialiasing = false; }
  10318. var width;
  10319. var height;
  10320. //If a precision value is specified
  10321. if (size.precision) {
  10322. width = Math.round(engine.getRenderWidth() * size.precision);
  10323. height = Math.round(width / engine.getAspectRatio(camera));
  10324. size = { width: width, height: height };
  10325. }
  10326. else if (size.width && size.height) {
  10327. width = size.width;
  10328. height = size.height;
  10329. }
  10330. //If passing only width, computing height to keep display canvas ratio.
  10331. else if (size.width && !size.height) {
  10332. width = size.width;
  10333. height = Math.round(width / engine.getAspectRatio(camera));
  10334. size = { width: width, height: height };
  10335. }
  10336. //If passing only height, computing width to keep display canvas ratio.
  10337. else if (size.height && !size.width) {
  10338. height = size.height;
  10339. width = Math.round(height * engine.getAspectRatio(camera));
  10340. size = { width: width, height: height };
  10341. }
  10342. //Assuming here that "size" parameter is a number
  10343. else if (!isNaN(size)) {
  10344. height = size;
  10345. width = size;
  10346. }
  10347. else {
  10348. Tools.Error("Invalid 'size' parameter !");
  10349. return;
  10350. }
  10351. var scene = camera.getScene();
  10352. var previousCamera = null;
  10353. if (scene.activeCamera !== camera) {
  10354. previousCamera = scene.activeCamera;
  10355. scene.activeCamera = camera;
  10356. }
  10357. // At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  10358. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10359. texture.renderList = null;
  10360. texture.samples = samples;
  10361. if (antialiasing) {
  10362. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  10363. }
  10364. texture.onAfterRenderObservable.add(function () {
  10365. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  10366. });
  10367. scene.incrementRenderId();
  10368. scene.resetCachedMaterial();
  10369. texture.render(true);
  10370. texture.dispose();
  10371. if (previousCamera) {
  10372. scene.activeCamera = previousCamera;
  10373. }
  10374. camera.getProjectionMatrix(true); // Force cache refresh;
  10375. };
  10376. /**
  10377. * Validates if xhr data is correct
  10378. * @param xhr defines the request to validate
  10379. * @param dataType defines the expected data type
  10380. * @returns true if data is correct
  10381. */
  10382. Tools.ValidateXHRData = function (xhr, dataType) {
  10383. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  10384. if (dataType === void 0) { dataType = 7; }
  10385. try {
  10386. if (dataType & 1) {
  10387. if (xhr.responseText && xhr.responseText.length > 0) {
  10388. return true;
  10389. }
  10390. else if (dataType === 1) {
  10391. return false;
  10392. }
  10393. }
  10394. if (dataType & 2) {
  10395. // Check header width and height since there is no "TGA" magic number
  10396. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  10397. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  10398. return true;
  10399. }
  10400. else if (dataType === 2) {
  10401. return false;
  10402. }
  10403. }
  10404. if (dataType & 4) {
  10405. // Check for the "DDS" magic number
  10406. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  10407. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  10408. return true;
  10409. }
  10410. else {
  10411. return false;
  10412. }
  10413. }
  10414. }
  10415. catch (e) {
  10416. // Global protection
  10417. }
  10418. return false;
  10419. };
  10420. /**
  10421. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  10422. * Be aware Math.random() could cause collisions, but:
  10423. * "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"
  10424. * @returns a pseudo random id
  10425. */
  10426. Tools.RandomId = function () {
  10427. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  10428. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  10429. return v.toString(16);
  10430. });
  10431. };
  10432. /**
  10433. * Test if the given uri is a base64 string
  10434. * @param uri The uri to test
  10435. * @return True if the uri is a base64 string or false otherwise
  10436. */
  10437. Tools.IsBase64 = function (uri) {
  10438. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  10439. };
  10440. /**
  10441. * Decode the given base64 uri.
  10442. * @param uri The uri to decode
  10443. * @return The decoded base64 data.
  10444. */
  10445. Tools.DecodeBase64 = function (uri) {
  10446. var decodedString = atob(uri.split(",")[1]);
  10447. var bufferLength = decodedString.length;
  10448. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  10449. for (var i = 0; i < bufferLength; i++) {
  10450. bufferView[i] = decodedString.charCodeAt(i);
  10451. }
  10452. return bufferView.buffer;
  10453. };
  10454. Tools._AddLogEntry = function (entry) {
  10455. Tools._LogCache = entry + Tools._LogCache;
  10456. if (Tools.OnNewCacheEntry) {
  10457. Tools.OnNewCacheEntry(entry);
  10458. }
  10459. };
  10460. Tools._FormatMessage = function (message) {
  10461. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  10462. var date = new Date();
  10463. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  10464. };
  10465. Tools._LogDisabled = function (message) {
  10466. // nothing to do
  10467. };
  10468. Tools._LogEnabled = function (message) {
  10469. var formattedMessage = Tools._FormatMessage(message);
  10470. console.log("BJS - " + formattedMessage);
  10471. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  10472. Tools._AddLogEntry(entry);
  10473. };
  10474. Tools._WarnDisabled = function (message) {
  10475. // nothing to do
  10476. };
  10477. Tools._WarnEnabled = function (message) {
  10478. var formattedMessage = Tools._FormatMessage(message);
  10479. console.warn("BJS - " + formattedMessage);
  10480. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  10481. Tools._AddLogEntry(entry);
  10482. };
  10483. Tools._ErrorDisabled = function (message) {
  10484. // nothing to do
  10485. };
  10486. Tools._ErrorEnabled = function (message) {
  10487. Tools.errorsCount++;
  10488. var formattedMessage = Tools._FormatMessage(message);
  10489. console.error("BJS - " + formattedMessage);
  10490. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  10491. Tools._AddLogEntry(entry);
  10492. };
  10493. Object.defineProperty(Tools, "LogCache", {
  10494. /**
  10495. * Gets current log cache (list of logs)
  10496. */
  10497. get: function () {
  10498. return Tools._LogCache;
  10499. },
  10500. enumerable: true,
  10501. configurable: true
  10502. });
  10503. /**
  10504. * Clears the log cache
  10505. */
  10506. Tools.ClearLogCache = function () {
  10507. Tools._LogCache = "";
  10508. Tools.errorsCount = 0;
  10509. };
  10510. Object.defineProperty(Tools, "LogLevels", {
  10511. /**
  10512. * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel)
  10513. */
  10514. set: function (level) {
  10515. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  10516. Tools.Log = Tools._LogEnabled;
  10517. }
  10518. else {
  10519. Tools.Log = Tools._LogDisabled;
  10520. }
  10521. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  10522. Tools.Warn = Tools._WarnEnabled;
  10523. }
  10524. else {
  10525. Tools.Warn = Tools._WarnDisabled;
  10526. }
  10527. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  10528. Tools.Error = Tools._ErrorEnabled;
  10529. }
  10530. else {
  10531. Tools.Error = Tools._ErrorDisabled;
  10532. }
  10533. },
  10534. enumerable: true,
  10535. configurable: true
  10536. });
  10537. /**
  10538. * Checks if the loaded document was accessed via `file:`-Protocol.
  10539. * @returns boolean
  10540. */
  10541. Tools.IsFileURL = function () {
  10542. return location.protocol === "file:";
  10543. };
  10544. /**
  10545. * Checks if the window object exists
  10546. * @returns true if the window object exists
  10547. */
  10548. Tools.IsWindowObjectExist = function () {
  10549. return (typeof window) !== "undefined";
  10550. };
  10551. Object.defineProperty(Tools, "PerformanceLogLevel", {
  10552. /**
  10553. * Sets the current performance log level
  10554. */
  10555. set: function (level) {
  10556. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  10557. Tools.StartPerformanceCounter = Tools._StartUserMark;
  10558. Tools.EndPerformanceCounter = Tools._EndUserMark;
  10559. return;
  10560. }
  10561. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  10562. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  10563. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  10564. return;
  10565. }
  10566. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10567. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10568. },
  10569. enumerable: true,
  10570. configurable: true
  10571. });
  10572. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  10573. };
  10574. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  10575. };
  10576. Tools._StartUserMark = function (counterName, condition) {
  10577. if (condition === void 0) { condition = true; }
  10578. if (!Tools._performance) {
  10579. if (!Tools.IsWindowObjectExist()) {
  10580. return;
  10581. }
  10582. Tools._performance = window.performance;
  10583. }
  10584. if (!condition || !Tools._performance.mark) {
  10585. return;
  10586. }
  10587. Tools._performance.mark(counterName + "-Begin");
  10588. };
  10589. Tools._EndUserMark = function (counterName, condition) {
  10590. if (condition === void 0) { condition = true; }
  10591. if (!condition || !Tools._performance.mark) {
  10592. return;
  10593. }
  10594. Tools._performance.mark(counterName + "-End");
  10595. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  10596. };
  10597. Tools._StartPerformanceConsole = function (counterName, condition) {
  10598. if (condition === void 0) { condition = true; }
  10599. if (!condition) {
  10600. return;
  10601. }
  10602. Tools._StartUserMark(counterName, condition);
  10603. if (console.time) {
  10604. console.time(counterName);
  10605. }
  10606. };
  10607. Tools._EndPerformanceConsole = function (counterName, condition) {
  10608. if (condition === void 0) { condition = true; }
  10609. if (!condition) {
  10610. return;
  10611. }
  10612. Tools._EndUserMark(counterName, condition);
  10613. if (console.time) {
  10614. console.timeEnd(counterName);
  10615. }
  10616. };
  10617. Object.defineProperty(Tools, "Now", {
  10618. /**
  10619. * Gets either window.performance.now() if supported or Date.now() else
  10620. */
  10621. get: function () {
  10622. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  10623. return window.performance.now();
  10624. }
  10625. return Date.now();
  10626. },
  10627. enumerable: true,
  10628. configurable: true
  10629. });
  10630. /**
  10631. * This method will return the name of the class used to create the instance of the given object.
  10632. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  10633. * @param object the object to get the class name from
  10634. * @param isType defines if the object is actually a type
  10635. * @returns the name of the class, will be "object" for a custom data type not using the @className decorator
  10636. */
  10637. Tools.GetClassName = function (object, isType) {
  10638. if (isType === void 0) { isType = false; }
  10639. var name = null;
  10640. if (!isType && object.getClassName) {
  10641. name = object.getClassName();
  10642. }
  10643. else {
  10644. if (object instanceof Object) {
  10645. var classObj = isType ? object : Object.getPrototypeOf(object);
  10646. name = classObj.constructor["__bjsclassName__"];
  10647. }
  10648. if (!name) {
  10649. name = typeof object;
  10650. }
  10651. }
  10652. return name;
  10653. };
  10654. /**
  10655. * Gets the first element of an array satisfying a given predicate
  10656. * @param array defines the array to browse
  10657. * @param predicate defines the predicate to use
  10658. * @returns null if not found or the element
  10659. */
  10660. Tools.First = function (array, predicate) {
  10661. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  10662. var el = array_1[_i];
  10663. if (predicate(el)) {
  10664. return el;
  10665. }
  10666. }
  10667. return null;
  10668. };
  10669. /**
  10670. * This method will return the name of the full name of the class, including its owning module (if any).
  10671. * 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).
  10672. * @param object the object to get the class name from
  10673. * @param isType defines if the object is actually a type
  10674. * @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.
  10675. * @ignorenaming
  10676. */
  10677. Tools.getFullClassName = function (object, isType) {
  10678. if (isType === void 0) { isType = false; }
  10679. var className = null;
  10680. var moduleName = null;
  10681. if (!isType && object.getClassName) {
  10682. className = object.getClassName();
  10683. }
  10684. else {
  10685. if (object instanceof Object) {
  10686. var classObj = isType ? object : Object.getPrototypeOf(object);
  10687. className = classObj.constructor["__bjsclassName__"];
  10688. moduleName = classObj.constructor["__bjsmoduleName__"];
  10689. }
  10690. if (!className) {
  10691. className = typeof object;
  10692. }
  10693. }
  10694. if (!className) {
  10695. return null;
  10696. }
  10697. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10698. };
  10699. /**
  10700. * Returns a promise that resolves after the given amount of time.
  10701. * @param delay Number of milliseconds to delay
  10702. * @returns Promise that resolves after the given amount of time
  10703. */
  10704. Tools.DelayAsync = function (delay) {
  10705. return new Promise(function (resolve) {
  10706. setTimeout(function () {
  10707. resolve();
  10708. }, delay);
  10709. });
  10710. };
  10711. /**
  10712. * Gets the current gradient from an array of IValueGradient
  10713. * @param ratio defines the current ratio to get
  10714. * @param gradients defines the array of IValueGradient
  10715. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10716. */
  10717. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10718. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10719. var currentGradient = gradients[gradientIndex];
  10720. var nextGradient = gradients[gradientIndex + 1];
  10721. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10722. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10723. updateFunc(currentGradient, nextGradient, scale);
  10724. return;
  10725. }
  10726. }
  10727. // Use last index if over
  10728. var lastIndex = gradients.length - 1;
  10729. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  10730. };
  10731. /**
  10732. * Gets or sets the base URL to use to load assets
  10733. */
  10734. Tools.BaseUrl = "";
  10735. /**
  10736. * Gets or sets the retry strategy to apply when an error happens while loading an asset
  10737. */
  10738. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10739. /**
  10740. * Default behaviour for cors in the application.
  10741. * It can be a string if the expected behavior is identical in the entire app.
  10742. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10743. */
  10744. Tools.CorsBehavior = "anonymous";
  10745. /**
  10746. * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded
  10747. * @ignorenaming
  10748. */
  10749. Tools.UseFallbackTexture = true;
  10750. /**
  10751. * Use this object to register external classes like custom textures or material
  10752. * to allow the laoders to instantiate them
  10753. */
  10754. Tools.RegisteredExternalClasses = {};
  10755. /**
  10756. * Texture content used if a texture cannot loaded
  10757. * @ignorenaming
  10758. */
  10759. 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";
  10760. Tools._tmpFloatArray = new Float32Array(1);
  10761. /**
  10762. * Gets or sets a function used to pre-process url before using them to load assets
  10763. */
  10764. Tools.PreprocessUrl = function (url) {
  10765. return url;
  10766. };
  10767. // Logs
  10768. /**
  10769. * No log
  10770. */
  10771. Tools.NoneLogLevel = 0;
  10772. /**
  10773. * Only message logs
  10774. */
  10775. Tools.MessageLogLevel = 1;
  10776. /**
  10777. * Only warning logs
  10778. */
  10779. Tools.WarningLogLevel = 2;
  10780. /**
  10781. * Only error logs
  10782. */
  10783. Tools.ErrorLogLevel = 4;
  10784. /**
  10785. * All logs
  10786. */
  10787. Tools.AllLogLevel = 7;
  10788. Tools._LogCache = "";
  10789. /**
  10790. * Gets a value indicating the number of loading errors
  10791. * @ignorenaming
  10792. */
  10793. Tools.errorsCount = 0;
  10794. /**
  10795. * Log a message to the console
  10796. */
  10797. Tools.Log = Tools._LogEnabled;
  10798. /**
  10799. * Write a warning message to the console
  10800. */
  10801. Tools.Warn = Tools._WarnEnabled;
  10802. /**
  10803. * Write an error message to the console
  10804. */
  10805. Tools.Error = Tools._ErrorEnabled;
  10806. // Performances
  10807. /**
  10808. * No performance log
  10809. */
  10810. Tools.PerformanceNoneLogLevel = 0;
  10811. /**
  10812. * Use user marks to log performance
  10813. */
  10814. Tools.PerformanceUserMarkLogLevel = 1;
  10815. /**
  10816. * Log performance to the console
  10817. */
  10818. Tools.PerformanceConsoleLogLevel = 2;
  10819. /**
  10820. * Starts a performance counter
  10821. */
  10822. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10823. /**
  10824. * Ends a specific performance coutner
  10825. */
  10826. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10827. return Tools;
  10828. }());
  10829. BABYLON.Tools = Tools;
  10830. /**
  10831. * This class is used to track a performance counter which is number based.
  10832. * The user has access to many properties which give statistics of different nature.
  10833. *
  10834. * The implementer can track two kinds of Performance Counter: time and count.
  10835. * 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.
  10836. * 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.
  10837. */
  10838. var PerfCounter = /** @class */ (function () {
  10839. /**
  10840. * Creates a new counter
  10841. */
  10842. function PerfCounter() {
  10843. this._startMonitoringTime = 0;
  10844. this._min = 0;
  10845. this._max = 0;
  10846. this._average = 0;
  10847. this._lastSecAverage = 0;
  10848. this._current = 0;
  10849. this._totalValueCount = 0;
  10850. this._totalAccumulated = 0;
  10851. this._lastSecAccumulated = 0;
  10852. this._lastSecTime = 0;
  10853. this._lastSecValueCount = 0;
  10854. }
  10855. Object.defineProperty(PerfCounter.prototype, "min", {
  10856. /**
  10857. * Returns the smallest value ever
  10858. */
  10859. get: function () {
  10860. return this._min;
  10861. },
  10862. enumerable: true,
  10863. configurable: true
  10864. });
  10865. Object.defineProperty(PerfCounter.prototype, "max", {
  10866. /**
  10867. * Returns the biggest value ever
  10868. */
  10869. get: function () {
  10870. return this._max;
  10871. },
  10872. enumerable: true,
  10873. configurable: true
  10874. });
  10875. Object.defineProperty(PerfCounter.prototype, "average", {
  10876. /**
  10877. * Returns the average value since the performance counter is running
  10878. */
  10879. get: function () {
  10880. return this._average;
  10881. },
  10882. enumerable: true,
  10883. configurable: true
  10884. });
  10885. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10886. /**
  10887. * Returns the average value of the last second the counter was monitored
  10888. */
  10889. get: function () {
  10890. return this._lastSecAverage;
  10891. },
  10892. enumerable: true,
  10893. configurable: true
  10894. });
  10895. Object.defineProperty(PerfCounter.prototype, "current", {
  10896. /**
  10897. * Returns the current value
  10898. */
  10899. get: function () {
  10900. return this._current;
  10901. },
  10902. enumerable: true,
  10903. configurable: true
  10904. });
  10905. Object.defineProperty(PerfCounter.prototype, "total", {
  10906. /**
  10907. * Gets the accumulated total
  10908. */
  10909. get: function () {
  10910. return this._totalAccumulated;
  10911. },
  10912. enumerable: true,
  10913. configurable: true
  10914. });
  10915. Object.defineProperty(PerfCounter.prototype, "count", {
  10916. /**
  10917. * Gets the total value count
  10918. */
  10919. get: function () {
  10920. return this._totalValueCount;
  10921. },
  10922. enumerable: true,
  10923. configurable: true
  10924. });
  10925. /**
  10926. * Call this method to start monitoring a new frame.
  10927. * 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.
  10928. */
  10929. PerfCounter.prototype.fetchNewFrame = function () {
  10930. this._totalValueCount++;
  10931. this._current = 0;
  10932. this._lastSecValueCount++;
  10933. };
  10934. /**
  10935. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10936. * @param newCount the count value to add to the monitored count
  10937. * @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.
  10938. */
  10939. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10940. if (!PerfCounter.Enabled) {
  10941. return;
  10942. }
  10943. this._current += newCount;
  10944. if (fetchResult) {
  10945. this._fetchResult();
  10946. }
  10947. };
  10948. /**
  10949. * Start monitoring this performance counter
  10950. */
  10951. PerfCounter.prototype.beginMonitoring = function () {
  10952. if (!PerfCounter.Enabled) {
  10953. return;
  10954. }
  10955. this._startMonitoringTime = Tools.Now;
  10956. };
  10957. /**
  10958. * Compute the time lapsed since the previous beginMonitoring() call.
  10959. * @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
  10960. */
  10961. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10962. if (newFrame === void 0) { newFrame = true; }
  10963. if (!PerfCounter.Enabled) {
  10964. return;
  10965. }
  10966. if (newFrame) {
  10967. this.fetchNewFrame();
  10968. }
  10969. var currentTime = Tools.Now;
  10970. this._current = currentTime - this._startMonitoringTime;
  10971. if (newFrame) {
  10972. this._fetchResult();
  10973. }
  10974. };
  10975. PerfCounter.prototype._fetchResult = function () {
  10976. this._totalAccumulated += this._current;
  10977. this._lastSecAccumulated += this._current;
  10978. // Min/Max update
  10979. this._min = Math.min(this._min, this._current);
  10980. this._max = Math.max(this._max, this._current);
  10981. this._average = this._totalAccumulated / this._totalValueCount;
  10982. // Reset last sec?
  10983. var now = Tools.Now;
  10984. if ((now - this._lastSecTime) > 1000) {
  10985. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10986. this._lastSecTime = now;
  10987. this._lastSecAccumulated = 0;
  10988. this._lastSecValueCount = 0;
  10989. }
  10990. };
  10991. /**
  10992. * Gets or sets a global boolean to turn on and off all the counters
  10993. */
  10994. PerfCounter.Enabled = true;
  10995. return PerfCounter;
  10996. }());
  10997. BABYLON.PerfCounter = PerfCounter;
  10998. /**
  10999. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  11000. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  11001. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  11002. * @param name The name of the class, case should be preserved
  11003. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  11004. */
  11005. function className(name, module) {
  11006. return function (target) {
  11007. target["__bjsclassName__"] = name;
  11008. target["__bjsmoduleName__"] = (module != null) ? module : null;
  11009. };
  11010. }
  11011. BABYLON.className = className;
  11012. /**
  11013. * An implementation of a loop for asynchronous functions.
  11014. */
  11015. var AsyncLoop = /** @class */ (function () {
  11016. /**
  11017. * Constructor.
  11018. * @param iterations the number of iterations.
  11019. * @param func the function to run each iteration
  11020. * @param successCallback the callback that will be called upon succesful execution
  11021. * @param offset starting offset.
  11022. */
  11023. function AsyncLoop(
  11024. /**
  11025. * Defines the number of iterations for the loop
  11026. */
  11027. iterations, func, successCallback, offset) {
  11028. if (offset === void 0) { offset = 0; }
  11029. this.iterations = iterations;
  11030. this.index = offset - 1;
  11031. this._done = false;
  11032. this._fn = func;
  11033. this._successCallback = successCallback;
  11034. }
  11035. /**
  11036. * Execute the next iteration. Must be called after the last iteration was finished.
  11037. */
  11038. AsyncLoop.prototype.executeNext = function () {
  11039. if (!this._done) {
  11040. if (this.index + 1 < this.iterations) {
  11041. ++this.index;
  11042. this._fn(this);
  11043. }
  11044. else {
  11045. this.breakLoop();
  11046. }
  11047. }
  11048. };
  11049. /**
  11050. * Break the loop and run the success callback.
  11051. */
  11052. AsyncLoop.prototype.breakLoop = function () {
  11053. this._done = true;
  11054. this._successCallback();
  11055. };
  11056. /**
  11057. * Create and run an async loop.
  11058. * @param iterations the number of iterations.
  11059. * @param fn the function to run each iteration
  11060. * @param successCallback the callback that will be called upon succesful execution
  11061. * @param offset starting offset.
  11062. * @returns the created async loop object
  11063. */
  11064. AsyncLoop.Run = function (iterations, fn, successCallback, offset) {
  11065. if (offset === void 0) { offset = 0; }
  11066. var loop = new AsyncLoop(iterations, fn, successCallback, offset);
  11067. loop.executeNext();
  11068. return loop;
  11069. };
  11070. /**
  11071. * A for-loop that will run a given number of iterations synchronous and the rest async.
  11072. * @param iterations total number of iterations
  11073. * @param syncedIterations number of synchronous iterations in each async iteration.
  11074. * @param fn the function to call each iteration.
  11075. * @param callback a success call back that will be called when iterating stops.
  11076. * @param breakFunction a break condition (optional)
  11077. * @param timeout timeout settings for the setTimeout function. default - 0.
  11078. * @returns the created async loop object
  11079. */
  11080. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  11081. if (timeout === void 0) { timeout = 0; }
  11082. return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  11083. if (breakFunction && breakFunction())
  11084. loop.breakLoop();
  11085. else {
  11086. setTimeout(function () {
  11087. for (var i = 0; i < syncedIterations; ++i) {
  11088. var iteration = (loop.index * syncedIterations) + i;
  11089. if (iteration >= iterations)
  11090. break;
  11091. fn(iteration);
  11092. if (breakFunction && breakFunction()) {
  11093. loop.breakLoop();
  11094. break;
  11095. }
  11096. }
  11097. loop.executeNext();
  11098. }, timeout);
  11099. }
  11100. }, callback);
  11101. };
  11102. return AsyncLoop;
  11103. }());
  11104. BABYLON.AsyncLoop = AsyncLoop;
  11105. })(BABYLON || (BABYLON = {}));
  11106. //# sourceMappingURL=babylon.tools.js.map
  11107. var BABYLON;
  11108. (function (BABYLON) {
  11109. var PromiseStates;
  11110. (function (PromiseStates) {
  11111. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  11112. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  11113. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  11114. })(PromiseStates || (PromiseStates = {}));
  11115. var FulFillmentAgregator = /** @class */ (function () {
  11116. function FulFillmentAgregator() {
  11117. this.count = 0;
  11118. this.target = 0;
  11119. this.results = [];
  11120. }
  11121. return FulFillmentAgregator;
  11122. }());
  11123. var InternalPromise = /** @class */ (function () {
  11124. function InternalPromise(resolver) {
  11125. var _this = this;
  11126. this._state = PromiseStates.Pending;
  11127. this._children = new Array();
  11128. this._rejectWasConsumed = false;
  11129. if (!resolver) {
  11130. return;
  11131. }
  11132. try {
  11133. resolver(function (value) {
  11134. _this._resolve(value);
  11135. }, function (reason) {
  11136. _this._reject(reason);
  11137. });
  11138. }
  11139. catch (e) {
  11140. this._reject(e);
  11141. }
  11142. }
  11143. Object.defineProperty(InternalPromise.prototype, "_result", {
  11144. get: function () {
  11145. return this._resultValue;
  11146. },
  11147. set: function (value) {
  11148. this._resultValue = value;
  11149. if (this._parent && this._parent._result === undefined) {
  11150. this._parent._result = value;
  11151. }
  11152. },
  11153. enumerable: true,
  11154. configurable: true
  11155. });
  11156. InternalPromise.prototype.catch = function (onRejected) {
  11157. return this.then(undefined, onRejected);
  11158. };
  11159. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  11160. var _this = this;
  11161. var newPromise = new InternalPromise();
  11162. newPromise._onFulfilled = onFulfilled;
  11163. newPromise._onRejected = onRejected;
  11164. // Composition
  11165. this._children.push(newPromise);
  11166. newPromise._parent = this;
  11167. if (this._state !== PromiseStates.Pending) {
  11168. BABYLON.Tools.SetImmediate(function () {
  11169. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  11170. var returnedValue = newPromise._resolve(_this._result);
  11171. if (returnedValue !== undefined && returnedValue !== null) {
  11172. if (returnedValue._state !== undefined) {
  11173. var returnedPromise = returnedValue;
  11174. newPromise._children.push(returnedPromise);
  11175. returnedPromise._parent = newPromise;
  11176. newPromise = returnedPromise;
  11177. }
  11178. else {
  11179. newPromise._result = returnedValue;
  11180. }
  11181. }
  11182. }
  11183. else {
  11184. newPromise._reject(_this._reason);
  11185. }
  11186. });
  11187. }
  11188. return newPromise;
  11189. };
  11190. InternalPromise.prototype._moveChildren = function (children) {
  11191. var _this = this;
  11192. var _a;
  11193. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  11194. this._children.forEach(function (child) {
  11195. child._parent = _this;
  11196. });
  11197. if (this._state === PromiseStates.Fulfilled) {
  11198. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  11199. var child = _b[_i];
  11200. child._resolve(this._result);
  11201. }
  11202. }
  11203. else if (this._state === PromiseStates.Rejected) {
  11204. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  11205. var child = _d[_c];
  11206. child._reject(this._reason);
  11207. }
  11208. }
  11209. };
  11210. InternalPromise.prototype._resolve = function (value) {
  11211. try {
  11212. this._state = PromiseStates.Fulfilled;
  11213. var returnedValue = null;
  11214. if (this._onFulfilled) {
  11215. returnedValue = this._onFulfilled(value);
  11216. }
  11217. if (returnedValue !== undefined && returnedValue !== null) {
  11218. if (returnedValue._state !== undefined) {
  11219. // Transmit children
  11220. var returnedPromise = returnedValue;
  11221. returnedPromise._parent = this;
  11222. returnedPromise._moveChildren(this._children);
  11223. value = returnedPromise._result;
  11224. }
  11225. else {
  11226. value = returnedValue;
  11227. }
  11228. }
  11229. this._result = value;
  11230. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11231. var child = _a[_i];
  11232. child._resolve(value);
  11233. }
  11234. this._children.length = 0;
  11235. delete this._onFulfilled;
  11236. delete this._onRejected;
  11237. }
  11238. catch (e) {
  11239. this._reject(e, true);
  11240. }
  11241. };
  11242. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  11243. if (onLocalThrow === void 0) { onLocalThrow = false; }
  11244. this._state = PromiseStates.Rejected;
  11245. this._reason = reason;
  11246. if (this._onRejected && !onLocalThrow) {
  11247. try {
  11248. this._onRejected(reason);
  11249. this._rejectWasConsumed = true;
  11250. }
  11251. catch (e) {
  11252. reason = e;
  11253. }
  11254. }
  11255. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11256. var child = _a[_i];
  11257. if (this._rejectWasConsumed) {
  11258. child._resolve(null);
  11259. }
  11260. else {
  11261. child._reject(reason);
  11262. }
  11263. }
  11264. this._children.length = 0;
  11265. delete this._onFulfilled;
  11266. delete this._onRejected;
  11267. };
  11268. InternalPromise.resolve = function (value) {
  11269. var newPromise = new InternalPromise();
  11270. newPromise._resolve(value);
  11271. return newPromise;
  11272. };
  11273. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  11274. promise.then(function (value) {
  11275. agregator.results[index] = value;
  11276. agregator.count++;
  11277. if (agregator.count === agregator.target) {
  11278. agregator.rootPromise._resolve(agregator.results);
  11279. }
  11280. return null;
  11281. }, function (reason) {
  11282. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  11283. agregator.rootPromise._reject(reason);
  11284. }
  11285. });
  11286. };
  11287. InternalPromise.all = function (promises) {
  11288. var newPromise = new InternalPromise();
  11289. var agregator = new FulFillmentAgregator();
  11290. agregator.target = promises.length;
  11291. agregator.rootPromise = newPromise;
  11292. if (promises.length) {
  11293. for (var index = 0; index < promises.length; index++) {
  11294. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  11295. }
  11296. }
  11297. else {
  11298. newPromise._resolve([]);
  11299. }
  11300. return newPromise;
  11301. };
  11302. InternalPromise.race = function (promises) {
  11303. var newPromise = new InternalPromise();
  11304. if (promises.length) {
  11305. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  11306. var promise = promises_1[_i];
  11307. promise.then(function (value) {
  11308. if (newPromise) {
  11309. newPromise._resolve(value);
  11310. newPromise = null;
  11311. }
  11312. return null;
  11313. }, function (reason) {
  11314. if (newPromise) {
  11315. newPromise._reject(reason);
  11316. newPromise = null;
  11317. }
  11318. });
  11319. }
  11320. }
  11321. return newPromise;
  11322. };
  11323. return InternalPromise;
  11324. }());
  11325. /**
  11326. * Helper class that provides a small promise polyfill
  11327. */
  11328. var PromisePolyfill = /** @class */ (function () {
  11329. function PromisePolyfill() {
  11330. }
  11331. /**
  11332. * Static function used to check if the polyfill is required
  11333. * If this is the case then the function will inject the polyfill to window.Promise
  11334. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  11335. */
  11336. PromisePolyfill.Apply = function (force) {
  11337. if (force === void 0) { force = false; }
  11338. if (force || typeof Promise === 'undefined') {
  11339. var root = window;
  11340. root.Promise = InternalPromise;
  11341. }
  11342. };
  11343. return PromisePolyfill;
  11344. }());
  11345. BABYLON.PromisePolyfill = PromisePolyfill;
  11346. })(BABYLON || (BABYLON = {}));
  11347. //# sourceMappingURL=babylon.promise.js.map
  11348. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  11349. var BABYLON;
  11350. (function (BABYLON) {
  11351. /**
  11352. * Helper class to push actions to a pool of workers.
  11353. */
  11354. var WorkerPool = /** @class */ (function () {
  11355. /**
  11356. * Constructor
  11357. * @param workers Array of workers to use for actions
  11358. */
  11359. function WorkerPool(workers) {
  11360. this._pendingActions = new Array();
  11361. this._workerInfos = workers.map(function (worker) { return ({
  11362. worker: worker,
  11363. active: false
  11364. }); });
  11365. }
  11366. /**
  11367. * Terminates all workers and clears any pending actions.
  11368. */
  11369. WorkerPool.prototype.dispose = function () {
  11370. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11371. var workerInfo = _a[_i];
  11372. workerInfo.worker.terminate();
  11373. }
  11374. delete this._workerInfos;
  11375. delete this._pendingActions;
  11376. };
  11377. /**
  11378. * Pushes an action to the worker pool. If all the workers are active, the action will be
  11379. * pended until a worker has completed its action.
  11380. * @param action The action to perform. Call onComplete when the action is complete.
  11381. */
  11382. WorkerPool.prototype.push = function (action) {
  11383. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11384. var workerInfo = _a[_i];
  11385. if (!workerInfo.active) {
  11386. this._execute(workerInfo, action);
  11387. return;
  11388. }
  11389. }
  11390. this._pendingActions.push(action);
  11391. };
  11392. WorkerPool.prototype._execute = function (workerInfo, action) {
  11393. var _this = this;
  11394. workerInfo.active = true;
  11395. action(workerInfo.worker, function () {
  11396. workerInfo.active = false;
  11397. var nextAction = _this._pendingActions.shift();
  11398. if (nextAction) {
  11399. _this._execute(workerInfo, nextAction);
  11400. }
  11401. });
  11402. };
  11403. return WorkerPool;
  11404. }());
  11405. BABYLON.WorkerPool = WorkerPool;
  11406. })(BABYLON || (BABYLON = {}));
  11407. //# sourceMappingURL=babylon.workerPool.js.map
  11408. var BABYLON;
  11409. (function (BABYLON) {
  11410. /**
  11411. * @hidden
  11412. **/
  11413. var _AlphaState = /** @class */ (function () {
  11414. /**
  11415. * Initializes the state.
  11416. */
  11417. function _AlphaState() {
  11418. this._isAlphaBlendDirty = false;
  11419. this._isBlendFunctionParametersDirty = false;
  11420. this._isBlendEquationParametersDirty = false;
  11421. this._isBlendConstantsDirty = false;
  11422. this._alphaBlend = false;
  11423. this._blendFunctionParameters = new Array(4);
  11424. this._blendEquationParameters = new Array(2);
  11425. this._blendConstants = new Array(4);
  11426. this.reset();
  11427. }
  11428. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  11429. get: function () {
  11430. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  11431. },
  11432. enumerable: true,
  11433. configurable: true
  11434. });
  11435. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  11436. get: function () {
  11437. return this._alphaBlend;
  11438. },
  11439. set: function (value) {
  11440. if (this._alphaBlend === value) {
  11441. return;
  11442. }
  11443. this._alphaBlend = value;
  11444. this._isAlphaBlendDirty = true;
  11445. },
  11446. enumerable: true,
  11447. configurable: true
  11448. });
  11449. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  11450. if (this._blendConstants[0] === r &&
  11451. this._blendConstants[1] === g &&
  11452. this._blendConstants[2] === b &&
  11453. this._blendConstants[3] === a) {
  11454. return;
  11455. }
  11456. this._blendConstants[0] = r;
  11457. this._blendConstants[1] = g;
  11458. this._blendConstants[2] = b;
  11459. this._blendConstants[3] = a;
  11460. this._isBlendConstantsDirty = true;
  11461. };
  11462. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  11463. if (this._blendFunctionParameters[0] === value0 &&
  11464. this._blendFunctionParameters[1] === value1 &&
  11465. this._blendFunctionParameters[2] === value2 &&
  11466. this._blendFunctionParameters[3] === value3) {
  11467. return;
  11468. }
  11469. this._blendFunctionParameters[0] = value0;
  11470. this._blendFunctionParameters[1] = value1;
  11471. this._blendFunctionParameters[2] = value2;
  11472. this._blendFunctionParameters[3] = value3;
  11473. this._isBlendFunctionParametersDirty = true;
  11474. };
  11475. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  11476. if (this._blendEquationParameters[0] === rgb &&
  11477. this._blendEquationParameters[1] === alpha) {
  11478. return;
  11479. }
  11480. this._blendEquationParameters[0] = rgb;
  11481. this._blendEquationParameters[1] = alpha;
  11482. this._isBlendEquationParametersDirty = true;
  11483. };
  11484. _AlphaState.prototype.reset = function () {
  11485. this._alphaBlend = false;
  11486. this._blendFunctionParameters[0] = null;
  11487. this._blendFunctionParameters[1] = null;
  11488. this._blendFunctionParameters[2] = null;
  11489. this._blendFunctionParameters[3] = null;
  11490. this._blendEquationParameters[0] = null;
  11491. this._blendEquationParameters[1] = null;
  11492. this._blendConstants[0] = null;
  11493. this._blendConstants[1] = null;
  11494. this._blendConstants[2] = null;
  11495. this._blendConstants[3] = null;
  11496. this._isAlphaBlendDirty = true;
  11497. this._isBlendFunctionParametersDirty = false;
  11498. this._isBlendEquationParametersDirty = false;
  11499. this._isBlendConstantsDirty = false;
  11500. };
  11501. _AlphaState.prototype.apply = function (gl) {
  11502. if (!this.isDirty) {
  11503. return;
  11504. }
  11505. // Alpha blend
  11506. if (this._isAlphaBlendDirty) {
  11507. if (this._alphaBlend) {
  11508. gl.enable(gl.BLEND);
  11509. }
  11510. else {
  11511. gl.disable(gl.BLEND);
  11512. }
  11513. this._isAlphaBlendDirty = false;
  11514. }
  11515. // Alpha function
  11516. if (this._isBlendFunctionParametersDirty) {
  11517. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  11518. this._isBlendFunctionParametersDirty = false;
  11519. }
  11520. // Alpha equation
  11521. if (this._isBlendEquationParametersDirty) {
  11522. gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]);
  11523. this._isBlendEquationParametersDirty = false;
  11524. }
  11525. // Constants
  11526. if (this._isBlendConstantsDirty) {
  11527. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  11528. this._isBlendConstantsDirty = false;
  11529. }
  11530. };
  11531. return _AlphaState;
  11532. }());
  11533. BABYLON._AlphaState = _AlphaState;
  11534. })(BABYLON || (BABYLON = {}));
  11535. //# sourceMappingURL=babylon.alphaCullingState.js.map
  11536. var BABYLON;
  11537. (function (BABYLON) {
  11538. /**
  11539. * @hidden
  11540. **/
  11541. var _DepthCullingState = /** @class */ (function () {
  11542. /**
  11543. * Initializes the state.
  11544. */
  11545. function _DepthCullingState() {
  11546. this._isDepthTestDirty = false;
  11547. this._isDepthMaskDirty = false;
  11548. this._isDepthFuncDirty = false;
  11549. this._isCullFaceDirty = false;
  11550. this._isCullDirty = false;
  11551. this._isZOffsetDirty = false;
  11552. this._isFrontFaceDirty = false;
  11553. this.reset();
  11554. }
  11555. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  11556. get: function () {
  11557. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  11558. },
  11559. enumerable: true,
  11560. configurable: true
  11561. });
  11562. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  11563. get: function () {
  11564. return this._zOffset;
  11565. },
  11566. set: function (value) {
  11567. if (this._zOffset === value) {
  11568. return;
  11569. }
  11570. this._zOffset = value;
  11571. this._isZOffsetDirty = true;
  11572. },
  11573. enumerable: true,
  11574. configurable: true
  11575. });
  11576. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  11577. get: function () {
  11578. return this._cullFace;
  11579. },
  11580. set: function (value) {
  11581. if (this._cullFace === value) {
  11582. return;
  11583. }
  11584. this._cullFace = value;
  11585. this._isCullFaceDirty = true;
  11586. },
  11587. enumerable: true,
  11588. configurable: true
  11589. });
  11590. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  11591. get: function () {
  11592. return this._cull;
  11593. },
  11594. set: function (value) {
  11595. if (this._cull === value) {
  11596. return;
  11597. }
  11598. this._cull = value;
  11599. this._isCullDirty = true;
  11600. },
  11601. enumerable: true,
  11602. configurable: true
  11603. });
  11604. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  11605. get: function () {
  11606. return this._depthFunc;
  11607. },
  11608. set: function (value) {
  11609. if (this._depthFunc === value) {
  11610. return;
  11611. }
  11612. this._depthFunc = value;
  11613. this._isDepthFuncDirty = true;
  11614. },
  11615. enumerable: true,
  11616. configurable: true
  11617. });
  11618. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  11619. get: function () {
  11620. return this._depthMask;
  11621. },
  11622. set: function (value) {
  11623. if (this._depthMask === value) {
  11624. return;
  11625. }
  11626. this._depthMask = value;
  11627. this._isDepthMaskDirty = true;
  11628. },
  11629. enumerable: true,
  11630. configurable: true
  11631. });
  11632. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  11633. get: function () {
  11634. return this._depthTest;
  11635. },
  11636. set: function (value) {
  11637. if (this._depthTest === value) {
  11638. return;
  11639. }
  11640. this._depthTest = value;
  11641. this._isDepthTestDirty = true;
  11642. },
  11643. enumerable: true,
  11644. configurable: true
  11645. });
  11646. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  11647. get: function () {
  11648. return this._frontFace;
  11649. },
  11650. set: function (value) {
  11651. if (this._frontFace === value) {
  11652. return;
  11653. }
  11654. this._frontFace = value;
  11655. this._isFrontFaceDirty = true;
  11656. },
  11657. enumerable: true,
  11658. configurable: true
  11659. });
  11660. _DepthCullingState.prototype.reset = function () {
  11661. this._depthMask = true;
  11662. this._depthTest = true;
  11663. this._depthFunc = null;
  11664. this._cullFace = null;
  11665. this._cull = null;
  11666. this._zOffset = 0;
  11667. this._frontFace = null;
  11668. this._isDepthTestDirty = true;
  11669. this._isDepthMaskDirty = true;
  11670. this._isDepthFuncDirty = false;
  11671. this._isCullFaceDirty = false;
  11672. this._isCullDirty = false;
  11673. this._isZOffsetDirty = false;
  11674. this._isFrontFaceDirty = false;
  11675. };
  11676. _DepthCullingState.prototype.apply = function (gl) {
  11677. if (!this.isDirty) {
  11678. return;
  11679. }
  11680. // Cull
  11681. if (this._isCullDirty) {
  11682. if (this.cull) {
  11683. gl.enable(gl.CULL_FACE);
  11684. }
  11685. else {
  11686. gl.disable(gl.CULL_FACE);
  11687. }
  11688. this._isCullDirty = false;
  11689. }
  11690. // Cull face
  11691. if (this._isCullFaceDirty) {
  11692. gl.cullFace(this.cullFace);
  11693. this._isCullFaceDirty = false;
  11694. }
  11695. // Depth mask
  11696. if (this._isDepthMaskDirty) {
  11697. gl.depthMask(this.depthMask);
  11698. this._isDepthMaskDirty = false;
  11699. }
  11700. // Depth test
  11701. if (this._isDepthTestDirty) {
  11702. if (this.depthTest) {
  11703. gl.enable(gl.DEPTH_TEST);
  11704. }
  11705. else {
  11706. gl.disable(gl.DEPTH_TEST);
  11707. }
  11708. this._isDepthTestDirty = false;
  11709. }
  11710. // Depth func
  11711. if (this._isDepthFuncDirty) {
  11712. gl.depthFunc(this.depthFunc);
  11713. this._isDepthFuncDirty = false;
  11714. }
  11715. // zOffset
  11716. if (this._isZOffsetDirty) {
  11717. if (this.zOffset) {
  11718. gl.enable(gl.POLYGON_OFFSET_FILL);
  11719. gl.polygonOffset(this.zOffset, 0);
  11720. }
  11721. else {
  11722. gl.disable(gl.POLYGON_OFFSET_FILL);
  11723. }
  11724. this._isZOffsetDirty = false;
  11725. }
  11726. // Front face
  11727. if (this._isFrontFaceDirty) {
  11728. gl.frontFace(this.frontFace);
  11729. this._isFrontFaceDirty = false;
  11730. }
  11731. };
  11732. return _DepthCullingState;
  11733. }());
  11734. BABYLON._DepthCullingState = _DepthCullingState;
  11735. })(BABYLON || (BABYLON = {}));
  11736. //# sourceMappingURL=babylon.depthCullingState.js.map
  11737. var BABYLON;
  11738. (function (BABYLON) {
  11739. /**
  11740. * @hidden
  11741. **/
  11742. var _StencilState = /** @class */ (function () {
  11743. function _StencilState() {
  11744. this._isStencilTestDirty = false;
  11745. this._isStencilMaskDirty = false;
  11746. this._isStencilFuncDirty = false;
  11747. this._isStencilOpDirty = false;
  11748. this.reset();
  11749. }
  11750. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11751. get: function () {
  11752. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11753. },
  11754. enumerable: true,
  11755. configurable: true
  11756. });
  11757. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11758. get: function () {
  11759. return this._stencilFunc;
  11760. },
  11761. set: function (value) {
  11762. if (this._stencilFunc === value) {
  11763. return;
  11764. }
  11765. this._stencilFunc = value;
  11766. this._isStencilFuncDirty = true;
  11767. },
  11768. enumerable: true,
  11769. configurable: true
  11770. });
  11771. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11772. get: function () {
  11773. return this._stencilFuncRef;
  11774. },
  11775. set: function (value) {
  11776. if (this._stencilFuncRef === value) {
  11777. return;
  11778. }
  11779. this._stencilFuncRef = value;
  11780. this._isStencilFuncDirty = true;
  11781. },
  11782. enumerable: true,
  11783. configurable: true
  11784. });
  11785. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11786. get: function () {
  11787. return this._stencilFuncMask;
  11788. },
  11789. set: function (value) {
  11790. if (this._stencilFuncMask === value) {
  11791. return;
  11792. }
  11793. this._stencilFuncMask = value;
  11794. this._isStencilFuncDirty = true;
  11795. },
  11796. enumerable: true,
  11797. configurable: true
  11798. });
  11799. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11800. get: function () {
  11801. return this._stencilOpStencilFail;
  11802. },
  11803. set: function (value) {
  11804. if (this._stencilOpStencilFail === value) {
  11805. return;
  11806. }
  11807. this._stencilOpStencilFail = value;
  11808. this._isStencilOpDirty = true;
  11809. },
  11810. enumerable: true,
  11811. configurable: true
  11812. });
  11813. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11814. get: function () {
  11815. return this._stencilOpDepthFail;
  11816. },
  11817. set: function (value) {
  11818. if (this._stencilOpDepthFail === value) {
  11819. return;
  11820. }
  11821. this._stencilOpDepthFail = value;
  11822. this._isStencilOpDirty = true;
  11823. },
  11824. enumerable: true,
  11825. configurable: true
  11826. });
  11827. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11828. get: function () {
  11829. return this._stencilOpStencilDepthPass;
  11830. },
  11831. set: function (value) {
  11832. if (this._stencilOpStencilDepthPass === value) {
  11833. return;
  11834. }
  11835. this._stencilOpStencilDepthPass = value;
  11836. this._isStencilOpDirty = true;
  11837. },
  11838. enumerable: true,
  11839. configurable: true
  11840. });
  11841. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11842. get: function () {
  11843. return this._stencilMask;
  11844. },
  11845. set: function (value) {
  11846. if (this._stencilMask === value) {
  11847. return;
  11848. }
  11849. this._stencilMask = value;
  11850. this._isStencilMaskDirty = true;
  11851. },
  11852. enumerable: true,
  11853. configurable: true
  11854. });
  11855. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11856. get: function () {
  11857. return this._stencilTest;
  11858. },
  11859. set: function (value) {
  11860. if (this._stencilTest === value) {
  11861. return;
  11862. }
  11863. this._stencilTest = value;
  11864. this._isStencilTestDirty = true;
  11865. },
  11866. enumerable: true,
  11867. configurable: true
  11868. });
  11869. _StencilState.prototype.reset = function () {
  11870. this._stencilTest = false;
  11871. this._stencilMask = 0xFF;
  11872. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11873. this._stencilFuncRef = 1;
  11874. this._stencilFuncMask = 0xFF;
  11875. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11876. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11877. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11878. this._isStencilTestDirty = true;
  11879. this._isStencilMaskDirty = true;
  11880. this._isStencilFuncDirty = true;
  11881. this._isStencilOpDirty = true;
  11882. };
  11883. _StencilState.prototype.apply = function (gl) {
  11884. if (!this.isDirty) {
  11885. return;
  11886. }
  11887. // Stencil test
  11888. if (this._isStencilTestDirty) {
  11889. if (this.stencilTest) {
  11890. gl.enable(gl.STENCIL_TEST);
  11891. }
  11892. else {
  11893. gl.disable(gl.STENCIL_TEST);
  11894. }
  11895. this._isStencilTestDirty = false;
  11896. }
  11897. // Stencil mask
  11898. if (this._isStencilMaskDirty) {
  11899. gl.stencilMask(this.stencilMask);
  11900. this._isStencilMaskDirty = false;
  11901. }
  11902. // Stencil func
  11903. if (this._isStencilFuncDirty) {
  11904. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11905. this._isStencilFuncDirty = false;
  11906. }
  11907. // Stencil op
  11908. if (this._isStencilOpDirty) {
  11909. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11910. this._isStencilOpDirty = false;
  11911. }
  11912. };
  11913. return _StencilState;
  11914. }());
  11915. BABYLON._StencilState = _StencilState;
  11916. })(BABYLON || (BABYLON = {}));
  11917. //# sourceMappingURL=babylon.stencilState.js.map
  11918. var __assign = (this && this.__assign) || function () {
  11919. __assign = Object.assign || function(t) {
  11920. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11921. s = arguments[i];
  11922. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11923. t[p] = s[p];
  11924. }
  11925. return t;
  11926. };
  11927. return __assign.apply(this, arguments);
  11928. };
  11929. var BABYLON;
  11930. (function (BABYLON) {
  11931. /**
  11932. * Keeps track of all the buffer info used in engine.
  11933. */
  11934. var BufferPointer = /** @class */ (function () {
  11935. function BufferPointer() {
  11936. }
  11937. return BufferPointer;
  11938. }());
  11939. /**
  11940. * Interface for attribute information associated with buffer instanciation
  11941. */
  11942. var InstancingAttributeInfo = /** @class */ (function () {
  11943. function InstancingAttributeInfo() {
  11944. }
  11945. return InstancingAttributeInfo;
  11946. }());
  11947. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11948. /**
  11949. * Define options used to create a render target texture
  11950. */
  11951. var RenderTargetCreationOptions = /** @class */ (function () {
  11952. function RenderTargetCreationOptions() {
  11953. }
  11954. return RenderTargetCreationOptions;
  11955. }());
  11956. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11957. /**
  11958. * Define options used to create a depth texture
  11959. */
  11960. var DepthTextureCreationOptions = /** @class */ (function () {
  11961. function DepthTextureCreationOptions() {
  11962. }
  11963. return DepthTextureCreationOptions;
  11964. }());
  11965. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11966. /**
  11967. * Class used to describe the capabilities of the engine relatively to the current browser
  11968. */
  11969. var EngineCapabilities = /** @class */ (function () {
  11970. function EngineCapabilities() {
  11971. }
  11972. return EngineCapabilities;
  11973. }());
  11974. BABYLON.EngineCapabilities = EngineCapabilities;
  11975. /**
  11976. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11977. */
  11978. var Engine = /** @class */ (function () {
  11979. /**
  11980. * Creates a new engine
  11981. * @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
  11982. * @param antialias defines enable antialiasing (default: false)
  11983. * @param options defines further options to be sent to the getContext() function
  11984. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11985. */
  11986. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11987. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11988. var _this = this;
  11989. // Public members
  11990. /**
  11991. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11992. */
  11993. this.forcePOTTextures = false;
  11994. /**
  11995. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11996. */
  11997. this.isFullscreen = false;
  11998. /**
  11999. * Gets a boolean indicating if the pointer is currently locked
  12000. */
  12001. this.isPointerLock = false;
  12002. /**
  12003. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  12004. */
  12005. this.cullBackFaces = true;
  12006. /**
  12007. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  12008. */
  12009. this.renderEvenInBackground = true;
  12010. /**
  12011. * Gets or sets a boolean indicating that cache can be kept between frames
  12012. */
  12013. this.preventCacheWipeBetweenFrames = false;
  12014. /**
  12015. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  12016. **/
  12017. this.enableOfflineSupport = false;
  12018. /**
  12019. * 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)
  12020. **/
  12021. this.disableManifestCheck = false;
  12022. /**
  12023. * Gets the list of created scenes
  12024. */
  12025. this.scenes = new Array();
  12026. /**
  12027. * Gets the list of created postprocesses
  12028. */
  12029. this.postProcesses = new Array();
  12030. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  12031. this.validateShaderPrograms = false;
  12032. // Observables
  12033. /**
  12034. * Observable event triggered each time the rendering canvas is resized
  12035. */
  12036. this.onResizeObservable = new BABYLON.Observable();
  12037. /**
  12038. * Observable event triggered each time the canvas loses focus
  12039. */
  12040. this.onCanvasBlurObservable = new BABYLON.Observable();
  12041. /**
  12042. * Observable event triggered each time the canvas gains focus
  12043. */
  12044. this.onCanvasFocusObservable = new BABYLON.Observable();
  12045. /**
  12046. * Observable event triggered each time the canvas receives pointerout event
  12047. */
  12048. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  12049. /**
  12050. * Observable event triggered before each texture is initialized
  12051. */
  12052. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  12053. //WebVR
  12054. this._vrDisplay = undefined;
  12055. this._vrSupported = false;
  12056. this._vrExclusivePointerMode = false;
  12057. // Uniform buffers list
  12058. /**
  12059. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  12060. */
  12061. this.disableUniformBuffers = false;
  12062. /** @hidden */
  12063. this._uniformBuffers = new Array();
  12064. // Observables
  12065. /**
  12066. * Observable raised when the engine begins a new frame
  12067. */
  12068. this.onBeginFrameObservable = new BABYLON.Observable();
  12069. /**
  12070. * Observable raised when the engine ends the current frame
  12071. */
  12072. this.onEndFrameObservable = new BABYLON.Observable();
  12073. /**
  12074. * Observable raised when the engine is about to compile a shader
  12075. */
  12076. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  12077. /**
  12078. * Observable raised when the engine has jsut compiled a shader
  12079. */
  12080. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  12081. this._windowIsBackground = false;
  12082. this._webGLVersion = 1.0;
  12083. /** @hidden */
  12084. this._badOS = false;
  12085. /** @hidden */
  12086. this._badDesktopOS = false;
  12087. /**
  12088. * Gets or sets a value indicating if we want to disable texture binding optmization.
  12089. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  12090. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  12091. */
  12092. this.disableTextureBindingOptimization = false;
  12093. /**
  12094. * Observable signaled when VR display mode changes
  12095. */
  12096. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  12097. /**
  12098. * Observable signaled when VR request present is complete
  12099. */
  12100. this.onVRRequestPresentComplete = new BABYLON.Observable();
  12101. /**
  12102. * Observable signaled when VR request present starts
  12103. */
  12104. this.onVRRequestPresentStart = new BABYLON.Observable();
  12105. this._colorWrite = true;
  12106. /** @hidden */
  12107. this._drawCalls = new BABYLON.PerfCounter();
  12108. /** @hidden */
  12109. this._textureCollisions = new BABYLON.PerfCounter();
  12110. this._renderingQueueLaunched = false;
  12111. this._activeRenderLoops = new Array();
  12112. // Deterministic lockstepMaxSteps
  12113. this._deterministicLockstep = false;
  12114. this._lockstepMaxSteps = 4;
  12115. // Lost context
  12116. /**
  12117. * Observable signaled when a context lost event is raised
  12118. */
  12119. this.onContextLostObservable = new BABYLON.Observable();
  12120. /**
  12121. * Observable signaled when a context restored event is raised
  12122. */
  12123. this.onContextRestoredObservable = new BABYLON.Observable();
  12124. this._contextWasLost = false;
  12125. this._doNotHandleContextLost = false;
  12126. // FPS
  12127. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  12128. this._fps = 60;
  12129. this._deltaTime = 0;
  12130. /**
  12131. * Turn this value on if you want to pause FPS computation when in background
  12132. */
  12133. this.disablePerformanceMonitorInBackground = false;
  12134. // States
  12135. /** @hidden */
  12136. this._depthCullingState = new BABYLON._DepthCullingState();
  12137. /** @hidden */
  12138. this._stencilState = new BABYLON._StencilState();
  12139. /** @hidden */
  12140. this._alphaState = new BABYLON._AlphaState();
  12141. /** @hidden */
  12142. this._alphaMode = Engine.ALPHA_DISABLE;
  12143. // Cache
  12144. this._internalTexturesCache = new Array();
  12145. /** @hidden */
  12146. this._activeChannel = 0;
  12147. this._currentTextureChannel = -1;
  12148. /** @hidden */
  12149. this._boundTexturesCache = {};
  12150. this._compiledEffects = {};
  12151. this._vertexAttribArraysEnabled = [];
  12152. this._uintIndicesCurrentlySet = false;
  12153. this._currentBoundBuffer = new Array();
  12154. /** @hidden */
  12155. this._currentFramebuffer = null;
  12156. this._currentBufferPointers = new Array();
  12157. this._currentInstanceLocations = new Array();
  12158. this._currentInstanceBuffers = new Array();
  12159. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12160. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12161. this._vaoRecordInProgress = false;
  12162. this._mustWipeVertexAttributes = false;
  12163. this._nextFreeTextureSlots = new Array();
  12164. this._maxSimultaneousTextures = 0;
  12165. this._activeRequests = new Array();
  12166. // Hardware supported Compressed Textures
  12167. this._texturesSupported = new Array();
  12168. /**
  12169. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  12170. */
  12171. this.premultipliedAlpha = true;
  12172. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  12173. this._onVRFullScreenTriggered = function () {
  12174. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  12175. //get the old size before we change
  12176. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  12177. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  12178. //get the width and height, change the render size
  12179. var leftEye = _this._vrDisplay.getEyeParameters('left');
  12180. _this.setHardwareScalingLevel(1);
  12181. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  12182. }
  12183. else {
  12184. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  12185. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  12186. }
  12187. };
  12188. this._unpackFlipYCached = null;
  12189. /**
  12190. * In case you are sharing the context with other applications, it might
  12191. * be interested to not cache the unpack flip y state to ensure a consistent
  12192. * value would be set.
  12193. */
  12194. this.enableUnpackFlipYCached = true;
  12195. this._boundUniforms = {};
  12196. // Register promises
  12197. BABYLON.PromisePolyfill.Apply();
  12198. var canvas = null;
  12199. Engine.Instances.push(this);
  12200. if (!canvasOrContext) {
  12201. return;
  12202. }
  12203. options = options || {};
  12204. if (canvasOrContext.getContext) {
  12205. canvas = canvasOrContext;
  12206. this._renderingCanvas = canvas;
  12207. if (antialias != null) {
  12208. options.antialias = antialias;
  12209. }
  12210. if (options.deterministicLockstep === undefined) {
  12211. options.deterministicLockstep = false;
  12212. }
  12213. if (options.lockstepMaxSteps === undefined) {
  12214. options.lockstepMaxSteps = 4;
  12215. }
  12216. if (options.preserveDrawingBuffer === undefined) {
  12217. options.preserveDrawingBuffer = false;
  12218. }
  12219. if (options.audioEngine === undefined) {
  12220. options.audioEngine = true;
  12221. }
  12222. if (options.stencil === undefined) {
  12223. options.stencil = true;
  12224. }
  12225. if (options.premultipliedAlpha === false) {
  12226. this.premultipliedAlpha = false;
  12227. }
  12228. this._deterministicLockstep = options.deterministicLockstep;
  12229. this._lockstepMaxSteps = options.lockstepMaxSteps;
  12230. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  12231. // Exceptions
  12232. if (navigator && navigator.userAgent) {
  12233. var ua = navigator.userAgent;
  12234. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  12235. var exception = _a[_i];
  12236. var key = exception.key;
  12237. var targets = exception.targets;
  12238. if (ua.indexOf(key) > -1) {
  12239. if (exception.capture && exception.captureConstraint) {
  12240. var capture = exception.capture;
  12241. var constraint = exception.captureConstraint;
  12242. var regex = new RegExp(capture);
  12243. var matches = regex.exec(ua);
  12244. if (matches && matches.length > 0) {
  12245. var capturedValue = parseInt(matches[matches.length - 1]);
  12246. if (capturedValue >= constraint) {
  12247. continue;
  12248. }
  12249. }
  12250. }
  12251. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  12252. var target = targets_1[_b];
  12253. switch (target) {
  12254. case "uniformBuffer":
  12255. this.disableUniformBuffers = true;
  12256. break;
  12257. case "textureBindingOptimization":
  12258. this.disableTextureBindingOptimization = true;
  12259. break;
  12260. }
  12261. }
  12262. }
  12263. }
  12264. }
  12265. // GL
  12266. if (!options.disableWebGL2Support) {
  12267. try {
  12268. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  12269. if (this._gl) {
  12270. this._webGLVersion = 2.0;
  12271. }
  12272. }
  12273. catch (e) {
  12274. // Do nothing
  12275. }
  12276. }
  12277. if (!this._gl) {
  12278. if (!canvas) {
  12279. throw new Error("The provided canvas is null or undefined.");
  12280. }
  12281. try {
  12282. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  12283. }
  12284. catch (e) {
  12285. throw new Error("WebGL not supported");
  12286. }
  12287. }
  12288. if (!this._gl) {
  12289. throw new Error("WebGL not supported");
  12290. }
  12291. this._onCanvasFocus = function () {
  12292. _this.onCanvasFocusObservable.notifyObservers(_this);
  12293. };
  12294. this._onCanvasBlur = function () {
  12295. _this.onCanvasBlurObservable.notifyObservers(_this);
  12296. };
  12297. canvas.addEventListener("focus", this._onCanvasFocus);
  12298. canvas.addEventListener("blur", this._onCanvasBlur);
  12299. this._onBlur = function () {
  12300. if (_this.disablePerformanceMonitorInBackground) {
  12301. _this._performanceMonitor.disable();
  12302. }
  12303. _this._windowIsBackground = true;
  12304. };
  12305. this._onFocus = function () {
  12306. if (_this.disablePerformanceMonitorInBackground) {
  12307. _this._performanceMonitor.enable();
  12308. }
  12309. _this._windowIsBackground = false;
  12310. };
  12311. this._onCanvasPointerOut = function (ev) {
  12312. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  12313. };
  12314. window.addEventListener("blur", this._onBlur);
  12315. window.addEventListener("focus", this._onFocus);
  12316. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  12317. // Context lost
  12318. if (!this._doNotHandleContextLost) {
  12319. this._onContextLost = function (evt) {
  12320. evt.preventDefault();
  12321. _this._contextWasLost = true;
  12322. BABYLON.Tools.Warn("WebGL context lost.");
  12323. _this.onContextLostObservable.notifyObservers(_this);
  12324. };
  12325. this._onContextRestored = function (evt) {
  12326. // Adding a timeout to avoid race condition at browser level
  12327. setTimeout(function () {
  12328. // Rebuild gl context
  12329. _this._initGLContext();
  12330. // Rebuild effects
  12331. _this._rebuildEffects();
  12332. // Rebuild textures
  12333. _this._rebuildInternalTextures();
  12334. // Rebuild buffers
  12335. _this._rebuildBuffers();
  12336. // Cache
  12337. _this.wipeCaches(true);
  12338. BABYLON.Tools.Warn("WebGL context successfully restored.");
  12339. _this.onContextRestoredObservable.notifyObservers(_this);
  12340. _this._contextWasLost = false;
  12341. }, 0);
  12342. };
  12343. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  12344. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  12345. }
  12346. }
  12347. else {
  12348. this._gl = canvasOrContext;
  12349. this._renderingCanvas = this._gl.canvas;
  12350. if (this._gl.renderbufferStorageMultisample) {
  12351. this._webGLVersion = 2.0;
  12352. }
  12353. options.stencil = this._gl.getContextAttributes().stencil;
  12354. }
  12355. // Viewport
  12356. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  12357. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  12358. this.resize();
  12359. this._isStencilEnable = options.stencil ? true : false;
  12360. this._initGLContext();
  12361. if (canvas) {
  12362. // Fullscreen
  12363. this._onFullscreenChange = function () {
  12364. if (document.fullscreen !== undefined) {
  12365. _this.isFullscreen = document.fullscreen;
  12366. }
  12367. else if (document.mozFullScreen !== undefined) {
  12368. _this.isFullscreen = document.mozFullScreen;
  12369. }
  12370. else if (document.webkitIsFullScreen !== undefined) {
  12371. _this.isFullscreen = document.webkitIsFullScreen;
  12372. }
  12373. else if (document.msIsFullScreen !== undefined) {
  12374. _this.isFullscreen = document.msIsFullScreen;
  12375. }
  12376. // Pointer lock
  12377. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  12378. canvas.requestPointerLock = canvas.requestPointerLock ||
  12379. canvas.msRequestPointerLock ||
  12380. canvas.mozRequestPointerLock ||
  12381. canvas.webkitRequestPointerLock;
  12382. if (canvas.requestPointerLock) {
  12383. canvas.requestPointerLock();
  12384. }
  12385. }
  12386. };
  12387. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  12388. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  12389. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  12390. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  12391. // Pointer lock
  12392. this._onPointerLockChange = function () {
  12393. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  12394. document.webkitPointerLockElement === canvas ||
  12395. document.msPointerLockElement === canvas ||
  12396. document.pointerLockElement === canvas);
  12397. };
  12398. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  12399. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  12400. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  12401. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  12402. this._onVRDisplayPointerRestricted = function () {
  12403. if (canvas) {
  12404. canvas.requestPointerLock();
  12405. }
  12406. };
  12407. this._onVRDisplayPointerUnrestricted = function () {
  12408. document.exitPointerLock();
  12409. };
  12410. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  12411. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  12412. }
  12413. // Create Audio Engine if needed.
  12414. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
  12415. Engine.audioEngine = Engine.AudioEngineFactory(this);
  12416. }
  12417. // Prepare buffer pointers
  12418. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  12419. this._currentBufferPointers[i] = new BufferPointer();
  12420. }
  12421. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  12422. // Load WebVR Devices
  12423. if (options.autoEnableWebVR) {
  12424. this.initWebVR();
  12425. }
  12426. // Detect if we are running on a faulty buggy OS.
  12427. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  12428. // Detect if we are running on a faulty buggy desktop OS.
  12429. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  12430. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  12431. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  12432. }
  12433. Object.defineProperty(Engine, "LastCreatedEngine", {
  12434. /**
  12435. * Gets the latest created engine
  12436. */
  12437. get: function () {
  12438. if (Engine.Instances.length === 0) {
  12439. return null;
  12440. }
  12441. return Engine.Instances[Engine.Instances.length - 1];
  12442. },
  12443. enumerable: true,
  12444. configurable: true
  12445. });
  12446. Object.defineProperty(Engine, "LastCreatedScene", {
  12447. /**
  12448. * Gets the latest created scene
  12449. */
  12450. get: function () {
  12451. var lastCreatedEngine = Engine.LastCreatedEngine;
  12452. if (!lastCreatedEngine) {
  12453. return null;
  12454. }
  12455. if (lastCreatedEngine.scenes.length === 0) {
  12456. return null;
  12457. }
  12458. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  12459. },
  12460. enumerable: true,
  12461. configurable: true
  12462. });
  12463. /**
  12464. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  12465. * @param flag defines which part of the materials must be marked as dirty
  12466. * @param predicate defines a predicate used to filter which materials should be affected
  12467. */
  12468. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  12469. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  12470. var engine = Engine.Instances[engineIndex];
  12471. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  12472. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  12473. }
  12474. }
  12475. };
  12476. Object.defineProperty(Engine, "Version", {
  12477. /**
  12478. * Returns the current version of the framework
  12479. */
  12480. get: function () {
  12481. return "3.3.0-rc.2";
  12482. },
  12483. enumerable: true,
  12484. configurable: true
  12485. });
  12486. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12487. /**
  12488. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12489. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12490. */
  12491. get: function () {
  12492. return this._vrExclusivePointerMode;
  12493. },
  12494. enumerable: true,
  12495. configurable: true
  12496. });
  12497. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12498. /**
  12499. * Gets a boolean indicating that the engine supports uniform buffers
  12500. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12501. */
  12502. get: function () {
  12503. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12504. },
  12505. enumerable: true,
  12506. configurable: true
  12507. });
  12508. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12509. /**
  12510. * Gets a boolean indicating that only power of 2 textures are supported
  12511. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12512. */
  12513. get: function () {
  12514. return this._webGLVersion < 2 || this.forcePOTTextures;
  12515. },
  12516. enumerable: true,
  12517. configurable: true
  12518. });
  12519. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12520. /**
  12521. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12522. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12523. */
  12524. get: function () {
  12525. return this._doNotHandleContextLost;
  12526. },
  12527. set: function (value) {
  12528. this._doNotHandleContextLost = value;
  12529. },
  12530. enumerable: true,
  12531. configurable: true
  12532. });
  12533. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12534. /**
  12535. * Gets the performance monitor attached to this engine
  12536. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12537. */
  12538. get: function () {
  12539. return this._performanceMonitor;
  12540. },
  12541. enumerable: true,
  12542. configurable: true
  12543. });
  12544. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12545. /**
  12546. * Gets the list of texture formats supported
  12547. */
  12548. get: function () {
  12549. return this._texturesSupported;
  12550. },
  12551. enumerable: true,
  12552. configurable: true
  12553. });
  12554. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12555. /**
  12556. * Gets the list of texture formats in use
  12557. */
  12558. get: function () {
  12559. return this._textureFormatInUse;
  12560. },
  12561. enumerable: true,
  12562. configurable: true
  12563. });
  12564. Object.defineProperty(Engine.prototype, "currentViewport", {
  12565. /**
  12566. * Gets the current viewport
  12567. */
  12568. get: function () {
  12569. return this._cachedViewport;
  12570. },
  12571. enumerable: true,
  12572. configurable: true
  12573. });
  12574. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12575. /**
  12576. * Gets the default empty texture
  12577. */
  12578. get: function () {
  12579. if (!this._emptyTexture) {
  12580. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12581. }
  12582. return this._emptyTexture;
  12583. },
  12584. enumerable: true,
  12585. configurable: true
  12586. });
  12587. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12588. /**
  12589. * Gets the default empty 3D texture
  12590. */
  12591. get: function () {
  12592. if (!this._emptyTexture3D) {
  12593. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12594. }
  12595. return this._emptyTexture3D;
  12596. },
  12597. enumerable: true,
  12598. configurable: true
  12599. });
  12600. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12601. /**
  12602. * Gets the default empty cube texture
  12603. */
  12604. get: function () {
  12605. if (!this._emptyCubeTexture) {
  12606. var faceData = new Uint8Array(4);
  12607. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12608. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12609. }
  12610. return this._emptyCubeTexture;
  12611. },
  12612. enumerable: true,
  12613. configurable: true
  12614. });
  12615. Engine.prototype._rebuildInternalTextures = function () {
  12616. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12617. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12618. var internalTexture = currentState_1[_i];
  12619. internalTexture._rebuild();
  12620. }
  12621. };
  12622. Engine.prototype._rebuildEffects = function () {
  12623. for (var key in this._compiledEffects) {
  12624. var effect = this._compiledEffects[key];
  12625. effect._prepareEffect();
  12626. }
  12627. BABYLON.Effect.ResetCache();
  12628. };
  12629. Engine.prototype._rebuildBuffers = function () {
  12630. // Index / Vertex
  12631. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12632. var scene = _a[_i];
  12633. scene.resetCachedMaterial();
  12634. scene._rebuildGeometries();
  12635. scene._rebuildTextures();
  12636. }
  12637. // Uniforms
  12638. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12639. var uniformBuffer = _c[_b];
  12640. uniformBuffer._rebuild();
  12641. }
  12642. };
  12643. Engine.prototype._initGLContext = function () {
  12644. // Caps
  12645. this._caps = new EngineCapabilities();
  12646. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12647. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12648. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12649. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12650. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12651. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12652. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12653. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12654. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12655. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12656. // Infos
  12657. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12658. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12659. if (rendererInfo != null) {
  12660. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12661. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12662. }
  12663. if (!this._glVendor) {
  12664. this._glVendor = "Unknown vendor";
  12665. }
  12666. if (!this._glRenderer) {
  12667. this._glRenderer = "Unknown renderer";
  12668. }
  12669. // Constants
  12670. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12671. if (this._gl.RGBA16F !== 0x881A) {
  12672. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12673. }
  12674. if (this._gl.RGBA32F !== 0x8814) {
  12675. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12676. }
  12677. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12678. this._gl.DEPTH24_STENCIL8 = 35056;
  12679. }
  12680. // Extensions
  12681. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12682. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12683. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12684. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12685. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12686. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12687. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12688. 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');
  12689. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12690. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12691. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12692. this._caps.highPrecisionShaderSupported = true;
  12693. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12694. if (this._caps.timerQuery) {
  12695. if (this._webGLVersion === 1) {
  12696. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12697. }
  12698. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12699. }
  12700. // Checks if some of the format renders first to allow the use of webgl inspector.
  12701. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12702. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12703. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12704. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12705. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12706. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12707. if (this._webGLVersion > 1) {
  12708. this._gl.HALF_FLOAT_OES = 0x140B;
  12709. }
  12710. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12711. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12712. // Draw buffers
  12713. if (this._webGLVersion > 1) {
  12714. this._caps.drawBuffersExtension = true;
  12715. }
  12716. else {
  12717. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12718. if (drawBuffersExtension !== null) {
  12719. this._caps.drawBuffersExtension = true;
  12720. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12721. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12722. for (var i = 0; i < 16; i++) {
  12723. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12724. }
  12725. }
  12726. else {
  12727. this._caps.drawBuffersExtension = false;
  12728. }
  12729. }
  12730. // Depth Texture
  12731. if (this._webGLVersion > 1) {
  12732. this._caps.depthTextureExtension = true;
  12733. }
  12734. else {
  12735. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12736. if (depthTextureExtension != null) {
  12737. this._caps.depthTextureExtension = true;
  12738. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12739. }
  12740. }
  12741. // Vertex array object
  12742. if (this._webGLVersion > 1) {
  12743. this._caps.vertexArrayObject = true;
  12744. }
  12745. else {
  12746. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12747. if (vertexArrayObjectExtension != null) {
  12748. this._caps.vertexArrayObject = true;
  12749. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12750. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12751. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12752. }
  12753. else {
  12754. this._caps.vertexArrayObject = false;
  12755. }
  12756. }
  12757. // Instances count
  12758. if (this._webGLVersion > 1) {
  12759. this._caps.instancedArrays = true;
  12760. }
  12761. else {
  12762. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12763. if (instanceExtension != null) {
  12764. this._caps.instancedArrays = true;
  12765. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12766. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12767. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12768. }
  12769. else {
  12770. this._caps.instancedArrays = false;
  12771. }
  12772. }
  12773. // Intelligently add supported compressed formats in order to check for.
  12774. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12775. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12776. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12777. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12778. if (this._caps.astc)
  12779. this.texturesSupported.push('-astc.ktx');
  12780. if (this._caps.s3tc)
  12781. this.texturesSupported.push('-dxt.ktx');
  12782. if (this._caps.pvrtc)
  12783. this.texturesSupported.push('-pvrtc.ktx');
  12784. if (this._caps.etc2)
  12785. this.texturesSupported.push('-etc2.ktx');
  12786. if (this._caps.etc1)
  12787. this.texturesSupported.push('-etc1.ktx');
  12788. if (this._gl.getShaderPrecisionFormat) {
  12789. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12790. if (highp) {
  12791. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12792. }
  12793. }
  12794. // Depth buffer
  12795. this.setDepthBuffer(true);
  12796. this.setDepthFunctionToLessOrEqual();
  12797. this.setDepthWrite(true);
  12798. // Texture maps
  12799. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12800. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12801. this._nextFreeTextureSlots.push(slot);
  12802. }
  12803. };
  12804. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12805. /**
  12806. * Gets version of the current webGL context
  12807. */
  12808. get: function () {
  12809. return this._webGLVersion;
  12810. },
  12811. enumerable: true,
  12812. configurable: true
  12813. });
  12814. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12815. /**
  12816. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12817. */
  12818. get: function () {
  12819. return this._isStencilEnable;
  12820. },
  12821. enumerable: true,
  12822. configurable: true
  12823. });
  12824. Engine.prototype._prepareWorkingCanvas = function () {
  12825. if (this._workingCanvas) {
  12826. return;
  12827. }
  12828. this._workingCanvas = document.createElement("canvas");
  12829. var context = this._workingCanvas.getContext("2d");
  12830. if (context) {
  12831. this._workingContext = context;
  12832. }
  12833. };
  12834. /**
  12835. * Reset the texture cache to empty state
  12836. */
  12837. Engine.prototype.resetTextureCache = function () {
  12838. for (var key in this._boundTexturesCache) {
  12839. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12840. continue;
  12841. }
  12842. var boundTexture = this._boundTexturesCache[key];
  12843. if (boundTexture) {
  12844. this._removeDesignatedSlot(boundTexture);
  12845. }
  12846. this._boundTexturesCache[key] = null;
  12847. }
  12848. if (!this.disableTextureBindingOptimization) {
  12849. this._nextFreeTextureSlots = [];
  12850. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12851. this._nextFreeTextureSlots.push(slot);
  12852. }
  12853. }
  12854. this._currentTextureChannel = -1;
  12855. };
  12856. /**
  12857. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12858. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12859. * @returns true if engine is in deterministic lock step mode
  12860. */
  12861. Engine.prototype.isDeterministicLockStep = function () {
  12862. return this._deterministicLockstep;
  12863. };
  12864. /**
  12865. * Gets the max steps when engine is running in deterministic lock step
  12866. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12867. * @returns the max steps
  12868. */
  12869. Engine.prototype.getLockstepMaxSteps = function () {
  12870. return this._lockstepMaxSteps;
  12871. };
  12872. /**
  12873. * Gets an object containing information about the current webGL context
  12874. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12875. */
  12876. Engine.prototype.getGlInfo = function () {
  12877. return {
  12878. vendor: this._glVendor,
  12879. renderer: this._glRenderer,
  12880. version: this._glVersion
  12881. };
  12882. };
  12883. /**
  12884. * Gets current aspect ratio
  12885. * @param camera defines the camera to use to get the aspect ratio
  12886. * @param useScreen defines if screen size must be used (or the current render target if any)
  12887. * @returns a number defining the aspect ratio
  12888. */
  12889. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12890. if (useScreen === void 0) { useScreen = false; }
  12891. var viewport = camera.viewport;
  12892. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12893. };
  12894. /**
  12895. * Gets current screen aspect ratio
  12896. * @returns a number defining the aspect ratio
  12897. */
  12898. Engine.prototype.getScreenAspectRatio = function () {
  12899. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12900. };
  12901. /**
  12902. * Gets the current render width
  12903. * @param useScreen defines if screen size must be used (or the current render target if any)
  12904. * @returns a number defining the current render width
  12905. */
  12906. Engine.prototype.getRenderWidth = function (useScreen) {
  12907. if (useScreen === void 0) { useScreen = false; }
  12908. if (!useScreen && this._currentRenderTarget) {
  12909. return this._currentRenderTarget.width;
  12910. }
  12911. return this._gl.drawingBufferWidth;
  12912. };
  12913. /**
  12914. * Gets the current render height
  12915. * @param useScreen defines if screen size must be used (or the current render target if any)
  12916. * @returns a number defining the current render height
  12917. */
  12918. Engine.prototype.getRenderHeight = function (useScreen) {
  12919. if (useScreen === void 0) { useScreen = false; }
  12920. if (!useScreen && this._currentRenderTarget) {
  12921. return this._currentRenderTarget.height;
  12922. }
  12923. return this._gl.drawingBufferHeight;
  12924. };
  12925. /**
  12926. * Gets the HTML canvas attached with the current webGL context
  12927. * @returns a HTML canvas
  12928. */
  12929. Engine.prototype.getRenderingCanvas = function () {
  12930. return this._renderingCanvas;
  12931. };
  12932. /**
  12933. * Gets the client rect of the HTML canvas attached with the current webGL context
  12934. * @returns a client rectanglee
  12935. */
  12936. Engine.prototype.getRenderingCanvasClientRect = function () {
  12937. if (!this._renderingCanvas) {
  12938. return null;
  12939. }
  12940. return this._renderingCanvas.getBoundingClientRect();
  12941. };
  12942. /**
  12943. * Defines the hardware scaling level.
  12944. * By default the hardware scaling level is computed from the window device ratio.
  12945. * 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.
  12946. * @param level defines the level to use
  12947. */
  12948. Engine.prototype.setHardwareScalingLevel = function (level) {
  12949. this._hardwareScalingLevel = level;
  12950. this.resize();
  12951. };
  12952. /**
  12953. * Gets the current hardware scaling level.
  12954. * By default the hardware scaling level is computed from the window device ratio.
  12955. * 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.
  12956. * @returns a number indicating the current hardware scaling level
  12957. */
  12958. Engine.prototype.getHardwareScalingLevel = function () {
  12959. return this._hardwareScalingLevel;
  12960. };
  12961. /**
  12962. * Gets the list of loaded textures
  12963. * @returns an array containing all loaded textures
  12964. */
  12965. Engine.prototype.getLoadedTexturesCache = function () {
  12966. return this._internalTexturesCache;
  12967. };
  12968. /**
  12969. * Gets the object containing all engine capabilities
  12970. * @returns the EngineCapabilities object
  12971. */
  12972. Engine.prototype.getCaps = function () {
  12973. return this._caps;
  12974. };
  12975. Object.defineProperty(Engine.prototype, "drawCalls", {
  12976. /** @hidden */
  12977. get: function () {
  12978. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12979. return 0;
  12980. },
  12981. enumerable: true,
  12982. configurable: true
  12983. });
  12984. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12985. /** @hidden */
  12986. get: function () {
  12987. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12988. return null;
  12989. },
  12990. enumerable: true,
  12991. configurable: true
  12992. });
  12993. /**
  12994. * Gets the current depth function
  12995. * @returns a number defining the depth function
  12996. */
  12997. Engine.prototype.getDepthFunction = function () {
  12998. return this._depthCullingState.depthFunc;
  12999. };
  13000. /**
  13001. * Sets the current depth function
  13002. * @param depthFunc defines the function to use
  13003. */
  13004. Engine.prototype.setDepthFunction = function (depthFunc) {
  13005. this._depthCullingState.depthFunc = depthFunc;
  13006. };
  13007. /**
  13008. * Sets the current depth function to GREATER
  13009. */
  13010. Engine.prototype.setDepthFunctionToGreater = function () {
  13011. this._depthCullingState.depthFunc = this._gl.GREATER;
  13012. };
  13013. /**
  13014. * Sets the current depth function to GEQUAL
  13015. */
  13016. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  13017. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  13018. };
  13019. /**
  13020. * Sets the current depth function to LESS
  13021. */
  13022. Engine.prototype.setDepthFunctionToLess = function () {
  13023. this._depthCullingState.depthFunc = this._gl.LESS;
  13024. };
  13025. /**
  13026. * Sets the current depth function to LEQUAL
  13027. */
  13028. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  13029. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  13030. };
  13031. /**
  13032. * Gets a boolean indicating if stencil buffer is enabled
  13033. * @returns the current stencil buffer state
  13034. */
  13035. Engine.prototype.getStencilBuffer = function () {
  13036. return this._stencilState.stencilTest;
  13037. };
  13038. /**
  13039. * Enable or disable the stencil buffer
  13040. * @param enable defines if the stencil buffer must be enabled or disabled
  13041. */
  13042. Engine.prototype.setStencilBuffer = function (enable) {
  13043. this._stencilState.stencilTest = enable;
  13044. };
  13045. /**
  13046. * Gets the current stencil mask
  13047. * @returns a number defining the new stencil mask to use
  13048. */
  13049. Engine.prototype.getStencilMask = function () {
  13050. return this._stencilState.stencilMask;
  13051. };
  13052. /**
  13053. * Sets the current stencil mask
  13054. * @param mask defines the new stencil mask to use
  13055. */
  13056. Engine.prototype.setStencilMask = function (mask) {
  13057. this._stencilState.stencilMask = mask;
  13058. };
  13059. /**
  13060. * Gets the current stencil function
  13061. * @returns a number defining the stencil function to use
  13062. */
  13063. Engine.prototype.getStencilFunction = function () {
  13064. return this._stencilState.stencilFunc;
  13065. };
  13066. /**
  13067. * Gets the current stencil reference value
  13068. * @returns a number defining the stencil reference value to use
  13069. */
  13070. Engine.prototype.getStencilFunctionReference = function () {
  13071. return this._stencilState.stencilFuncRef;
  13072. };
  13073. /**
  13074. * Gets the current stencil mask
  13075. * @returns a number defining the stencil mask to use
  13076. */
  13077. Engine.prototype.getStencilFunctionMask = function () {
  13078. return this._stencilState.stencilFuncMask;
  13079. };
  13080. /**
  13081. * Sets the current stencil function
  13082. * @param stencilFunc defines the new stencil function to use
  13083. */
  13084. Engine.prototype.setStencilFunction = function (stencilFunc) {
  13085. this._stencilState.stencilFunc = stencilFunc;
  13086. };
  13087. /**
  13088. * Sets the current stencil reference
  13089. * @param reference defines the new stencil reference to use
  13090. */
  13091. Engine.prototype.setStencilFunctionReference = function (reference) {
  13092. this._stencilState.stencilFuncRef = reference;
  13093. };
  13094. /**
  13095. * Sets the current stencil mask
  13096. * @param mask defines the new stencil mask to use
  13097. */
  13098. Engine.prototype.setStencilFunctionMask = function (mask) {
  13099. this._stencilState.stencilFuncMask = mask;
  13100. };
  13101. /**
  13102. * Gets the current stencil operation when stencil fails
  13103. * @returns a number defining stencil operation to use when stencil fails
  13104. */
  13105. Engine.prototype.getStencilOperationFail = function () {
  13106. return this._stencilState.stencilOpStencilFail;
  13107. };
  13108. /**
  13109. * Gets the current stencil operation when depth fails
  13110. * @returns a number defining stencil operation to use when depth fails
  13111. */
  13112. Engine.prototype.getStencilOperationDepthFail = function () {
  13113. return this._stencilState.stencilOpDepthFail;
  13114. };
  13115. /**
  13116. * Gets the current stencil operation when stencil passes
  13117. * @returns a number defining stencil operation to use when stencil passes
  13118. */
  13119. Engine.prototype.getStencilOperationPass = function () {
  13120. return this._stencilState.stencilOpStencilDepthPass;
  13121. };
  13122. /**
  13123. * Sets the stencil operation to use when stencil fails
  13124. * @param operation defines the stencil operation to use when stencil fails
  13125. */
  13126. Engine.prototype.setStencilOperationFail = function (operation) {
  13127. this._stencilState.stencilOpStencilFail = operation;
  13128. };
  13129. /**
  13130. * Sets the stencil operation to use when depth fails
  13131. * @param operation defines the stencil operation to use when depth fails
  13132. */
  13133. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  13134. this._stencilState.stencilOpDepthFail = operation;
  13135. };
  13136. /**
  13137. * Sets the stencil operation to use when stencil passes
  13138. * @param operation defines the stencil operation to use when stencil passes
  13139. */
  13140. Engine.prototype.setStencilOperationPass = function (operation) {
  13141. this._stencilState.stencilOpStencilDepthPass = operation;
  13142. };
  13143. /**
  13144. * Sets a boolean indicating if the dithering state is enabled or disabled
  13145. * @param value defines the dithering state
  13146. */
  13147. Engine.prototype.setDitheringState = function (value) {
  13148. if (value) {
  13149. this._gl.enable(this._gl.DITHER);
  13150. }
  13151. else {
  13152. this._gl.disable(this._gl.DITHER);
  13153. }
  13154. };
  13155. /**
  13156. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  13157. * @param value defines the rasterizer state
  13158. */
  13159. Engine.prototype.setRasterizerState = function (value) {
  13160. if (value) {
  13161. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  13162. }
  13163. else {
  13164. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  13165. }
  13166. };
  13167. /**
  13168. * stop executing a render loop function and remove it from the execution array
  13169. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  13170. */
  13171. Engine.prototype.stopRenderLoop = function (renderFunction) {
  13172. if (!renderFunction) {
  13173. this._activeRenderLoops = [];
  13174. return;
  13175. }
  13176. var index = this._activeRenderLoops.indexOf(renderFunction);
  13177. if (index >= 0) {
  13178. this._activeRenderLoops.splice(index, 1);
  13179. }
  13180. };
  13181. /** @hidden */
  13182. Engine.prototype._renderLoop = function () {
  13183. if (!this._contextWasLost) {
  13184. var shouldRender = true;
  13185. if (!this.renderEvenInBackground && this._windowIsBackground) {
  13186. shouldRender = false;
  13187. }
  13188. if (shouldRender) {
  13189. // Start new frame
  13190. this.beginFrame();
  13191. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  13192. var renderFunction = this._activeRenderLoops[index];
  13193. renderFunction();
  13194. }
  13195. // Present
  13196. this.endFrame();
  13197. }
  13198. }
  13199. if (this._activeRenderLoops.length > 0) {
  13200. // Register new frame
  13201. var requester = null;
  13202. if (this._vrDisplay && this._vrDisplay.isPresenting)
  13203. requester = this._vrDisplay;
  13204. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  13205. }
  13206. else {
  13207. this._renderingQueueLaunched = false;
  13208. }
  13209. };
  13210. /**
  13211. * Register and execute a render loop. The engine can have more than one render function
  13212. * @param renderFunction defines the function to continuously execute
  13213. */
  13214. Engine.prototype.runRenderLoop = function (renderFunction) {
  13215. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  13216. return;
  13217. }
  13218. this._activeRenderLoops.push(renderFunction);
  13219. if (!this._renderingQueueLaunched) {
  13220. this._renderingQueueLaunched = true;
  13221. this._bindedRenderFunction = this._renderLoop.bind(this);
  13222. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  13223. }
  13224. };
  13225. /**
  13226. * Toggle full screen mode
  13227. * @param requestPointerLock defines if a pointer lock should be requested from the user
  13228. */
  13229. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  13230. if (this.isFullscreen) {
  13231. BABYLON.Tools.ExitFullscreen();
  13232. }
  13233. else {
  13234. this._pointerLockRequested = requestPointerLock;
  13235. if (this._renderingCanvas) {
  13236. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  13237. }
  13238. }
  13239. };
  13240. /**
  13241. * Clear the current render buffer or the current render target (if any is set up)
  13242. * @param color defines the color to use
  13243. * @param backBuffer defines if the back buffer must be cleared
  13244. * @param depth defines if the depth buffer must be cleared
  13245. * @param stencil defines if the stencil buffer must be cleared
  13246. */
  13247. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  13248. if (stencil === void 0) { stencil = false; }
  13249. this.applyStates();
  13250. var mode = 0;
  13251. if (backBuffer && color) {
  13252. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  13253. mode |= this._gl.COLOR_BUFFER_BIT;
  13254. }
  13255. if (depth) {
  13256. this._gl.clearDepth(1.0);
  13257. mode |= this._gl.DEPTH_BUFFER_BIT;
  13258. }
  13259. if (stencil) {
  13260. this._gl.clearStencil(0);
  13261. mode |= this._gl.STENCIL_BUFFER_BIT;
  13262. }
  13263. this._gl.clear(mode);
  13264. };
  13265. /**
  13266. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  13267. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  13268. * @param y defines the y-coordinate of the corner of the clear rectangle
  13269. * @param width defines the width of the clear rectangle
  13270. * @param height defines the height of the clear rectangle
  13271. * @param clearColor defines the clear color
  13272. */
  13273. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  13274. var gl = this._gl;
  13275. // Save state
  13276. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  13277. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  13278. // Change state
  13279. gl.enable(gl.SCISSOR_TEST);
  13280. gl.scissor(x, y, width, height);
  13281. // Clear
  13282. this.clear(clearColor, true, true, true);
  13283. // Restore state
  13284. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  13285. if (curScissor === true) {
  13286. gl.enable(gl.SCISSOR_TEST);
  13287. }
  13288. else {
  13289. gl.disable(gl.SCISSOR_TEST);
  13290. }
  13291. };
  13292. /** @hidden */
  13293. Engine.prototype._viewport = function (x, y, width, height) {
  13294. if (x !== this._viewportCached.x ||
  13295. y !== this._viewportCached.y ||
  13296. width !== this._viewportCached.z ||
  13297. height !== this._viewportCached.w) {
  13298. this._viewportCached.x = x;
  13299. this._viewportCached.y = y;
  13300. this._viewportCached.z = width;
  13301. this._viewportCached.w = height;
  13302. this._gl.viewport(x, y, width, height);
  13303. }
  13304. };
  13305. /**
  13306. * Set the WebGL's viewport
  13307. * @param viewport defines the viewport element to be used
  13308. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  13309. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  13310. */
  13311. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  13312. var width = requiredWidth || this.getRenderWidth();
  13313. var height = requiredHeight || this.getRenderHeight();
  13314. var x = viewport.x || 0;
  13315. var y = viewport.y || 0;
  13316. this._cachedViewport = viewport;
  13317. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  13318. };
  13319. /**
  13320. * Directly set the WebGL Viewport
  13321. * @param x defines the x coordinate of the viewport (in screen space)
  13322. * @param y defines the y coordinate of the viewport (in screen space)
  13323. * @param width defines the width of the viewport (in screen space)
  13324. * @param height defines the height of the viewport (in screen space)
  13325. * @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
  13326. */
  13327. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  13328. var currentViewport = this._cachedViewport;
  13329. this._cachedViewport = null;
  13330. this._viewport(x, y, width, height);
  13331. return currentViewport;
  13332. };
  13333. /**
  13334. * Begin a new frame
  13335. */
  13336. Engine.prototype.beginFrame = function () {
  13337. this.onBeginFrameObservable.notifyObservers(this);
  13338. this._measureFps();
  13339. };
  13340. /**
  13341. * Enf the current frame
  13342. */
  13343. Engine.prototype.endFrame = function () {
  13344. // Force a flush in case we are using a bad OS.
  13345. if (this._badOS) {
  13346. this.flushFramebuffer();
  13347. }
  13348. // Submit frame to the vr device, if enabled
  13349. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13350. // TODO: We should only submit the frame if we read frameData successfully.
  13351. this._vrDisplay.submitFrame();
  13352. }
  13353. this.onEndFrameObservable.notifyObservers(this);
  13354. };
  13355. /**
  13356. * Resize the view according to the canvas' size
  13357. */
  13358. Engine.prototype.resize = function () {
  13359. // We're not resizing the size of the canvas while in VR mode & presenting
  13360. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  13361. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  13362. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  13363. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  13364. }
  13365. };
  13366. /**
  13367. * Force a specific size of the canvas
  13368. * @param width defines the new canvas' width
  13369. * @param height defines the new canvas' height
  13370. */
  13371. Engine.prototype.setSize = function (width, height) {
  13372. if (!this._renderingCanvas) {
  13373. return;
  13374. }
  13375. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13376. return;
  13377. }
  13378. this._renderingCanvas.width = width;
  13379. this._renderingCanvas.height = height;
  13380. for (var index = 0; index < this.scenes.length; index++) {
  13381. var scene = this.scenes[index];
  13382. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13383. var cam = scene.cameras[camIndex];
  13384. cam._currentRenderId = 0;
  13385. }
  13386. }
  13387. if (this.onResizeObservable.hasObservers) {
  13388. this.onResizeObservable.notifyObservers(this);
  13389. }
  13390. };
  13391. // WebVR functions
  13392. /**
  13393. * Gets a boolean indicating if a webVR device was detected
  13394. * @returns true if a webVR device was detected
  13395. */
  13396. Engine.prototype.isVRDevicePresent = function () {
  13397. return !!this._vrDisplay;
  13398. };
  13399. /**
  13400. * Gets the current webVR device
  13401. * @returns the current webVR device (or null)
  13402. */
  13403. Engine.prototype.getVRDevice = function () {
  13404. return this._vrDisplay;
  13405. };
  13406. /**
  13407. * Initializes a webVR display and starts listening to display change events
  13408. * The onVRDisplayChangedObservable will be notified upon these changes
  13409. * @returns The onVRDisplayChangedObservable
  13410. */
  13411. Engine.prototype.initWebVR = function () {
  13412. this.initWebVRAsync();
  13413. return this.onVRDisplayChangedObservable;
  13414. };
  13415. /**
  13416. * Initializes a webVR display and starts listening to display change events
  13417. * The onVRDisplayChangedObservable will be notified upon these changes
  13418. * @returns A promise containing a VRDisplay and if vr is supported
  13419. */
  13420. Engine.prototype.initWebVRAsync = function () {
  13421. var _this = this;
  13422. var notifyObservers = function () {
  13423. var eventArgs = {
  13424. vrDisplay: _this._vrDisplay,
  13425. vrSupported: _this._vrSupported
  13426. };
  13427. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13428. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13429. };
  13430. if (!this._onVrDisplayConnect) {
  13431. this._onVrDisplayConnect = function (event) {
  13432. _this._vrDisplay = event.display;
  13433. notifyObservers();
  13434. };
  13435. this._onVrDisplayDisconnect = function () {
  13436. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13437. _this._vrDisplay = undefined;
  13438. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13439. notifyObservers();
  13440. };
  13441. this._onVrDisplayPresentChange = function () {
  13442. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13443. };
  13444. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13445. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13446. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13447. }
  13448. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13449. this._webVRInitPromise.then(notifyObservers);
  13450. return this._webVRInitPromise;
  13451. };
  13452. /**
  13453. * Call this function to switch to webVR mode
  13454. * Will do nothing if webVR is not supported or if there is no webVR device
  13455. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13456. */
  13457. Engine.prototype.enableVR = function () {
  13458. var _this = this;
  13459. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13460. var onResolved = function () {
  13461. _this.onVRRequestPresentComplete.notifyObservers(true);
  13462. _this._onVRFullScreenTriggered();
  13463. };
  13464. var onRejected = function () {
  13465. _this.onVRRequestPresentComplete.notifyObservers(false);
  13466. };
  13467. this.onVRRequestPresentStart.notifyObservers(this);
  13468. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13469. }
  13470. };
  13471. /**
  13472. * Call this function to leave webVR mode
  13473. * Will do nothing if webVR is not supported or if there is no webVR device
  13474. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13475. */
  13476. Engine.prototype.disableVR = function () {
  13477. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13478. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13479. }
  13480. };
  13481. Engine.prototype._getVRDisplaysAsync = function () {
  13482. var _this = this;
  13483. return new Promise(function (res, rej) {
  13484. if (navigator.getVRDisplays) {
  13485. navigator.getVRDisplays().then(function (devices) {
  13486. _this._vrSupported = true;
  13487. // note that devices may actually be an empty array. This is fine;
  13488. // we expect this._vrDisplay to be undefined in this case.
  13489. _this._vrDisplay = devices[0];
  13490. res({
  13491. vrDisplay: _this._vrDisplay,
  13492. vrSupported: _this._vrSupported
  13493. });
  13494. });
  13495. }
  13496. else {
  13497. _this._vrDisplay = undefined;
  13498. _this._vrSupported = false;
  13499. res({
  13500. vrDisplay: _this._vrDisplay,
  13501. vrSupported: _this._vrSupported
  13502. });
  13503. }
  13504. });
  13505. };
  13506. /**
  13507. * Binds the frame buffer to the specified texture.
  13508. * @param texture The texture to render to or null for the default canvas
  13509. * @param faceIndex The face of the texture to render to in case of cube texture
  13510. * @param requiredWidth The width of the target to render to
  13511. * @param requiredHeight The height of the target to render to
  13512. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13513. * @param depthStencilTexture The depth stencil texture to use to render
  13514. * @param lodLevel defines le lod level to bind to the frame buffer
  13515. */
  13516. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13517. if (lodLevel === void 0) { lodLevel = 0; }
  13518. if (this._currentRenderTarget) {
  13519. this.unBindFramebuffer(this._currentRenderTarget);
  13520. }
  13521. this._currentRenderTarget = texture;
  13522. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13523. var gl = this._gl;
  13524. if (texture.isCube) {
  13525. if (faceIndex === undefined) {
  13526. faceIndex = 0;
  13527. }
  13528. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13529. if (depthStencilTexture) {
  13530. if (depthStencilTexture._generateStencilBuffer) {
  13531. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13532. }
  13533. else {
  13534. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13535. }
  13536. }
  13537. }
  13538. if (this._cachedViewport && !forceFullscreenViewport) {
  13539. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13540. }
  13541. else {
  13542. if (!requiredWidth) {
  13543. requiredWidth = texture.width;
  13544. if (lodLevel) {
  13545. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13546. }
  13547. }
  13548. if (!requiredHeight) {
  13549. requiredHeight = texture.height;
  13550. if (lodLevel) {
  13551. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13552. }
  13553. }
  13554. this._viewport(0, 0, requiredWidth, requiredHeight);
  13555. }
  13556. this.wipeCaches();
  13557. };
  13558. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13559. if (this._currentFramebuffer !== framebuffer) {
  13560. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13561. this._currentFramebuffer = framebuffer;
  13562. }
  13563. };
  13564. /**
  13565. * Unbind the current render target texture from the webGL context
  13566. * @param texture defines the render target texture to unbind
  13567. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13568. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13569. */
  13570. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13571. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13572. this._currentRenderTarget = null;
  13573. // If MSAA, we need to bitblt back to main texture
  13574. var gl = this._gl;
  13575. if (texture._MSAAFramebuffer) {
  13576. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13577. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13578. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13579. }
  13580. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13581. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13582. gl.generateMipmap(gl.TEXTURE_2D);
  13583. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13584. }
  13585. if (onBeforeUnbind) {
  13586. if (texture._MSAAFramebuffer) {
  13587. // Bind the correct framebuffer
  13588. this.bindUnboundFramebuffer(texture._framebuffer);
  13589. }
  13590. onBeforeUnbind();
  13591. }
  13592. this.bindUnboundFramebuffer(null);
  13593. };
  13594. /**
  13595. * Unbind a list of render target textures from the webGL context
  13596. * This is used only when drawBuffer extension or webGL2 are active
  13597. * @param textures defines the render target textures to unbind
  13598. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13599. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13600. */
  13601. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13602. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13603. this._currentRenderTarget = null;
  13604. // If MSAA, we need to bitblt back to main texture
  13605. var gl = this._gl;
  13606. if (textures[0]._MSAAFramebuffer) {
  13607. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13608. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13609. var attachments = textures[0]._attachments;
  13610. if (!attachments) {
  13611. attachments = new Array(textures.length);
  13612. textures[0]._attachments = attachments;
  13613. }
  13614. for (var i = 0; i < textures.length; i++) {
  13615. var texture = textures[i];
  13616. for (var j = 0; j < attachments.length; j++) {
  13617. attachments[j] = gl.NONE;
  13618. }
  13619. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13620. gl.readBuffer(attachments[i]);
  13621. gl.drawBuffers(attachments);
  13622. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13623. }
  13624. for (var i = 0; i < attachments.length; i++) {
  13625. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13626. }
  13627. gl.drawBuffers(attachments);
  13628. }
  13629. for (var i = 0; i < textures.length; i++) {
  13630. var texture = textures[i];
  13631. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13632. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13633. gl.generateMipmap(gl.TEXTURE_2D);
  13634. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13635. }
  13636. }
  13637. if (onBeforeUnbind) {
  13638. if (textures[0]._MSAAFramebuffer) {
  13639. // Bind the correct framebuffer
  13640. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13641. }
  13642. onBeforeUnbind();
  13643. }
  13644. this.bindUnboundFramebuffer(null);
  13645. };
  13646. /**
  13647. * Force the mipmap generation for the given render target texture
  13648. * @param texture defines the render target texture to use
  13649. */
  13650. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13651. if (texture.generateMipMaps) {
  13652. var gl = this._gl;
  13653. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13654. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13655. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13656. }
  13657. };
  13658. /**
  13659. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13660. */
  13661. Engine.prototype.flushFramebuffer = function () {
  13662. this._gl.flush();
  13663. };
  13664. /**
  13665. * Unbind the current render target and bind the default framebuffer
  13666. */
  13667. Engine.prototype.restoreDefaultFramebuffer = function () {
  13668. if (this._currentRenderTarget) {
  13669. this.unBindFramebuffer(this._currentRenderTarget);
  13670. }
  13671. else {
  13672. this.bindUnboundFramebuffer(null);
  13673. }
  13674. if (this._cachedViewport) {
  13675. this.setViewport(this._cachedViewport);
  13676. }
  13677. this.wipeCaches();
  13678. };
  13679. // UBOs
  13680. /**
  13681. * Create an uniform buffer
  13682. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13683. * @param elements defines the content of the uniform buffer
  13684. * @returns the webGL uniform buffer
  13685. */
  13686. Engine.prototype.createUniformBuffer = function (elements) {
  13687. var ubo = this._gl.createBuffer();
  13688. if (!ubo) {
  13689. throw new Error("Unable to create uniform buffer");
  13690. }
  13691. this.bindUniformBuffer(ubo);
  13692. if (elements instanceof Float32Array) {
  13693. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13694. }
  13695. else {
  13696. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13697. }
  13698. this.bindUniformBuffer(null);
  13699. ubo.references = 1;
  13700. return ubo;
  13701. };
  13702. /**
  13703. * Create a dynamic uniform buffer
  13704. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13705. * @param elements defines the content of the uniform buffer
  13706. * @returns the webGL uniform buffer
  13707. */
  13708. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13709. var ubo = this._gl.createBuffer();
  13710. if (!ubo) {
  13711. throw new Error("Unable to create dynamic uniform buffer");
  13712. }
  13713. this.bindUniformBuffer(ubo);
  13714. if (elements instanceof Float32Array) {
  13715. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13716. }
  13717. else {
  13718. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13719. }
  13720. this.bindUniformBuffer(null);
  13721. ubo.references = 1;
  13722. return ubo;
  13723. };
  13724. /**
  13725. * Update an existing uniform buffer
  13726. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13727. * @param uniformBuffer defines the target uniform buffer
  13728. * @param elements defines the content to update
  13729. * @param offset defines the offset in the uniform buffer where update should start
  13730. * @param count defines the size of the data to update
  13731. */
  13732. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13733. this.bindUniformBuffer(uniformBuffer);
  13734. if (offset === undefined) {
  13735. offset = 0;
  13736. }
  13737. if (count === undefined) {
  13738. if (elements instanceof Float32Array) {
  13739. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13740. }
  13741. else {
  13742. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13743. }
  13744. }
  13745. else {
  13746. if (elements instanceof Float32Array) {
  13747. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13748. }
  13749. else {
  13750. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13751. }
  13752. }
  13753. this.bindUniformBuffer(null);
  13754. };
  13755. // VBOs
  13756. Engine.prototype._resetVertexBufferBinding = function () {
  13757. this.bindArrayBuffer(null);
  13758. this._cachedVertexBuffers = null;
  13759. };
  13760. /**
  13761. * Creates a vertex buffer
  13762. * @param data the data for the vertex buffer
  13763. * @returns the new WebGL static buffer
  13764. */
  13765. Engine.prototype.createVertexBuffer = function (data) {
  13766. var vbo = this._gl.createBuffer();
  13767. if (!vbo) {
  13768. throw new Error("Unable to create vertex buffer");
  13769. }
  13770. this.bindArrayBuffer(vbo);
  13771. if (data instanceof Array) {
  13772. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13773. }
  13774. else {
  13775. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13776. }
  13777. this._resetVertexBufferBinding();
  13778. vbo.references = 1;
  13779. return vbo;
  13780. };
  13781. /**
  13782. * Creates a dynamic vertex buffer
  13783. * @param data the data for the dynamic vertex buffer
  13784. * @returns the new WebGL dynamic buffer
  13785. */
  13786. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13787. var vbo = this._gl.createBuffer();
  13788. if (!vbo) {
  13789. throw new Error("Unable to create dynamic vertex buffer");
  13790. }
  13791. this.bindArrayBuffer(vbo);
  13792. if (data instanceof Array) {
  13793. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13794. }
  13795. else {
  13796. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13797. }
  13798. this._resetVertexBufferBinding();
  13799. vbo.references = 1;
  13800. return vbo;
  13801. };
  13802. /**
  13803. * Update a dynamic index buffer
  13804. * @param indexBuffer defines the target index buffer
  13805. * @param indices defines the data to update
  13806. * @param offset defines the offset in the target index buffer where update should start
  13807. */
  13808. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13809. if (offset === void 0) { offset = 0; }
  13810. // Force cache update
  13811. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13812. this.bindIndexBuffer(indexBuffer);
  13813. var arrayBuffer;
  13814. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13815. arrayBuffer = indices;
  13816. }
  13817. else {
  13818. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13819. }
  13820. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13821. this._resetIndexBufferBinding();
  13822. };
  13823. /**
  13824. * Updates a dynamic vertex buffer.
  13825. * @param vertexBuffer the vertex buffer to update
  13826. * @param data the data used to update the vertex buffer
  13827. * @param byteOffset the byte offset of the data
  13828. * @param byteLength the byte length of the data
  13829. */
  13830. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13831. this.bindArrayBuffer(vertexBuffer);
  13832. if (byteOffset === undefined) {
  13833. byteOffset = 0;
  13834. }
  13835. if (byteLength === undefined) {
  13836. if (data instanceof Array) {
  13837. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13838. }
  13839. else {
  13840. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13841. }
  13842. }
  13843. else {
  13844. if (data instanceof Array) {
  13845. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13846. }
  13847. else {
  13848. if (data instanceof ArrayBuffer) {
  13849. data = new Uint8Array(data, byteOffset, byteLength);
  13850. }
  13851. else {
  13852. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13853. }
  13854. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13855. }
  13856. }
  13857. this._resetVertexBufferBinding();
  13858. };
  13859. Engine.prototype._resetIndexBufferBinding = function () {
  13860. this.bindIndexBuffer(null);
  13861. this._cachedIndexBuffer = null;
  13862. };
  13863. /**
  13864. * Creates a new index buffer
  13865. * @param indices defines the content of the index buffer
  13866. * @param updatable defines if the index buffer must be updatable
  13867. * @returns a new webGL buffer
  13868. */
  13869. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13870. var vbo = this._gl.createBuffer();
  13871. if (!vbo) {
  13872. throw new Error("Unable to create index buffer");
  13873. }
  13874. this.bindIndexBuffer(vbo);
  13875. // Check for 32 bits indices
  13876. var arrayBuffer;
  13877. var need32Bits = false;
  13878. if (indices instanceof Uint16Array) {
  13879. arrayBuffer = indices;
  13880. }
  13881. else {
  13882. //check 32 bit support
  13883. if (this._caps.uintIndices) {
  13884. if (indices instanceof Uint32Array) {
  13885. arrayBuffer = indices;
  13886. need32Bits = true;
  13887. }
  13888. else {
  13889. //number[] or Int32Array, check if 32 bit is necessary
  13890. for (var index = 0; index < indices.length; index++) {
  13891. if (indices[index] > 65535) {
  13892. need32Bits = true;
  13893. break;
  13894. }
  13895. }
  13896. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13897. }
  13898. }
  13899. else {
  13900. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13901. arrayBuffer = new Uint16Array(indices);
  13902. }
  13903. }
  13904. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13905. this._resetIndexBufferBinding();
  13906. vbo.references = 1;
  13907. vbo.is32Bits = need32Bits;
  13908. return vbo;
  13909. };
  13910. /**
  13911. * Bind a webGL buffer to the webGL context
  13912. * @param buffer defines the buffer to bind
  13913. */
  13914. Engine.prototype.bindArrayBuffer = function (buffer) {
  13915. if (!this._vaoRecordInProgress) {
  13916. this._unbindVertexArrayObject();
  13917. }
  13918. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13919. };
  13920. /**
  13921. * Bind an uniform buffer to the current webGL context
  13922. * @param buffer defines the buffer to bind
  13923. */
  13924. Engine.prototype.bindUniformBuffer = function (buffer) {
  13925. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13926. };
  13927. /**
  13928. * Bind a buffer to the current webGL context at a given location
  13929. * @param buffer defines the buffer to bind
  13930. * @param location defines the index where to bind the buffer
  13931. */
  13932. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13933. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13934. };
  13935. /**
  13936. * Bind a specific block at a given index in a specific shader program
  13937. * @param shaderProgram defines the shader program
  13938. * @param blockName defines the block name
  13939. * @param index defines the index where to bind the block
  13940. */
  13941. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13942. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13943. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13944. };
  13945. ;
  13946. Engine.prototype.bindIndexBuffer = function (buffer) {
  13947. if (!this._vaoRecordInProgress) {
  13948. this._unbindVertexArrayObject();
  13949. }
  13950. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13951. };
  13952. Engine.prototype.bindBuffer = function (buffer, target) {
  13953. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13954. this._gl.bindBuffer(target, buffer);
  13955. this._currentBoundBuffer[target] = buffer;
  13956. }
  13957. };
  13958. /**
  13959. * update the bound buffer with the given data
  13960. * @param data defines the data to update
  13961. */
  13962. Engine.prototype.updateArrayBuffer = function (data) {
  13963. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13964. };
  13965. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13966. var pointer = this._currentBufferPointers[indx];
  13967. var changed = false;
  13968. if (!pointer.active) {
  13969. changed = true;
  13970. pointer.active = true;
  13971. pointer.index = indx;
  13972. pointer.size = size;
  13973. pointer.type = type;
  13974. pointer.normalized = normalized;
  13975. pointer.stride = stride;
  13976. pointer.offset = offset;
  13977. pointer.buffer = buffer;
  13978. }
  13979. else {
  13980. if (pointer.buffer !== buffer) {
  13981. pointer.buffer = buffer;
  13982. changed = true;
  13983. }
  13984. if (pointer.size !== size) {
  13985. pointer.size = size;
  13986. changed = true;
  13987. }
  13988. if (pointer.type !== type) {
  13989. pointer.type = type;
  13990. changed = true;
  13991. }
  13992. if (pointer.normalized !== normalized) {
  13993. pointer.normalized = normalized;
  13994. changed = true;
  13995. }
  13996. if (pointer.stride !== stride) {
  13997. pointer.stride = stride;
  13998. changed = true;
  13999. }
  14000. if (pointer.offset !== offset) {
  14001. pointer.offset = offset;
  14002. changed = true;
  14003. }
  14004. }
  14005. if (changed || this._vaoRecordInProgress) {
  14006. this.bindArrayBuffer(buffer);
  14007. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  14008. }
  14009. };
  14010. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  14011. if (indexBuffer == null) {
  14012. return;
  14013. }
  14014. if (this._cachedIndexBuffer !== indexBuffer) {
  14015. this._cachedIndexBuffer = indexBuffer;
  14016. this.bindIndexBuffer(indexBuffer);
  14017. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  14018. }
  14019. };
  14020. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  14021. var attributes = effect.getAttributesNames();
  14022. if (!this._vaoRecordInProgress) {
  14023. this._unbindVertexArrayObject();
  14024. }
  14025. this.unbindAllAttributes();
  14026. for (var index = 0; index < attributes.length; index++) {
  14027. var order = effect.getAttributeLocation(index);
  14028. if (order >= 0) {
  14029. var vertexBuffer = vertexBuffers[attributes[index]];
  14030. if (!vertexBuffer) {
  14031. continue;
  14032. }
  14033. this._gl.enableVertexAttribArray(order);
  14034. if (!this._vaoRecordInProgress) {
  14035. this._vertexAttribArraysEnabled[order] = true;
  14036. }
  14037. var buffer = vertexBuffer.getBuffer();
  14038. if (buffer) {
  14039. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  14040. if (vertexBuffer.getIsInstanced()) {
  14041. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  14042. if (!this._vaoRecordInProgress) {
  14043. this._currentInstanceLocations.push(order);
  14044. this._currentInstanceBuffers.push(buffer);
  14045. }
  14046. }
  14047. }
  14048. }
  14049. }
  14050. };
  14051. /**
  14052. * Records a vertex array object
  14053. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14054. * @param vertexBuffers defines the list of vertex buffers to store
  14055. * @param indexBuffer defines the index buffer to store
  14056. * @param effect defines the effect to store
  14057. * @returns the new vertex array object
  14058. */
  14059. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  14060. var vao = this._gl.createVertexArray();
  14061. this._vaoRecordInProgress = true;
  14062. this._gl.bindVertexArray(vao);
  14063. this._mustWipeVertexAttributes = true;
  14064. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14065. this.bindIndexBuffer(indexBuffer);
  14066. this._vaoRecordInProgress = false;
  14067. this._gl.bindVertexArray(null);
  14068. return vao;
  14069. };
  14070. /**
  14071. * Bind a specific vertex array object
  14072. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14073. * @param vertexArrayObject defines the vertex array object to bind
  14074. * @param indexBuffer defines the index buffer to bind
  14075. */
  14076. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  14077. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  14078. this._cachedVertexArrayObject = vertexArrayObject;
  14079. this._gl.bindVertexArray(vertexArrayObject);
  14080. this._cachedVertexBuffers = null;
  14081. this._cachedIndexBuffer = null;
  14082. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  14083. this._mustWipeVertexAttributes = true;
  14084. }
  14085. };
  14086. /**
  14087. * Bind webGl buffers directly to the webGL context
  14088. * @param vertexBuffer defines the vertex buffer to bind
  14089. * @param indexBuffer defines the index buffer to bind
  14090. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  14091. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  14092. * @param effect defines the effect associated with the vertex buffer
  14093. */
  14094. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  14095. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  14096. this._cachedVertexBuffers = vertexBuffer;
  14097. this._cachedEffectForVertexBuffers = effect;
  14098. var attributesCount = effect.getAttributesCount();
  14099. this._unbindVertexArrayObject();
  14100. this.unbindAllAttributes();
  14101. var offset = 0;
  14102. for (var index = 0; index < attributesCount; index++) {
  14103. if (index < vertexDeclaration.length) {
  14104. var order = effect.getAttributeLocation(index);
  14105. if (order >= 0) {
  14106. this._gl.enableVertexAttribArray(order);
  14107. this._vertexAttribArraysEnabled[order] = true;
  14108. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  14109. }
  14110. offset += vertexDeclaration[index] * 4;
  14111. }
  14112. }
  14113. }
  14114. this._bindIndexBufferWithCache(indexBuffer);
  14115. };
  14116. Engine.prototype._unbindVertexArrayObject = function () {
  14117. if (!this._cachedVertexArrayObject) {
  14118. return;
  14119. }
  14120. this._cachedVertexArrayObject = null;
  14121. this._gl.bindVertexArray(null);
  14122. };
  14123. /**
  14124. * Bind a list of vertex buffers to the webGL context
  14125. * @param vertexBuffers defines the list of vertex buffers to bind
  14126. * @param indexBuffer defines the index buffer to bind
  14127. * @param effect defines the effect associated with the vertex buffers
  14128. */
  14129. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  14130. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  14131. this._cachedVertexBuffers = vertexBuffers;
  14132. this._cachedEffectForVertexBuffers = effect;
  14133. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14134. }
  14135. this._bindIndexBufferWithCache(indexBuffer);
  14136. };
  14137. /**
  14138. * Unbind all instance attributes
  14139. */
  14140. Engine.prototype.unbindInstanceAttributes = function () {
  14141. var boundBuffer;
  14142. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  14143. var instancesBuffer = this._currentInstanceBuffers[i];
  14144. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  14145. boundBuffer = instancesBuffer;
  14146. this.bindArrayBuffer(instancesBuffer);
  14147. }
  14148. var offsetLocation = this._currentInstanceLocations[i];
  14149. this._gl.vertexAttribDivisor(offsetLocation, 0);
  14150. }
  14151. this._currentInstanceBuffers.length = 0;
  14152. this._currentInstanceLocations.length = 0;
  14153. };
  14154. /**
  14155. * Release and free the memory of a vertex array object
  14156. * @param vao defines the vertex array object to delete
  14157. */
  14158. Engine.prototype.releaseVertexArrayObject = function (vao) {
  14159. this._gl.deleteVertexArray(vao);
  14160. };
  14161. /** @hidden */
  14162. Engine.prototype._releaseBuffer = function (buffer) {
  14163. buffer.references--;
  14164. if (buffer.references === 0) {
  14165. this._gl.deleteBuffer(buffer);
  14166. return true;
  14167. }
  14168. return false;
  14169. };
  14170. /**
  14171. * Creates a webGL buffer to use with instanciation
  14172. * @param capacity defines the size of the buffer
  14173. * @returns the webGL buffer
  14174. */
  14175. Engine.prototype.createInstancesBuffer = function (capacity) {
  14176. var buffer = this._gl.createBuffer();
  14177. if (!buffer) {
  14178. throw new Error("Unable to create instance buffer");
  14179. }
  14180. buffer.capacity = capacity;
  14181. this.bindArrayBuffer(buffer);
  14182. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  14183. return buffer;
  14184. };
  14185. /**
  14186. * Delete a webGL buffer used with instanciation
  14187. * @param buffer defines the webGL buffer to delete
  14188. */
  14189. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  14190. this._gl.deleteBuffer(buffer);
  14191. };
  14192. /**
  14193. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  14194. * @param instancesBuffer defines the webGL buffer to update and bind
  14195. * @param data defines the data to store in the buffer
  14196. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  14197. */
  14198. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  14199. this.bindArrayBuffer(instancesBuffer);
  14200. if (data) {
  14201. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14202. }
  14203. if (offsetLocations[0].index !== undefined) {
  14204. var stride = 0;
  14205. for (var i = 0; i < offsetLocations.length; i++) {
  14206. var ai = offsetLocations[i];
  14207. stride += ai.attributeSize * 4;
  14208. }
  14209. for (var i = 0; i < offsetLocations.length; i++) {
  14210. var ai = offsetLocations[i];
  14211. if (!this._vertexAttribArraysEnabled[ai.index]) {
  14212. this._gl.enableVertexAttribArray(ai.index);
  14213. this._vertexAttribArraysEnabled[ai.index] = true;
  14214. }
  14215. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  14216. this._gl.vertexAttribDivisor(ai.index, 1);
  14217. this._currentInstanceLocations.push(ai.index);
  14218. this._currentInstanceBuffers.push(instancesBuffer);
  14219. }
  14220. }
  14221. else {
  14222. for (var index = 0; index < 4; index++) {
  14223. var offsetLocation = offsetLocations[index];
  14224. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  14225. this._gl.enableVertexAttribArray(offsetLocation);
  14226. this._vertexAttribArraysEnabled[offsetLocation] = true;
  14227. }
  14228. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  14229. this._gl.vertexAttribDivisor(offsetLocation, 1);
  14230. this._currentInstanceLocations.push(offsetLocation);
  14231. this._currentInstanceBuffers.push(instancesBuffer);
  14232. }
  14233. }
  14234. };
  14235. /**
  14236. * Apply all cached states (depth, culling, stencil and alpha)
  14237. */
  14238. Engine.prototype.applyStates = function () {
  14239. this._depthCullingState.apply(this._gl);
  14240. this._stencilState.apply(this._gl);
  14241. this._alphaState.apply(this._gl);
  14242. };
  14243. /**
  14244. * Send a draw order
  14245. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14246. * @param indexStart defines the starting index
  14247. * @param indexCount defines the number of index to draw
  14248. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14249. */
  14250. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  14251. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  14252. };
  14253. /**
  14254. * Draw a list of points
  14255. * @param verticesStart defines the index of first vertex to draw
  14256. * @param verticesCount defines the count of vertices to draw
  14257. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14258. */
  14259. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  14260. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  14261. };
  14262. /**
  14263. * Draw a list of unindexed primitives
  14264. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14265. * @param verticesStart defines the index of first vertex to draw
  14266. * @param verticesCount defines the count of vertices to draw
  14267. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14268. */
  14269. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  14270. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  14271. };
  14272. /**
  14273. * Draw a list of indexed primitives
  14274. * @param fillMode defines the primitive to use
  14275. * @param indexStart defines the starting index
  14276. * @param indexCount defines the number of index to draw
  14277. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14278. */
  14279. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  14280. // Apply states
  14281. this.applyStates();
  14282. this._drawCalls.addCount(1, false);
  14283. // Render
  14284. var drawMode = this._drawMode(fillMode);
  14285. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  14286. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  14287. if (instancesCount) {
  14288. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  14289. }
  14290. else {
  14291. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  14292. }
  14293. };
  14294. /**
  14295. * Draw a list of unindexed primitives
  14296. * @param fillMode defines the primitive to use
  14297. * @param verticesStart defines the index of first vertex to draw
  14298. * @param verticesCount defines the count of vertices to draw
  14299. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14300. */
  14301. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  14302. // Apply states
  14303. this.applyStates();
  14304. this._drawCalls.addCount(1, false);
  14305. var drawMode = this._drawMode(fillMode);
  14306. if (instancesCount) {
  14307. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  14308. }
  14309. else {
  14310. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  14311. }
  14312. };
  14313. Engine.prototype._drawMode = function (fillMode) {
  14314. switch (fillMode) {
  14315. // Triangle views
  14316. case BABYLON.Material.TriangleFillMode:
  14317. return this._gl.TRIANGLES;
  14318. case BABYLON.Material.PointFillMode:
  14319. return this._gl.POINTS;
  14320. case BABYLON.Material.WireFrameFillMode:
  14321. return this._gl.LINES;
  14322. // Draw modes
  14323. case BABYLON.Material.PointListDrawMode:
  14324. return this._gl.POINTS;
  14325. case BABYLON.Material.LineListDrawMode:
  14326. return this._gl.LINES;
  14327. case BABYLON.Material.LineLoopDrawMode:
  14328. return this._gl.LINE_LOOP;
  14329. case BABYLON.Material.LineStripDrawMode:
  14330. return this._gl.LINE_STRIP;
  14331. case BABYLON.Material.TriangleStripDrawMode:
  14332. return this._gl.TRIANGLE_STRIP;
  14333. case BABYLON.Material.TriangleFanDrawMode:
  14334. return this._gl.TRIANGLE_FAN;
  14335. default:
  14336. return this._gl.TRIANGLES;
  14337. }
  14338. };
  14339. // Shaders
  14340. /** @hidden */
  14341. Engine.prototype._releaseEffect = function (effect) {
  14342. if (this._compiledEffects[effect._key]) {
  14343. delete this._compiledEffects[effect._key];
  14344. this._deleteProgram(effect.getProgram());
  14345. }
  14346. };
  14347. /** @hidden */
  14348. Engine.prototype._deleteProgram = function (program) {
  14349. if (program) {
  14350. program.__SPECTOR_rebuildProgram = null;
  14351. if (program.transformFeedback) {
  14352. this.deleteTransformFeedback(program.transformFeedback);
  14353. program.transformFeedback = null;
  14354. }
  14355. this._gl.deleteProgram(program);
  14356. }
  14357. };
  14358. /**
  14359. * Create a new effect (used to store vertex/fragment shaders)
  14360. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  14361. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  14362. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  14363. * @param samplers defines an array of string used to represent textures
  14364. * @param defines defines the string containing the defines to use to compile the shaders
  14365. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14366. * @param onCompiled defines a function to call when the effect creation is successful
  14367. * @param onError defines a function to call when the effect creation has failed
  14368. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  14369. * @returns the new Effect
  14370. */
  14371. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  14372. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  14373. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  14374. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  14375. if (this._compiledEffects[name]) {
  14376. var compiledEffect = this._compiledEffects[name];
  14377. if (onCompiled && compiledEffect.isReady()) {
  14378. onCompiled(compiledEffect);
  14379. }
  14380. return compiledEffect;
  14381. }
  14382. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14383. effect._key = name;
  14384. this._compiledEffects[name] = effect;
  14385. return effect;
  14386. };
  14387. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  14388. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  14389. };
  14390. ;
  14391. Engine.prototype._compileRawShader = function (source, type) {
  14392. var gl = this._gl;
  14393. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  14394. gl.shaderSource(shader, source);
  14395. gl.compileShader(shader);
  14396. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  14397. var log = gl.getShaderInfoLog(shader);
  14398. if (log) {
  14399. throw new Error(log);
  14400. }
  14401. }
  14402. if (!shader) {
  14403. throw new Error("Something went wrong while compile the shader.");
  14404. }
  14405. return shader;
  14406. };
  14407. ;
  14408. /**
  14409. * Directly creates a webGL program
  14410. * @param vertexCode defines the vertex shader code to use
  14411. * @param fragmentCode defines the fragment shader code to use
  14412. * @param context defines the webGL context to use (if not set, the current one will be used)
  14413. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14414. * @returns the new webGL program
  14415. */
  14416. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14417. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14418. context = context || this._gl;
  14419. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  14420. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  14421. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14422. };
  14423. /**
  14424. * Creates a webGL program
  14425. * @param vertexCode defines the vertex shader code to use
  14426. * @param fragmentCode defines the fragment shader code to use
  14427. * @param defines defines the string containing the defines to use to compile the shaders
  14428. * @param context defines the webGL context to use (if not set, the current one will be used)
  14429. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14430. * @returns the new webGL program
  14431. */
  14432. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14433. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14434. context = context || this._gl;
  14435. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14436. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14437. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  14438. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  14439. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14440. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14441. return program;
  14442. };
  14443. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14444. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14445. var shaderProgram = context.createProgram();
  14446. if (!shaderProgram) {
  14447. throw new Error("Unable to create program");
  14448. }
  14449. context.attachShader(shaderProgram, vertexShader);
  14450. context.attachShader(shaderProgram, fragmentShader);
  14451. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14452. var transformFeedback = this.createTransformFeedback();
  14453. this.bindTransformFeedback(transformFeedback);
  14454. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14455. shaderProgram.transformFeedback = transformFeedback;
  14456. }
  14457. context.linkProgram(shaderProgram);
  14458. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14459. this.bindTransformFeedback(null);
  14460. }
  14461. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14462. if (!linked) {
  14463. var error = context.getProgramInfoLog(shaderProgram);
  14464. if (error) {
  14465. throw new Error(error);
  14466. }
  14467. }
  14468. if (this.validateShaderPrograms) {
  14469. context.validateProgram(shaderProgram);
  14470. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  14471. if (!validated) {
  14472. var error = context.getProgramInfoLog(shaderProgram);
  14473. if (error) {
  14474. throw new Error(error);
  14475. }
  14476. }
  14477. }
  14478. context.deleteShader(vertexShader);
  14479. context.deleteShader(fragmentShader);
  14480. return shaderProgram;
  14481. };
  14482. /**
  14483. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14484. * @param shaderProgram defines the webGL program to use
  14485. * @param uniformsNames defines the list of uniform names
  14486. * @returns an array of webGL uniform locations
  14487. */
  14488. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14489. var results = new Array();
  14490. for (var index = 0; index < uniformsNames.length; index++) {
  14491. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14492. }
  14493. return results;
  14494. };
  14495. /**
  14496. * Gets the lsit of active attributes for a given webGL program
  14497. * @param shaderProgram defines the webGL program to use
  14498. * @param attributesNames defines the list of attribute names to get
  14499. * @returns an array of indices indicating the offset of each attribute
  14500. */
  14501. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14502. var results = [];
  14503. for (var index = 0; index < attributesNames.length; index++) {
  14504. try {
  14505. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14506. }
  14507. catch (e) {
  14508. results.push(-1);
  14509. }
  14510. }
  14511. return results;
  14512. };
  14513. /**
  14514. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14515. * @param effect defines the effect to activate
  14516. */
  14517. Engine.prototype.enableEffect = function (effect) {
  14518. if (!effect || effect === this._currentEffect) {
  14519. return;
  14520. }
  14521. // Use program
  14522. this.bindSamplers(effect);
  14523. this._currentEffect = effect;
  14524. if (effect.onBind) {
  14525. effect.onBind(effect);
  14526. }
  14527. if (effect._onBindObservable) {
  14528. effect._onBindObservable.notifyObservers(effect);
  14529. }
  14530. };
  14531. /**
  14532. * Set the value of an uniform to an array of int32
  14533. * @param uniform defines the webGL uniform location where to store the value
  14534. * @param array defines the array of int32 to store
  14535. */
  14536. Engine.prototype.setIntArray = function (uniform, array) {
  14537. if (!uniform)
  14538. return;
  14539. this._gl.uniform1iv(uniform, array);
  14540. };
  14541. /**
  14542. * Set the value of an uniform to an array of int32 (stored as vec2)
  14543. * @param uniform defines the webGL uniform location where to store the value
  14544. * @param array defines the array of int32 to store
  14545. */
  14546. Engine.prototype.setIntArray2 = function (uniform, array) {
  14547. if (!uniform || array.length % 2 !== 0)
  14548. return;
  14549. this._gl.uniform2iv(uniform, array);
  14550. };
  14551. /**
  14552. * Set the value of an uniform to an array of int32 (stored as vec3)
  14553. * @param uniform defines the webGL uniform location where to store the value
  14554. * @param array defines the array of int32 to store
  14555. */
  14556. Engine.prototype.setIntArray3 = function (uniform, array) {
  14557. if (!uniform || array.length % 3 !== 0)
  14558. return;
  14559. this._gl.uniform3iv(uniform, array);
  14560. };
  14561. /**
  14562. * Set the value of an uniform to an array of int32 (stored as vec4)
  14563. * @param uniform defines the webGL uniform location where to store the value
  14564. * @param array defines the array of int32 to store
  14565. */
  14566. Engine.prototype.setIntArray4 = function (uniform, array) {
  14567. if (!uniform || array.length % 4 !== 0)
  14568. return;
  14569. this._gl.uniform4iv(uniform, array);
  14570. };
  14571. /**
  14572. * Set the value of an uniform to an array of float32
  14573. * @param uniform defines the webGL uniform location where to store the value
  14574. * @param array defines the array of float32 to store
  14575. */
  14576. Engine.prototype.setFloatArray = function (uniform, array) {
  14577. if (!uniform)
  14578. return;
  14579. this._gl.uniform1fv(uniform, array);
  14580. };
  14581. /**
  14582. * Set the value of an uniform to an array of float32 (stored as vec2)
  14583. * @param uniform defines the webGL uniform location where to store the value
  14584. * @param array defines the array of float32 to store
  14585. */
  14586. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14587. if (!uniform || array.length % 2 !== 0)
  14588. return;
  14589. this._gl.uniform2fv(uniform, array);
  14590. };
  14591. /**
  14592. * Set the value of an uniform to an array of float32 (stored as vec3)
  14593. * @param uniform defines the webGL uniform location where to store the value
  14594. * @param array defines the array of float32 to store
  14595. */
  14596. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14597. if (!uniform || array.length % 3 !== 0)
  14598. return;
  14599. this._gl.uniform3fv(uniform, array);
  14600. };
  14601. /**
  14602. * Set the value of an uniform to an array of float32 (stored as vec4)
  14603. * @param uniform defines the webGL uniform location where to store the value
  14604. * @param array defines the array of float32 to store
  14605. */
  14606. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14607. if (!uniform || array.length % 4 !== 0)
  14608. return;
  14609. this._gl.uniform4fv(uniform, array);
  14610. };
  14611. /**
  14612. * Set the value of an uniform to an array of number
  14613. * @param uniform defines the webGL uniform location where to store the value
  14614. * @param array defines the array of number to store
  14615. */
  14616. Engine.prototype.setArray = function (uniform, array) {
  14617. if (!uniform)
  14618. return;
  14619. this._gl.uniform1fv(uniform, array);
  14620. };
  14621. /**
  14622. * Set the value of an uniform to an array of number (stored as vec2)
  14623. * @param uniform defines the webGL uniform location where to store the value
  14624. * @param array defines the array of number to store
  14625. */
  14626. Engine.prototype.setArray2 = function (uniform, array) {
  14627. if (!uniform || array.length % 2 !== 0)
  14628. return;
  14629. this._gl.uniform2fv(uniform, array);
  14630. };
  14631. /**
  14632. * Set the value of an uniform to an array of number (stored as vec3)
  14633. * @param uniform defines the webGL uniform location where to store the value
  14634. * @param array defines the array of number to store
  14635. */
  14636. Engine.prototype.setArray3 = function (uniform, array) {
  14637. if (!uniform || array.length % 3 !== 0)
  14638. return;
  14639. this._gl.uniform3fv(uniform, array);
  14640. };
  14641. /**
  14642. * Set the value of an uniform to an array of number (stored as vec4)
  14643. * @param uniform defines the webGL uniform location where to store the value
  14644. * @param array defines the array of number to store
  14645. */
  14646. Engine.prototype.setArray4 = function (uniform, array) {
  14647. if (!uniform || array.length % 4 !== 0)
  14648. return;
  14649. this._gl.uniform4fv(uniform, array);
  14650. };
  14651. /**
  14652. * Set the value of an uniform to an array of float32 (stored as matrices)
  14653. * @param uniform defines the webGL uniform location where to store the value
  14654. * @param matrices defines the array of float32 to store
  14655. */
  14656. Engine.prototype.setMatrices = function (uniform, matrices) {
  14657. if (!uniform)
  14658. return;
  14659. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14660. };
  14661. /**
  14662. * Set the value of an uniform to a matrix
  14663. * @param uniform defines the webGL uniform location where to store the value
  14664. * @param matrix defines the matrix to store
  14665. */
  14666. Engine.prototype.setMatrix = function (uniform, matrix) {
  14667. if (!uniform)
  14668. return;
  14669. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14670. };
  14671. /**
  14672. * Set the value of an uniform to a matrix (3x3)
  14673. * @param uniform defines the webGL uniform location where to store the value
  14674. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14675. */
  14676. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14677. if (!uniform)
  14678. return;
  14679. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14680. };
  14681. /**
  14682. * Set the value of an uniform to a matrix (2x2)
  14683. * @param uniform defines the webGL uniform location where to store the value
  14684. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14685. */
  14686. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14687. if (!uniform)
  14688. return;
  14689. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14690. };
  14691. /**
  14692. * Set the value of an uniform to a number (int)
  14693. * @param uniform defines the webGL uniform location where to store the value
  14694. * @param value defines the int number to store
  14695. */
  14696. Engine.prototype.setInt = function (uniform, value) {
  14697. if (!uniform)
  14698. return;
  14699. this._gl.uniform1i(uniform, value);
  14700. };
  14701. /**
  14702. * Set the value of an uniform to a number (float)
  14703. * @param uniform defines the webGL uniform location where to store the value
  14704. * @param value defines the float number to store
  14705. */
  14706. Engine.prototype.setFloat = function (uniform, value) {
  14707. if (!uniform)
  14708. return;
  14709. this._gl.uniform1f(uniform, value);
  14710. };
  14711. /**
  14712. * Set the value of an uniform to a vec2
  14713. * @param uniform defines the webGL uniform location where to store the value
  14714. * @param x defines the 1st component of the value
  14715. * @param y defines the 2nd component of the value
  14716. */
  14717. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14718. if (!uniform)
  14719. return;
  14720. this._gl.uniform2f(uniform, x, y);
  14721. };
  14722. /**
  14723. * Set the value of an uniform to a vec3
  14724. * @param uniform defines the webGL uniform location where to store the value
  14725. * @param x defines the 1st component of the value
  14726. * @param y defines the 2nd component of the value
  14727. * @param z defines the 3rd component of the value
  14728. */
  14729. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14730. if (!uniform)
  14731. return;
  14732. this._gl.uniform3f(uniform, x, y, z);
  14733. };
  14734. /**
  14735. * Set the value of an uniform to a boolean
  14736. * @param uniform defines the webGL uniform location where to store the value
  14737. * @param bool defines the boolean to store
  14738. */
  14739. Engine.prototype.setBool = function (uniform, bool) {
  14740. if (!uniform)
  14741. return;
  14742. this._gl.uniform1i(uniform, bool);
  14743. };
  14744. /**
  14745. * Set the value of an uniform to a vec4
  14746. * @param uniform defines the webGL uniform location where to store the value
  14747. * @param x defines the 1st component of the value
  14748. * @param y defines the 2nd component of the value
  14749. * @param z defines the 3rd component of the value
  14750. * @param w defines the 4th component of the value
  14751. */
  14752. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14753. if (!uniform)
  14754. return;
  14755. this._gl.uniform4f(uniform, x, y, z, w);
  14756. };
  14757. /**
  14758. * Set the value of an uniform to a Color3
  14759. * @param uniform defines the webGL uniform location where to store the value
  14760. * @param color3 defines the color to store
  14761. */
  14762. Engine.prototype.setColor3 = function (uniform, color3) {
  14763. if (!uniform)
  14764. return;
  14765. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14766. };
  14767. /**
  14768. * Set the value of an uniform to a Color3 and an alpha value
  14769. * @param uniform defines the webGL uniform location where to store the value
  14770. * @param color3 defines the color to store
  14771. * @param alpha defines the alpha component to store
  14772. */
  14773. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14774. if (!uniform)
  14775. return;
  14776. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14777. };
  14778. /**
  14779. * Sets a Color4 on a uniform variable
  14780. * @param uniform defines the uniform location
  14781. * @param color4 defines the value to be set
  14782. */
  14783. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14784. if (!uniform)
  14785. return;
  14786. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14787. };
  14788. // States
  14789. /**
  14790. * Set various states to the webGL context
  14791. * @param culling defines backface culling state
  14792. * @param zOffset defines the value to apply to zOffset (0 by default)
  14793. * @param force defines if states must be applied even if cache is up to date
  14794. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14795. */
  14796. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14797. if (zOffset === void 0) { zOffset = 0; }
  14798. if (reverseSide === void 0) { reverseSide = false; }
  14799. // Culling
  14800. if (this._depthCullingState.cull !== culling || force) {
  14801. this._depthCullingState.cull = culling;
  14802. }
  14803. // Cull face
  14804. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14805. if (this._depthCullingState.cullFace !== cullFace || force) {
  14806. this._depthCullingState.cullFace = cullFace;
  14807. }
  14808. // Z offset
  14809. this.setZOffset(zOffset);
  14810. // Front face
  14811. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14812. if (this._depthCullingState.frontFace !== frontFace || force) {
  14813. this._depthCullingState.frontFace = frontFace;
  14814. }
  14815. };
  14816. /**
  14817. * Set the z offset to apply to current rendering
  14818. * @param value defines the offset to apply
  14819. */
  14820. Engine.prototype.setZOffset = function (value) {
  14821. this._depthCullingState.zOffset = value;
  14822. };
  14823. /**
  14824. * Gets the current value of the zOffset
  14825. * @returns the current zOffset state
  14826. */
  14827. Engine.prototype.getZOffset = function () {
  14828. return this._depthCullingState.zOffset;
  14829. };
  14830. /**
  14831. * Enable or disable depth buffering
  14832. * @param enable defines the state to set
  14833. */
  14834. Engine.prototype.setDepthBuffer = function (enable) {
  14835. this._depthCullingState.depthTest = enable;
  14836. };
  14837. /**
  14838. * Gets a boolean indicating if depth writing is enabled
  14839. * @returns the current depth writing state
  14840. */
  14841. Engine.prototype.getDepthWrite = function () {
  14842. return this._depthCullingState.depthMask;
  14843. };
  14844. /**
  14845. * Enable or disable depth writing
  14846. * @param enable defines the state to set
  14847. */
  14848. Engine.prototype.setDepthWrite = function (enable) {
  14849. this._depthCullingState.depthMask = enable;
  14850. };
  14851. /**
  14852. * Enable or disable color writing
  14853. * @param enable defines the state to set
  14854. */
  14855. Engine.prototype.setColorWrite = function (enable) {
  14856. this._gl.colorMask(enable, enable, enable, enable);
  14857. this._colorWrite = enable;
  14858. };
  14859. /**
  14860. * Gets a boolean indicating if color writing is enabled
  14861. * @returns the current color writing state
  14862. */
  14863. Engine.prototype.getColorWrite = function () {
  14864. return this._colorWrite;
  14865. };
  14866. /**
  14867. * Sets alpha constants used by some alpha blending modes
  14868. * @param r defines the red component
  14869. * @param g defines the green component
  14870. * @param b defines the blue component
  14871. * @param a defines the alpha component
  14872. */
  14873. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14874. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14875. };
  14876. /**
  14877. * Sets the current alpha mode
  14878. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14879. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14880. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14881. */
  14882. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14883. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14884. if (this._alphaMode === mode) {
  14885. return;
  14886. }
  14887. switch (mode) {
  14888. case Engine.ALPHA_DISABLE:
  14889. this._alphaState.alphaBlend = false;
  14890. break;
  14891. case Engine.ALPHA_PREMULTIPLIED:
  14892. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14893. this._alphaState.alphaBlend = true;
  14894. break;
  14895. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14896. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14897. this._alphaState.alphaBlend = true;
  14898. break;
  14899. case Engine.ALPHA_COMBINE:
  14900. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14901. this._alphaState.alphaBlend = true;
  14902. break;
  14903. case Engine.ALPHA_ONEONE:
  14904. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14905. this._alphaState.alphaBlend = true;
  14906. break;
  14907. case Engine.ALPHA_ADD:
  14908. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14909. this._alphaState.alphaBlend = true;
  14910. break;
  14911. case Engine.ALPHA_SUBTRACT:
  14912. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14913. this._alphaState.alphaBlend = true;
  14914. break;
  14915. case Engine.ALPHA_MULTIPLY:
  14916. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14917. this._alphaState.alphaBlend = true;
  14918. break;
  14919. case Engine.ALPHA_MAXIMIZED:
  14920. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14921. this._alphaState.alphaBlend = true;
  14922. break;
  14923. case Engine.ALPHA_INTERPOLATE:
  14924. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14925. this._alphaState.alphaBlend = true;
  14926. break;
  14927. case Engine.ALPHA_SCREENMODE:
  14928. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14929. this._alphaState.alphaBlend = true;
  14930. break;
  14931. }
  14932. if (!noDepthWriteChange) {
  14933. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14934. }
  14935. this._alphaMode = mode;
  14936. };
  14937. /**
  14938. * Gets the current alpha mode
  14939. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14940. * @returns the current alpha mode
  14941. */
  14942. Engine.prototype.getAlphaMode = function () {
  14943. return this._alphaMode;
  14944. };
  14945. // Textures
  14946. /**
  14947. * Clears the list of texture accessible through engine.
  14948. * This can help preventing texture load conflict due to name collision.
  14949. */
  14950. Engine.prototype.clearInternalTexturesCache = function () {
  14951. this._internalTexturesCache = [];
  14952. };
  14953. /**
  14954. * Force the entire cache to be cleared
  14955. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14956. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14957. */
  14958. Engine.prototype.wipeCaches = function (bruteForce) {
  14959. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14960. return;
  14961. }
  14962. this._currentEffect = null;
  14963. this._viewportCached.x = 0;
  14964. this._viewportCached.y = 0;
  14965. this._viewportCached.z = 0;
  14966. this._viewportCached.w = 0;
  14967. if (bruteForce) {
  14968. this.resetTextureCache();
  14969. this._currentProgram = null;
  14970. this._stencilState.reset();
  14971. this._depthCullingState.reset();
  14972. this.setDepthFunctionToLessOrEqual();
  14973. this._alphaState.reset();
  14974. this._unpackFlipYCached = null;
  14975. }
  14976. this._resetVertexBufferBinding();
  14977. this._cachedIndexBuffer = null;
  14978. this._cachedEffectForVertexBuffers = null;
  14979. this._unbindVertexArrayObject();
  14980. this.bindIndexBuffer(null);
  14981. };
  14982. /**
  14983. * Set the compressed texture format to use, based on the formats you have, and the formats
  14984. * supported by the hardware / browser.
  14985. *
  14986. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14987. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14988. * to API arguments needed to compressed textures. This puts the burden on the container
  14989. * generator to house the arcane code for determining these for current & future formats.
  14990. *
  14991. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14992. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14993. *
  14994. * Note: The result of this call is not taken into account when a texture is base64.
  14995. *
  14996. * @param formatsAvailable defines the list of those format families you have created
  14997. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14998. *
  14999. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  15000. * @returns The extension selected.
  15001. */
  15002. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  15003. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  15004. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  15005. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  15006. return this._textureFormatInUse = this._texturesSupported[i];
  15007. }
  15008. }
  15009. }
  15010. // actively set format to nothing, to allow this to be called more than once
  15011. // and possibly fail the 2nd time
  15012. this._textureFormatInUse = null;
  15013. return null;
  15014. };
  15015. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  15016. var gl = this._gl;
  15017. var magFilter = gl.NEAREST;
  15018. var minFilter = gl.NEAREST;
  15019. switch (samplingMode) {
  15020. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  15021. magFilter = gl.LINEAR;
  15022. if (generateMipMaps) {
  15023. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15024. }
  15025. else {
  15026. minFilter = gl.LINEAR;
  15027. }
  15028. break;
  15029. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  15030. magFilter = gl.LINEAR;
  15031. if (generateMipMaps) {
  15032. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15033. }
  15034. else {
  15035. minFilter = gl.LINEAR;
  15036. }
  15037. break;
  15038. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  15039. magFilter = gl.NEAREST;
  15040. if (generateMipMaps) {
  15041. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15042. }
  15043. else {
  15044. minFilter = gl.NEAREST;
  15045. }
  15046. break;
  15047. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  15048. magFilter = gl.NEAREST;
  15049. if (generateMipMaps) {
  15050. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15051. }
  15052. else {
  15053. minFilter = gl.NEAREST;
  15054. }
  15055. break;
  15056. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  15057. magFilter = gl.NEAREST;
  15058. if (generateMipMaps) {
  15059. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15060. }
  15061. else {
  15062. minFilter = gl.LINEAR;
  15063. }
  15064. break;
  15065. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  15066. magFilter = gl.NEAREST;
  15067. if (generateMipMaps) {
  15068. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15069. }
  15070. else {
  15071. minFilter = gl.LINEAR;
  15072. }
  15073. break;
  15074. case Engine.TEXTURE_NEAREST_LINEAR:
  15075. magFilter = gl.NEAREST;
  15076. minFilter = gl.LINEAR;
  15077. break;
  15078. case Engine.TEXTURE_NEAREST_NEAREST:
  15079. magFilter = gl.NEAREST;
  15080. minFilter = gl.NEAREST;
  15081. break;
  15082. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  15083. magFilter = gl.LINEAR;
  15084. if (generateMipMaps) {
  15085. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15086. }
  15087. else {
  15088. minFilter = gl.NEAREST;
  15089. }
  15090. break;
  15091. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  15092. magFilter = gl.LINEAR;
  15093. if (generateMipMaps) {
  15094. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15095. }
  15096. else {
  15097. minFilter = gl.NEAREST;
  15098. }
  15099. break;
  15100. case Engine.TEXTURE_LINEAR_LINEAR:
  15101. magFilter = gl.LINEAR;
  15102. minFilter = gl.LINEAR;
  15103. break;
  15104. case Engine.TEXTURE_LINEAR_NEAREST:
  15105. magFilter = gl.LINEAR;
  15106. minFilter = gl.NEAREST;
  15107. break;
  15108. }
  15109. return {
  15110. min: minFilter,
  15111. mag: magFilter
  15112. };
  15113. };
  15114. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  15115. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15116. var img;
  15117. var onload = function () {
  15118. loadedImages[index] = img;
  15119. loadedImages._internalCount++;
  15120. if (scene) {
  15121. scene._removePendingData(img);
  15122. }
  15123. if (loadedImages._internalCount === 6) {
  15124. onfinish(loadedImages);
  15125. }
  15126. };
  15127. var onerror = function (message, exception) {
  15128. if (scene) {
  15129. scene._removePendingData(img);
  15130. }
  15131. if (onErrorCallBack) {
  15132. onErrorCallBack(message, exception);
  15133. }
  15134. };
  15135. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  15136. if (scene) {
  15137. scene._addPendingData(img);
  15138. }
  15139. };
  15140. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  15141. if (onError === void 0) { onError = null; }
  15142. var loadedImages = [];
  15143. loadedImages._internalCount = 0;
  15144. for (var index = 0; index < 6; index++) {
  15145. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  15146. }
  15147. };
  15148. ;
  15149. /** @hidden */
  15150. Engine.prototype._createTexture = function () {
  15151. var texture = this._gl.createTexture();
  15152. if (!texture) {
  15153. throw new Error("Unable to create texture");
  15154. }
  15155. return texture;
  15156. };
  15157. /**
  15158. * Usually called from BABYLON.Texture.ts.
  15159. * Passed information to create a WebGLTexture
  15160. * @param urlArg defines a value which contains one of the following:
  15161. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  15162. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  15163. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  15164. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  15165. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  15166. * @param scene needed for loading to the correct scene
  15167. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  15168. * @param onLoad optional callback to be called upon successful completion
  15169. * @param onError optional callback to be called upon failure
  15170. * @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
  15171. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  15172. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  15173. * @param forcedExtension defines the extension to use to pick the right loader
  15174. * @returns a InternalTexture for assignment back into BABYLON.Texture
  15175. */
  15176. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  15177. var _this = this;
  15178. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15179. if (onLoad === void 0) { onLoad = null; }
  15180. if (onError === void 0) { onError = null; }
  15181. if (buffer === void 0) { buffer = null; }
  15182. if (fallback === void 0) { fallback = null; }
  15183. if (format === void 0) { format = null; }
  15184. if (forcedExtension === void 0) { forcedExtension = null; }
  15185. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  15186. var fromData = url.substr(0, 5) === "data:";
  15187. var fromBlob = url.substr(0, 5) === "blob:";
  15188. var isBase64 = fromData && url.indexOf(";base64,") !== -1;
  15189. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  15190. // establish the file extension, if possible
  15191. var lastDot = url.lastIndexOf('.');
  15192. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  15193. var loader = null;
  15194. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15195. var availableLoader = _a[_i];
  15196. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  15197. loader = availableLoader;
  15198. break;
  15199. }
  15200. }
  15201. if (loader) {
  15202. url = loader.transformUrl(url, this._textureFormatInUse);
  15203. }
  15204. if (scene) {
  15205. scene._addPendingData(texture);
  15206. }
  15207. texture.url = url;
  15208. texture.generateMipMaps = !noMipmap;
  15209. texture.samplingMode = samplingMode;
  15210. texture.invertY = invertY;
  15211. if (!this._doNotHandleContextLost) {
  15212. // Keep a link to the buffer only if we plan to handle context lost
  15213. texture._buffer = buffer;
  15214. }
  15215. var onLoadObserver = null;
  15216. if (onLoad && !fallback) {
  15217. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  15218. }
  15219. if (!fallback)
  15220. this._internalTexturesCache.push(texture);
  15221. var onInternalError = function (message, exception) {
  15222. if (scene) {
  15223. scene._removePendingData(texture);
  15224. }
  15225. var customFallback = false;
  15226. if (loader) {
  15227. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  15228. if (fallbackUrl) {
  15229. // Add Back
  15230. customFallback = true;
  15231. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15232. }
  15233. }
  15234. if (!customFallback) {
  15235. if (onLoadObserver) {
  15236. texture.onLoadedObservable.remove(onLoadObserver);
  15237. }
  15238. if (BABYLON.Tools.UseFallbackTexture) {
  15239. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15240. }
  15241. }
  15242. if (onError) {
  15243. onError(message || "Unknown error", exception);
  15244. }
  15245. };
  15246. // processing for non-image formats
  15247. if (loader) {
  15248. var callback = function (data) {
  15249. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  15250. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  15251. done();
  15252. return false;
  15253. }, samplingMode);
  15254. });
  15255. };
  15256. if (!buffer) {
  15257. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  15258. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  15259. });
  15260. }
  15261. else {
  15262. callback(buffer);
  15263. }
  15264. }
  15265. else {
  15266. var onload = function (img) {
  15267. if (fromBlob && !_this._doNotHandleContextLost) {
  15268. // We need to store the image if we need to rebuild the texture
  15269. // in case of a webgl context lost
  15270. texture._buffer = img;
  15271. }
  15272. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  15273. var gl = _this._gl;
  15274. var isPot = (img.width === potWidth && img.height === potHeight);
  15275. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  15276. if (isPot) {
  15277. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15278. return false;
  15279. }
  15280. var maxTextureSize = _this._caps.maxTextureSize;
  15281. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  15282. _this._prepareWorkingCanvas();
  15283. if (!_this._workingCanvas || !_this._workingContext) {
  15284. return false;
  15285. }
  15286. _this._workingCanvas.width = potWidth;
  15287. _this._workingCanvas.height = potHeight;
  15288. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  15289. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15290. texture.width = potWidth;
  15291. texture.height = potHeight;
  15292. return false;
  15293. }
  15294. else {
  15295. // Using shaders when possible to rescale because canvas.drawImage is lossy
  15296. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15297. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  15298. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15299. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15300. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15301. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15302. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15303. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  15304. _this._releaseTexture(source_1);
  15305. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15306. continuationCallback();
  15307. });
  15308. }
  15309. return true;
  15310. }, samplingMode);
  15311. };
  15312. if (!fromData || isBase64) {
  15313. if (buffer instanceof HTMLImageElement) {
  15314. onload(buffer);
  15315. }
  15316. else {
  15317. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  15318. }
  15319. }
  15320. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  15321. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  15322. }
  15323. else {
  15324. onload(buffer);
  15325. }
  15326. }
  15327. return texture;
  15328. };
  15329. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  15330. var _this = this;
  15331. var rtt = this.createRenderTargetTexture({
  15332. width: destination.width,
  15333. height: destination.height,
  15334. }, {
  15335. generateMipMaps: false,
  15336. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  15337. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  15338. generateDepthBuffer: false,
  15339. generateStencilBuffer: false
  15340. });
  15341. if (!this._rescalePostProcess) {
  15342. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  15343. }
  15344. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  15345. _this._rescalePostProcess.onApply = function (effect) {
  15346. effect._bindTexture("textureSampler", source);
  15347. };
  15348. var hostingScene = scene;
  15349. if (!hostingScene) {
  15350. hostingScene = _this.scenes[_this.scenes.length - 1];
  15351. }
  15352. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  15353. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  15354. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  15355. _this.unBindFramebuffer(rtt);
  15356. _this._releaseTexture(rtt);
  15357. if (onComplete) {
  15358. onComplete();
  15359. }
  15360. });
  15361. };
  15362. /**
  15363. * Update a raw texture
  15364. * @param texture defines the texture to update
  15365. * @param data defines the data to store in the texture
  15366. * @param format defines the format of the data
  15367. * @param invertY defines if data must be stored with Y axis inverted
  15368. * @param compression defines the compression used (null by default)
  15369. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15370. */
  15371. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  15372. if (compression === void 0) { compression = null; }
  15373. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15374. if (!texture) {
  15375. return;
  15376. }
  15377. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  15378. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  15379. // babylon's internalFormat but gl's texImage2D format
  15380. var internalFormat = this._getInternalFormat(format);
  15381. var textureType = this._getWebGLTextureType(type);
  15382. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15383. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15384. if (!this._doNotHandleContextLost) {
  15385. texture._bufferView = data;
  15386. texture.format = format;
  15387. texture.type = type;
  15388. texture.invertY = invertY;
  15389. texture._compression = compression;
  15390. }
  15391. if (texture.width % 4 !== 0) {
  15392. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15393. }
  15394. if (compression && data) {
  15395. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  15396. }
  15397. else {
  15398. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  15399. }
  15400. if (texture.generateMipMaps) {
  15401. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15402. }
  15403. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15404. // this.resetTextureCache();
  15405. texture.isReady = true;
  15406. };
  15407. /**
  15408. * Creates a raw texture
  15409. * @param data defines the data to store in the texture
  15410. * @param width defines the width of the texture
  15411. * @param height defines the height of the texture
  15412. * @param format defines the format of the data
  15413. * @param generateMipMaps defines if the engine should generate the mip levels
  15414. * @param invertY defines if data must be stored with Y axis inverted
  15415. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15416. * @param compression defines the compression used (null by default)
  15417. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15418. * @returns the raw texture inside an InternalTexture
  15419. */
  15420. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  15421. if (compression === void 0) { compression = null; }
  15422. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15423. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  15424. texture.baseWidth = width;
  15425. texture.baseHeight = height;
  15426. texture.width = width;
  15427. texture.height = height;
  15428. texture.format = format;
  15429. texture.generateMipMaps = generateMipMaps;
  15430. texture.samplingMode = samplingMode;
  15431. texture.invertY = invertY;
  15432. texture._compression = compression;
  15433. texture.type = type;
  15434. if (!this._doNotHandleContextLost) {
  15435. texture._bufferView = data;
  15436. }
  15437. this.updateRawTexture(texture, data, format, invertY, compression, type);
  15438. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15439. // Filters
  15440. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15441. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15442. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15443. if (generateMipMaps) {
  15444. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15445. }
  15446. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15447. this._internalTexturesCache.push(texture);
  15448. return texture;
  15449. };
  15450. /** @hidden */
  15451. Engine.prototype._unpackFlipY = function (value) {
  15452. if (this._unpackFlipYCached !== value) {
  15453. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  15454. if (this.enableUnpackFlipYCached) {
  15455. this._unpackFlipYCached = value;
  15456. }
  15457. }
  15458. };
  15459. /** @hidden */
  15460. Engine.prototype._getUnpackAlignement = function () {
  15461. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  15462. };
  15463. /**
  15464. * Creates a dynamic texture
  15465. * @param width defines the width of the texture
  15466. * @param height defines the height of the texture
  15467. * @param generateMipMaps defines if the engine should generate the mip levels
  15468. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15469. * @returns the dynamic texture inside an InternalTexture
  15470. */
  15471. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  15472. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  15473. texture.baseWidth = width;
  15474. texture.baseHeight = height;
  15475. if (generateMipMaps) {
  15476. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  15477. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  15478. }
  15479. // this.resetTextureCache();
  15480. texture.width = width;
  15481. texture.height = height;
  15482. texture.isReady = false;
  15483. texture.generateMipMaps = generateMipMaps;
  15484. texture.samplingMode = samplingMode;
  15485. this.updateTextureSamplingMode(samplingMode, texture);
  15486. this._internalTexturesCache.push(texture);
  15487. return texture;
  15488. };
  15489. /**
  15490. * Update the sampling mode of a given texture
  15491. * @param samplingMode defines the required sampling mode
  15492. * @param texture defines the texture to update
  15493. */
  15494. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  15495. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  15496. if (texture.isCube) {
  15497. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15498. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15499. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15500. }
  15501. else if (texture.is3D) {
  15502. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15503. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15504. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15505. }
  15506. else {
  15507. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15508. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15509. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15510. }
  15511. texture.samplingMode = samplingMode;
  15512. };
  15513. /**
  15514. * Update the content of a dynamic texture
  15515. * @param texture defines the texture to update
  15516. * @param canvas defines the canvas containing the source
  15517. * @param invertY defines if data must be stored with Y axis inverted
  15518. * @param premulAlpha defines if alpha is stored as premultiplied
  15519. * @param format defines the format of the data
  15520. */
  15521. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  15522. if (premulAlpha === void 0) { premulAlpha = false; }
  15523. if (!texture) {
  15524. return;
  15525. }
  15526. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15527. this._unpackFlipY(invertY);
  15528. if (premulAlpha) {
  15529. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  15530. }
  15531. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  15532. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  15533. if (texture.generateMipMaps) {
  15534. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15535. }
  15536. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15537. if (premulAlpha) {
  15538. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15539. }
  15540. texture.isReady = true;
  15541. };
  15542. /**
  15543. * Update a video texture
  15544. * @param texture defines the texture to update
  15545. * @param video defines the video element to use
  15546. * @param invertY defines if data must be stored with Y axis inverted
  15547. */
  15548. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15549. if (!texture || texture._isDisabled) {
  15550. return;
  15551. }
  15552. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15553. this._unpackFlipY(!invertY); // Video are upside down by default
  15554. try {
  15555. // Testing video texture support
  15556. if (this._videoTextureSupported === undefined) {
  15557. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15558. if (this._gl.getError() !== 0) {
  15559. this._videoTextureSupported = false;
  15560. }
  15561. else {
  15562. this._videoTextureSupported = true;
  15563. }
  15564. }
  15565. // Copy video through the current working canvas if video texture is not supported
  15566. if (!this._videoTextureSupported) {
  15567. if (!texture._workingCanvas) {
  15568. texture._workingCanvas = document.createElement("canvas");
  15569. var context = texture._workingCanvas.getContext("2d");
  15570. if (!context) {
  15571. throw new Error("Unable to get 2d context");
  15572. }
  15573. texture._workingContext = context;
  15574. texture._workingCanvas.width = texture.width;
  15575. texture._workingCanvas.height = texture.height;
  15576. }
  15577. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15578. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15579. }
  15580. else {
  15581. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15582. }
  15583. if (texture.generateMipMaps) {
  15584. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15585. }
  15586. if (!wasPreviouslyBound) {
  15587. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15588. }
  15589. // this.resetTextureCache();
  15590. texture.isReady = true;
  15591. }
  15592. catch (ex) {
  15593. // Something unexpected
  15594. // Let's disable the texture
  15595. texture._isDisabled = true;
  15596. }
  15597. };
  15598. /**
  15599. * Updates a depth texture Comparison Mode and Function.
  15600. * If the comparison Function is equal to 0, the mode will be set to none.
  15601. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15602. * @param texture The texture to set the comparison function for
  15603. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15604. */
  15605. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15606. if (this.webGLVersion === 1) {
  15607. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15608. return;
  15609. }
  15610. var gl = this._gl;
  15611. if (texture.isCube) {
  15612. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15613. if (comparisonFunction === 0) {
  15614. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15615. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15616. }
  15617. else {
  15618. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15619. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15620. }
  15621. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15622. }
  15623. else {
  15624. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15625. if (comparisonFunction === 0) {
  15626. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15627. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15628. }
  15629. else {
  15630. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15631. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15632. }
  15633. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15634. }
  15635. texture._comparisonFunction = comparisonFunction;
  15636. };
  15637. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15638. var width = size.width || size;
  15639. var height = size.height || size;
  15640. internalTexture.baseWidth = width;
  15641. internalTexture.baseHeight = height;
  15642. internalTexture.width = width;
  15643. internalTexture.height = height;
  15644. internalTexture.isReady = true;
  15645. internalTexture.samples = 1;
  15646. internalTexture.generateMipMaps = false;
  15647. internalTexture._generateDepthBuffer = true;
  15648. internalTexture._generateStencilBuffer = generateStencil;
  15649. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15650. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15651. internalTexture._comparisonFunction = comparisonFunction;
  15652. var gl = this._gl;
  15653. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15654. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  15655. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15656. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15657. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15658. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15659. if (comparisonFunction === 0) {
  15660. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15661. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15662. }
  15663. else {
  15664. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15665. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15666. }
  15667. };
  15668. /**
  15669. * Creates a depth stencil texture.
  15670. * This is only available in WebGL 2 or with the depth texture extension available.
  15671. * @param size The size of face edge in the texture.
  15672. * @param options The options defining the texture.
  15673. * @returns The texture
  15674. */
  15675. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15676. if (options.isCube) {
  15677. var width = size.width || size;
  15678. return this._createDepthStencilCubeTexture(width, options);
  15679. }
  15680. else {
  15681. return this._createDepthStencilTexture(size, options);
  15682. }
  15683. };
  15684. /**
  15685. * Creates a depth stencil texture.
  15686. * This is only available in WebGL 2 or with the depth texture extension available.
  15687. * @param size The size of face edge in the texture.
  15688. * @param options The options defining the texture.
  15689. * @returns The texture
  15690. */
  15691. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15692. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15693. if (!this._caps.depthTextureExtension) {
  15694. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15695. return internalTexture;
  15696. }
  15697. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15698. var gl = this._gl;
  15699. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15700. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15701. if (this.webGLVersion > 1) {
  15702. if (internalOptions.generateStencil) {
  15703. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15704. }
  15705. else {
  15706. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15707. }
  15708. }
  15709. else {
  15710. if (internalOptions.generateStencil) {
  15711. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15712. }
  15713. else {
  15714. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15715. }
  15716. }
  15717. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15718. return internalTexture;
  15719. };
  15720. /**
  15721. * Creates a depth stencil cube texture.
  15722. * This is only available in WebGL 2.
  15723. * @param size The size of face edge in the cube texture.
  15724. * @param options The options defining the cube texture.
  15725. * @returns The cube texture
  15726. */
  15727. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15728. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15729. internalTexture.isCube = true;
  15730. if (this.webGLVersion === 1) {
  15731. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15732. return internalTexture;
  15733. }
  15734. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15735. var gl = this._gl;
  15736. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15737. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15738. // Create the depth/stencil buffer
  15739. for (var face = 0; face < 6; face++) {
  15740. if (internalOptions.generateStencil) {
  15741. 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);
  15742. }
  15743. else {
  15744. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15745. }
  15746. }
  15747. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15748. return internalTexture;
  15749. };
  15750. /**
  15751. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15752. * @param renderTarget The render target to set the frame buffer for
  15753. */
  15754. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15755. // Create the framebuffer
  15756. var internalTexture = renderTarget.getInternalTexture();
  15757. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15758. return;
  15759. }
  15760. var gl = this._gl;
  15761. var depthStencilTexture = renderTarget.depthStencilTexture;
  15762. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15763. if (depthStencilTexture.isCube) {
  15764. if (depthStencilTexture._generateStencilBuffer) {
  15765. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15766. }
  15767. else {
  15768. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15769. }
  15770. }
  15771. else {
  15772. if (depthStencilTexture._generateStencilBuffer) {
  15773. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15774. }
  15775. else {
  15776. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15777. }
  15778. }
  15779. this.bindUnboundFramebuffer(null);
  15780. };
  15781. /**
  15782. * Creates a new render target texture
  15783. * @param size defines the size of the texture
  15784. * @param options defines the options used to create the texture
  15785. * @returns a new render target texture stored in an InternalTexture
  15786. */
  15787. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15788. var fullOptions = new RenderTargetCreationOptions();
  15789. if (options !== undefined && typeof options === "object") {
  15790. fullOptions.generateMipMaps = options.generateMipMaps;
  15791. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15792. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15793. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15794. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15795. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15796. }
  15797. else {
  15798. fullOptions.generateMipMaps = options;
  15799. fullOptions.generateDepthBuffer = true;
  15800. fullOptions.generateStencilBuffer = false;
  15801. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15802. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15803. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15804. }
  15805. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15806. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15807. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15808. }
  15809. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15810. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15811. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15812. }
  15813. var gl = this._gl;
  15814. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15815. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15816. var width = size.width || size;
  15817. var height = size.height || size;
  15818. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15819. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15820. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15821. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15822. }
  15823. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15824. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15825. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15826. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15827. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15828. // Create the framebuffer
  15829. var currentFrameBuffer = this._currentFramebuffer;
  15830. var framebuffer = gl.createFramebuffer();
  15831. this.bindUnboundFramebuffer(framebuffer);
  15832. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15833. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15834. if (fullOptions.generateMipMaps) {
  15835. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15836. }
  15837. // Unbind
  15838. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15839. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15840. this.bindUnboundFramebuffer(currentFrameBuffer);
  15841. texture._framebuffer = framebuffer;
  15842. texture.baseWidth = width;
  15843. texture.baseHeight = height;
  15844. texture.width = width;
  15845. texture.height = height;
  15846. texture.isReady = true;
  15847. texture.samples = 1;
  15848. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15849. texture.samplingMode = fullOptions.samplingMode;
  15850. texture.type = fullOptions.type;
  15851. texture.format = fullOptions.format;
  15852. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15853. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15854. // this.resetTextureCache();
  15855. this._internalTexturesCache.push(texture);
  15856. return texture;
  15857. };
  15858. /**
  15859. * Create a multi render target texture
  15860. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15861. * @param size defines the size of the texture
  15862. * @param options defines the creation options
  15863. * @returns the cube texture as an InternalTexture
  15864. */
  15865. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15866. var generateMipMaps = false;
  15867. var generateDepthBuffer = true;
  15868. var generateStencilBuffer = false;
  15869. var generateDepthTexture = false;
  15870. var textureCount = 1;
  15871. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15872. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15873. var types = new Array();
  15874. var samplingModes = new Array();
  15875. if (options !== undefined) {
  15876. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15877. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15878. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15879. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15880. textureCount = options.textureCount || 1;
  15881. if (options.types) {
  15882. types = options.types;
  15883. }
  15884. if (options.samplingModes) {
  15885. samplingModes = options.samplingModes;
  15886. }
  15887. }
  15888. var gl = this._gl;
  15889. // Create the framebuffer
  15890. var framebuffer = gl.createFramebuffer();
  15891. this.bindUnboundFramebuffer(framebuffer);
  15892. var width = size.width || size;
  15893. var height = size.height || size;
  15894. var textures = [];
  15895. var attachments = [];
  15896. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15897. for (var i = 0; i < textureCount; i++) {
  15898. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15899. var type = types[i] || defaultType;
  15900. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15901. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15902. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15903. }
  15904. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15905. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15906. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15907. }
  15908. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15909. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15910. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15911. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15912. }
  15913. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15914. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15915. textures.push(texture);
  15916. attachments.push(attachment);
  15917. gl.activeTexture(gl["TEXTURE" + i]);
  15918. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15919. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15920. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15921. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15922. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15923. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15924. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15925. if (generateMipMaps) {
  15926. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15927. }
  15928. // Unbind
  15929. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15930. texture._framebuffer = framebuffer;
  15931. texture._depthStencilBuffer = depthStencilBuffer;
  15932. texture.baseWidth = width;
  15933. texture.baseHeight = height;
  15934. texture.width = width;
  15935. texture.height = height;
  15936. texture.isReady = true;
  15937. texture.samples = 1;
  15938. texture.generateMipMaps = generateMipMaps;
  15939. texture.samplingMode = samplingMode;
  15940. texture.type = type;
  15941. texture._generateDepthBuffer = generateDepthBuffer;
  15942. texture._generateStencilBuffer = generateStencilBuffer;
  15943. texture._attachments = attachments;
  15944. this._internalTexturesCache.push(texture);
  15945. }
  15946. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15947. // Depth texture
  15948. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15949. gl.activeTexture(gl.TEXTURE0);
  15950. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15951. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15952. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15953. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15954. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15955. 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);
  15956. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15957. depthTexture._framebuffer = framebuffer;
  15958. depthTexture.baseWidth = width;
  15959. depthTexture.baseHeight = height;
  15960. depthTexture.width = width;
  15961. depthTexture.height = height;
  15962. depthTexture.isReady = true;
  15963. depthTexture.samples = 1;
  15964. depthTexture.generateMipMaps = generateMipMaps;
  15965. depthTexture.samplingMode = gl.NEAREST;
  15966. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15967. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15968. textures.push(depthTexture);
  15969. this._internalTexturesCache.push(depthTexture);
  15970. }
  15971. gl.drawBuffers(attachments);
  15972. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15973. this.bindUnboundFramebuffer(null);
  15974. this.resetTextureCache();
  15975. return textures;
  15976. };
  15977. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15978. if (samples === void 0) { samples = 1; }
  15979. var depthStencilBuffer = null;
  15980. var gl = this._gl;
  15981. // Create the depth/stencil buffer
  15982. if (generateStencilBuffer) {
  15983. depthStencilBuffer = gl.createRenderbuffer();
  15984. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15985. if (samples > 1) {
  15986. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15987. }
  15988. else {
  15989. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15990. }
  15991. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15992. }
  15993. else if (generateDepthBuffer) {
  15994. depthStencilBuffer = gl.createRenderbuffer();
  15995. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15996. if (samples > 1) {
  15997. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15998. }
  15999. else {
  16000. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  16001. }
  16002. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  16003. }
  16004. return depthStencilBuffer;
  16005. };
  16006. /**
  16007. * Updates the sample count of a render target texture
  16008. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16009. * @param texture defines the texture to update
  16010. * @param samples defines the sample count to set
  16011. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16012. */
  16013. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  16014. if (this.webGLVersion < 2 || !texture) {
  16015. return 1;
  16016. }
  16017. if (texture.samples === samples) {
  16018. return samples;
  16019. }
  16020. var gl = this._gl;
  16021. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16022. // Dispose previous render buffers
  16023. if (texture._depthStencilBuffer) {
  16024. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16025. texture._depthStencilBuffer = null;
  16026. }
  16027. if (texture._MSAAFramebuffer) {
  16028. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16029. texture._MSAAFramebuffer = null;
  16030. }
  16031. if (texture._MSAARenderBuffer) {
  16032. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16033. texture._MSAARenderBuffer = null;
  16034. }
  16035. if (samples > 1) {
  16036. var framebuffer = gl.createFramebuffer();
  16037. if (!framebuffer) {
  16038. throw new Error("Unable to create multi sampled framebuffer");
  16039. }
  16040. texture._MSAAFramebuffer = framebuffer;
  16041. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  16042. var colorRenderbuffer = gl.createRenderbuffer();
  16043. if (!colorRenderbuffer) {
  16044. throw new Error("Unable to create multi sampled framebuffer");
  16045. }
  16046. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16047. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16048. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  16049. texture._MSAARenderBuffer = colorRenderbuffer;
  16050. }
  16051. else {
  16052. this.bindUnboundFramebuffer(texture._framebuffer);
  16053. }
  16054. texture.samples = samples;
  16055. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  16056. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16057. this.bindUnboundFramebuffer(null);
  16058. return samples;
  16059. };
  16060. /**
  16061. * Update the sample count for a given multiple render target texture
  16062. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16063. * @param textures defines the textures to update
  16064. * @param samples defines the sample count to set
  16065. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16066. */
  16067. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  16068. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  16069. return 1;
  16070. }
  16071. if (textures[0].samples === samples) {
  16072. return samples;
  16073. }
  16074. var gl = this._gl;
  16075. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16076. // Dispose previous render buffers
  16077. if (textures[0]._depthStencilBuffer) {
  16078. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  16079. textures[0]._depthStencilBuffer = null;
  16080. }
  16081. if (textures[0]._MSAAFramebuffer) {
  16082. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  16083. textures[0]._MSAAFramebuffer = null;
  16084. }
  16085. for (var i = 0; i < textures.length; i++) {
  16086. if (textures[i]._MSAARenderBuffer) {
  16087. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  16088. textures[i]._MSAARenderBuffer = null;
  16089. }
  16090. }
  16091. if (samples > 1) {
  16092. var framebuffer = gl.createFramebuffer();
  16093. if (!framebuffer) {
  16094. throw new Error("Unable to create multi sampled framebuffer");
  16095. }
  16096. this.bindUnboundFramebuffer(framebuffer);
  16097. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  16098. var attachments = [];
  16099. for (var i = 0; i < textures.length; i++) {
  16100. var texture = textures[i];
  16101. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  16102. var colorRenderbuffer = gl.createRenderbuffer();
  16103. if (!colorRenderbuffer) {
  16104. throw new Error("Unable to create multi sampled framebuffer");
  16105. }
  16106. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16107. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16108. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  16109. texture._MSAAFramebuffer = framebuffer;
  16110. texture._MSAARenderBuffer = colorRenderbuffer;
  16111. texture.samples = samples;
  16112. texture._depthStencilBuffer = depthStencilBuffer;
  16113. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16114. attachments.push(attachment);
  16115. }
  16116. gl.drawBuffers(attachments);
  16117. }
  16118. else {
  16119. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  16120. }
  16121. this.bindUnboundFramebuffer(null);
  16122. return samples;
  16123. };
  16124. /** @hidden */
  16125. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  16126. if (faceIndex === void 0) { faceIndex = 0; }
  16127. if (lod === void 0) { lod = 0; }
  16128. var gl = this._gl;
  16129. var target = gl.TEXTURE_2D;
  16130. if (texture.isCube) {
  16131. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16132. }
  16133. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  16134. };
  16135. /** @hidden */
  16136. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  16137. if (faceIndex === void 0) { faceIndex = 0; }
  16138. if (lod === void 0) { lod = 0; }
  16139. var gl = this._gl;
  16140. var textureType = this._getWebGLTextureType(texture.type);
  16141. var format = this._getInternalFormat(texture.format);
  16142. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16143. this._unpackFlipY(texture.invertY);
  16144. var target = gl.TEXTURE_2D;
  16145. if (texture.isCube) {
  16146. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16147. }
  16148. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  16149. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  16150. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  16151. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  16152. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  16153. };
  16154. /** @hidden */
  16155. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  16156. if (faceIndex === void 0) { faceIndex = 0; }
  16157. if (lod === void 0) { lod = 0; }
  16158. var gl = this._gl;
  16159. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16160. this._bindTextureDirectly(bindTarget, texture, true);
  16161. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  16162. this._bindTextureDirectly(bindTarget, null, true);
  16163. };
  16164. /** @hidden */
  16165. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  16166. if (faceIndex === void 0) { faceIndex = 0; }
  16167. if (lod === void 0) { lod = 0; }
  16168. var gl = this._gl;
  16169. var textureType = this._getWebGLTextureType(texture.type);
  16170. var format = this._getInternalFormat(texture.format);
  16171. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16172. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16173. this._bindTextureDirectly(bindTarget, texture, true);
  16174. this._unpackFlipY(texture.invertY);
  16175. var target = gl.TEXTURE_2D;
  16176. if (texture.isCube) {
  16177. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16178. }
  16179. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  16180. this._bindTextureDirectly(bindTarget, null, true);
  16181. };
  16182. /**
  16183. * Creates a new render target cube texture
  16184. * @param size defines the size of the texture
  16185. * @param options defines the options used to create the texture
  16186. * @returns a new render target cube texture stored in an InternalTexture
  16187. */
  16188. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  16189. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  16190. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  16191. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16192. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16193. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16194. }
  16195. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16196. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16197. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16198. }
  16199. var gl = this._gl;
  16200. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  16201. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16202. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  16203. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16204. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16205. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  16206. }
  16207. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16208. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16209. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16210. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16211. for (var face = 0; face < 6; face++) {
  16212. 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);
  16213. }
  16214. // Create the framebuffer
  16215. var framebuffer = gl.createFramebuffer();
  16216. this.bindUnboundFramebuffer(framebuffer);
  16217. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  16218. // MipMaps
  16219. if (fullOptions.generateMipMaps) {
  16220. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16221. }
  16222. // Unbind
  16223. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16224. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16225. this.bindUnboundFramebuffer(null);
  16226. texture._framebuffer = framebuffer;
  16227. texture.width = size;
  16228. texture.height = size;
  16229. texture.isReady = true;
  16230. texture.isCube = true;
  16231. texture.samples = 1;
  16232. texture.generateMipMaps = fullOptions.generateMipMaps;
  16233. texture.samplingMode = fullOptions.samplingMode;
  16234. texture.type = fullOptions.type;
  16235. texture.format = fullOptions.format;
  16236. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  16237. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  16238. this._internalTexturesCache.push(texture);
  16239. return texture;
  16240. };
  16241. /**
  16242. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  16243. * @param rootUrl defines the url where the file to load is located
  16244. * @param scene defines the current scene
  16245. * @param lodScale defines scale to apply to the mip map selection
  16246. * @param lodOffset defines offset to apply to the mip map selection
  16247. * @param onLoad defines an optional callback raised when the texture is loaded
  16248. * @param onError defines an optional callback raised if there is an issue to load the texture
  16249. * @param format defines the format of the data
  16250. * @param forcedExtension defines the extension to use to pick the right loader
  16251. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  16252. * @returns the cube texture as an InternalTexture
  16253. */
  16254. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  16255. var _this = this;
  16256. if (onLoad === void 0) { onLoad = null; }
  16257. if (onError === void 0) { onError = null; }
  16258. if (forcedExtension === void 0) { forcedExtension = null; }
  16259. if (createPolynomials === void 0) { createPolynomials = true; }
  16260. var callback = function (loadData) {
  16261. if (!loadData) {
  16262. if (onLoad) {
  16263. onLoad(null);
  16264. }
  16265. return;
  16266. }
  16267. var texture = loadData.texture;
  16268. if (!createPolynomials) {
  16269. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  16270. }
  16271. else if (loadData.info.sphericalPolynomial) {
  16272. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  16273. }
  16274. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  16275. if (_this._caps.textureLOD) {
  16276. // Do not add extra process if texture lod is supported.
  16277. if (onLoad) {
  16278. onLoad(texture);
  16279. }
  16280. return;
  16281. }
  16282. var mipSlices = 3;
  16283. var gl = _this._gl;
  16284. var width = loadData.width;
  16285. if (!width) {
  16286. return;
  16287. }
  16288. var textures = [];
  16289. for (var i = 0; i < mipSlices; i++) {
  16290. //compute LOD from even spacing in smoothness (matching shader calculation)
  16291. var smoothness = i / (mipSlices - 1);
  16292. var roughness = 1 - smoothness;
  16293. var minLODIndex = lodOffset; // roughness = 0
  16294. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  16295. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  16296. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  16297. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  16298. glTextureFromLod.type = texture.type;
  16299. glTextureFromLod.format = texture.format;
  16300. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  16301. glTextureFromLod.height = glTextureFromLod.width;
  16302. glTextureFromLod.isCube = true;
  16303. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  16304. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16305. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  16306. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16307. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16308. if (loadData.isDDS) {
  16309. var info = loadData.info;
  16310. var data = loadData.data;
  16311. _this._unpackFlipY(info.isCompressed);
  16312. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  16313. }
  16314. else {
  16315. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  16316. }
  16317. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16318. // Wrap in a base texture for easy binding.
  16319. var lodTexture = new BABYLON.BaseTexture(scene);
  16320. lodTexture.isCube = true;
  16321. lodTexture._texture = glTextureFromLod;
  16322. glTextureFromLod.isReady = true;
  16323. textures.push(lodTexture);
  16324. }
  16325. texture._lodTextureHigh = textures[2];
  16326. texture._lodTextureMid = textures[1];
  16327. texture._lodTextureLow = textures[0];
  16328. if (onLoad) {
  16329. onLoad(texture);
  16330. }
  16331. };
  16332. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  16333. };
  16334. /**
  16335. * Creates a cube texture
  16336. * @param rootUrl defines the url where the files to load is located
  16337. * @param scene defines the current scene
  16338. * @param files defines the list of files to load (1 per face)
  16339. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  16340. * @param onLoad defines an optional callback raised when the texture is loaded
  16341. * @param onError defines an optional callback raised if there is an issue to load the texture
  16342. * @param format defines the format of the data
  16343. * @param forcedExtension defines the extension to use to pick the right loader
  16344. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  16345. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  16346. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  16347. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  16348. * @returns the cube texture as an InternalTexture
  16349. */
  16350. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  16351. var _this = this;
  16352. if (onLoad === void 0) { onLoad = null; }
  16353. if (onError === void 0) { onError = null; }
  16354. if (forcedExtension === void 0) { forcedExtension = null; }
  16355. if (createPolynomials === void 0) { createPolynomials = false; }
  16356. if (lodScale === void 0) { lodScale = 0; }
  16357. if (lodOffset === void 0) { lodOffset = 0; }
  16358. if (fallback === void 0) { fallback = null; }
  16359. var gl = this._gl;
  16360. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  16361. texture.isCube = true;
  16362. texture.url = rootUrl;
  16363. texture.generateMipMaps = !noMipmap;
  16364. texture._lodGenerationScale = lodScale;
  16365. texture._lodGenerationOffset = lodOffset;
  16366. if (!this._doNotHandleContextLost) {
  16367. texture._extension = forcedExtension;
  16368. texture._files = files;
  16369. }
  16370. var lastDot = rootUrl.lastIndexOf('.');
  16371. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  16372. var loader = null;
  16373. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  16374. var availableLoader = _a[_i];
  16375. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  16376. loader = availableLoader;
  16377. break;
  16378. }
  16379. }
  16380. var onInternalError = function (request, exception) {
  16381. if (loader) {
  16382. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  16383. if (fallbackUrl) {
  16384. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  16385. }
  16386. }
  16387. if (onError && request) {
  16388. onError(request.status + " " + request.statusText, exception);
  16389. }
  16390. };
  16391. if (loader) {
  16392. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  16393. var onloaddata = function (data) {
  16394. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16395. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  16396. };
  16397. if (files && files.length === 6) {
  16398. if (loader.supportCascades) {
  16399. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  16400. }
  16401. else if (onError) {
  16402. onError("Textures type does not support cascades.");
  16403. }
  16404. }
  16405. else {
  16406. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  16407. }
  16408. }
  16409. else {
  16410. if (!files) {
  16411. throw new Error("Cannot load cubemap because files were not defined");
  16412. }
  16413. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  16414. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  16415. var height = width;
  16416. _this._prepareWorkingCanvas();
  16417. if (!_this._workingCanvas || !_this._workingContext) {
  16418. return;
  16419. }
  16420. _this._workingCanvas.width = width;
  16421. _this._workingCanvas.height = height;
  16422. var faces = [
  16423. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  16424. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  16425. ];
  16426. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16427. _this._unpackFlipY(false);
  16428. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  16429. for (var index = 0; index < faces.length; index++) {
  16430. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  16431. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  16432. }
  16433. if (!noMipmap) {
  16434. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16435. }
  16436. _this._setCubeMapTextureParams(!noMipmap);
  16437. texture.width = width;
  16438. texture.height = height;
  16439. texture.isReady = true;
  16440. if (format) {
  16441. texture.format = format;
  16442. }
  16443. texture.onLoadedObservable.notifyObservers(texture);
  16444. texture.onLoadedObservable.clear();
  16445. if (onLoad) {
  16446. onLoad();
  16447. }
  16448. }, files, onError);
  16449. }
  16450. this._internalTexturesCache.push(texture);
  16451. return texture;
  16452. };
  16453. /**
  16454. * @hidden
  16455. */
  16456. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  16457. var gl = this._gl;
  16458. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16459. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  16460. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16461. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16462. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16463. // this.resetTextureCache();
  16464. };
  16465. /**
  16466. * Update a raw cube texture
  16467. * @param texture defines the texture to udpdate
  16468. * @param data defines the data to store
  16469. * @param format defines the data format
  16470. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  16471. * @param invertY defines if data must be stored with Y axis inverted
  16472. * @param compression defines the compression used (null by default)
  16473. * @param level defines which level of the texture to update
  16474. */
  16475. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  16476. if (compression === void 0) { compression = null; }
  16477. if (level === void 0) { level = 0; }
  16478. texture._bufferViewArray = data;
  16479. texture.format = format;
  16480. texture.type = type;
  16481. texture.invertY = invertY;
  16482. texture._compression = compression;
  16483. var gl = this._gl;
  16484. var textureType = this._getWebGLTextureType(type);
  16485. var internalFormat = this._getInternalFormat(format);
  16486. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  16487. var needConversion = false;
  16488. if (internalFormat === gl.RGB) {
  16489. internalFormat = gl.RGBA;
  16490. needConversion = true;
  16491. }
  16492. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16493. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16494. if (texture.width % 4 !== 0) {
  16495. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  16496. }
  16497. // Data are known to be in +X +Y +Z -X -Y -Z
  16498. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16499. var faceData = data[faceIndex];
  16500. if (compression) {
  16501. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  16502. }
  16503. else {
  16504. if (needConversion) {
  16505. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  16506. }
  16507. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  16508. }
  16509. }
  16510. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16511. if (isPot && texture.generateMipMaps && level === 0) {
  16512. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16513. }
  16514. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16515. // this.resetTextureCache();
  16516. texture.isReady = true;
  16517. };
  16518. /**
  16519. * Creates a new raw cube texture
  16520. * @param data defines the array of data to use to create each face
  16521. * @param size defines the size of the textures
  16522. * @param format defines the format of the data
  16523. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16524. * @param generateMipMaps defines if the engine should generate the mip levels
  16525. * @param invertY defines if data must be stored with Y axis inverted
  16526. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16527. * @param compression defines the compression used (null by default)
  16528. * @returns the cube texture as an InternalTexture
  16529. */
  16530. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16531. if (compression === void 0) { compression = null; }
  16532. var gl = this._gl;
  16533. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16534. texture.isCube = true;
  16535. texture.format = format;
  16536. texture.type = type;
  16537. if (!this._doNotHandleContextLost) {
  16538. texture._bufferViewArray = data;
  16539. }
  16540. var textureType = this._getWebGLTextureType(type);
  16541. var internalFormat = this._getInternalFormat(format);
  16542. if (internalFormat === gl.RGB) {
  16543. internalFormat = gl.RGBA;
  16544. }
  16545. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  16546. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16547. generateMipMaps = false;
  16548. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16549. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16550. }
  16551. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16552. generateMipMaps = false;
  16553. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16554. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16555. }
  16556. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  16557. generateMipMaps = false;
  16558. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  16559. }
  16560. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  16561. generateMipMaps = false;
  16562. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  16563. }
  16564. var width = size;
  16565. var height = width;
  16566. texture.width = width;
  16567. texture.height = height;
  16568. // Double check on POT to generate Mips.
  16569. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16570. if (!isPot) {
  16571. generateMipMaps = false;
  16572. }
  16573. // Upload data if needed. The texture won't be ready until then.
  16574. if (data) {
  16575. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16576. }
  16577. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16578. // Filters
  16579. if (data && generateMipMaps) {
  16580. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16581. }
  16582. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16583. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16584. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16585. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16586. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16587. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16588. texture.generateMipMaps = generateMipMaps;
  16589. return texture;
  16590. };
  16591. /**
  16592. * Creates a new raw cube texture from a specified url
  16593. * @param url defines the url where the data is located
  16594. * @param scene defines the current scene
  16595. * @param size defines the size of the textures
  16596. * @param format defines the format of the data
  16597. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16598. * @param noMipmap defines if the engine should avoid generating the mip levels
  16599. * @param callback defines a callback used to extract texture data from loaded data
  16600. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16601. * @param onLoad defines a callback called when texture is loaded
  16602. * @param onError defines a callback called if there is an error
  16603. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16604. * @param invertY defines if data must be stored with Y axis inverted
  16605. * @returns the cube texture as an InternalTexture
  16606. */
  16607. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16608. var _this = this;
  16609. if (onLoad === void 0) { onLoad = null; }
  16610. if (onError === void 0) { onError = null; }
  16611. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16612. if (invertY === void 0) { invertY = false; }
  16613. var gl = this._gl;
  16614. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16615. scene._addPendingData(texture);
  16616. texture.url = url;
  16617. this._internalTexturesCache.push(texture);
  16618. var onerror = function (request, exception) {
  16619. scene._removePendingData(texture);
  16620. if (onError && request) {
  16621. onError(request.status + " " + request.statusText, exception);
  16622. }
  16623. };
  16624. var internalCallback = function (data) {
  16625. var width = texture.width;
  16626. var faceDataArrays = callback(data);
  16627. if (!faceDataArrays) {
  16628. return;
  16629. }
  16630. if (mipmapGenerator) {
  16631. var textureType = _this._getWebGLTextureType(type);
  16632. var internalFormat = _this._getInternalFormat(format);
  16633. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16634. var needConversion = false;
  16635. if (internalFormat === gl.RGB) {
  16636. internalFormat = gl.RGBA;
  16637. needConversion = true;
  16638. }
  16639. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16640. _this._unpackFlipY(false);
  16641. var mipData = mipmapGenerator(faceDataArrays);
  16642. for (var level = 0; level < mipData.length; level++) {
  16643. var mipSize = width >> level;
  16644. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16645. var mipFaceData = mipData[level][faceIndex];
  16646. if (needConversion) {
  16647. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16648. }
  16649. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16650. }
  16651. }
  16652. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16653. }
  16654. else {
  16655. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16656. }
  16657. texture.isReady = true;
  16658. // this.resetTextureCache();
  16659. scene._removePendingData(texture);
  16660. if (onLoad) {
  16661. onLoad();
  16662. }
  16663. };
  16664. this._loadFile(url, function (data) {
  16665. internalCallback(data);
  16666. }, undefined, scene.database, true, onerror);
  16667. return texture;
  16668. };
  16669. ;
  16670. /**
  16671. * Update a raw 3D texture
  16672. * @param texture defines the texture to update
  16673. * @param data defines the data to store
  16674. * @param format defines the data format
  16675. * @param invertY defines if data must be stored with Y axis inverted
  16676. * @param compression defines the used compression (can be null)
  16677. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16678. */
  16679. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16680. if (compression === void 0) { compression = null; }
  16681. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16682. var internalType = this._getWebGLTextureType(textureType);
  16683. var internalFormat = this._getInternalFormat(format);
  16684. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16685. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16686. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16687. if (!this._doNotHandleContextLost) {
  16688. texture._bufferView = data;
  16689. texture.format = format;
  16690. texture.invertY = invertY;
  16691. texture._compression = compression;
  16692. }
  16693. if (texture.width % 4 !== 0) {
  16694. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16695. }
  16696. if (compression && data) {
  16697. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16698. }
  16699. else {
  16700. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16701. }
  16702. if (texture.generateMipMaps) {
  16703. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16704. }
  16705. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16706. // this.resetTextureCache();
  16707. texture.isReady = true;
  16708. };
  16709. /**
  16710. * Creates a new raw 3D texture
  16711. * @param data defines the data used to create the texture
  16712. * @param width defines the width of the texture
  16713. * @param height defines the height of the texture
  16714. * @param depth defines the depth of the texture
  16715. * @param format defines the format of the texture
  16716. * @param generateMipMaps defines if the engine must generate mip levels
  16717. * @param invertY defines if data must be stored with Y axis inverted
  16718. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16719. * @param compression defines the compressed used (can be null)
  16720. * @param textureType defines the compressed used (can be null)
  16721. * @returns a new raw 3D texture (stored in an InternalTexture)
  16722. */
  16723. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16724. if (compression === void 0) { compression = null; }
  16725. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16726. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16727. texture.baseWidth = width;
  16728. texture.baseHeight = height;
  16729. texture.baseDepth = depth;
  16730. texture.width = width;
  16731. texture.height = height;
  16732. texture.depth = depth;
  16733. texture.format = format;
  16734. texture.type = textureType;
  16735. texture.generateMipMaps = generateMipMaps;
  16736. texture.samplingMode = samplingMode;
  16737. texture.is3D = true;
  16738. if (!this._doNotHandleContextLost) {
  16739. texture._bufferView = data;
  16740. }
  16741. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16742. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16743. // Filters
  16744. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16745. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16746. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16747. if (generateMipMaps) {
  16748. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16749. }
  16750. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16751. this._internalTexturesCache.push(texture);
  16752. return texture;
  16753. };
  16754. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16755. var gl = this._gl;
  16756. if (!gl) {
  16757. return;
  16758. }
  16759. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16760. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16761. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16762. if (!noMipmap && !isCompressed) {
  16763. gl.generateMipmap(gl.TEXTURE_2D);
  16764. }
  16765. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16766. // this.resetTextureCache();
  16767. if (scene) {
  16768. scene._removePendingData(texture);
  16769. }
  16770. texture.onLoadedObservable.notifyObservers(texture);
  16771. texture.onLoadedObservable.clear();
  16772. };
  16773. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16774. var _this = this;
  16775. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16776. var maxTextureSize = this.getCaps().maxTextureSize;
  16777. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16778. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16779. var gl = this._gl;
  16780. if (!gl) {
  16781. return;
  16782. }
  16783. if (!texture._webGLTexture) {
  16784. // this.resetTextureCache();
  16785. if (scene) {
  16786. scene._removePendingData(texture);
  16787. }
  16788. return;
  16789. }
  16790. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16791. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16792. texture.baseWidth = width;
  16793. texture.baseHeight = height;
  16794. texture.width = potWidth;
  16795. texture.height = potHeight;
  16796. texture.isReady = true;
  16797. if (processFunction(potWidth, potHeight, function () {
  16798. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16799. })) {
  16800. // Returning as texture needs extra async steps
  16801. return;
  16802. }
  16803. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16804. };
  16805. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16806. // Create new RGBA data container.
  16807. var rgbaData;
  16808. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16809. rgbaData = new Float32Array(width * height * 4);
  16810. }
  16811. else {
  16812. rgbaData = new Uint32Array(width * height * 4);
  16813. }
  16814. // Convert each pixel.
  16815. for (var x = 0; x < width; x++) {
  16816. for (var y = 0; y < height; y++) {
  16817. var index = (y * width + x) * 3;
  16818. var newIndex = (y * width + x) * 4;
  16819. // Map Old Value to new value.
  16820. rgbaData[newIndex + 0] = rgbData[index + 0];
  16821. rgbaData[newIndex + 1] = rgbData[index + 1];
  16822. rgbaData[newIndex + 2] = rgbData[index + 2];
  16823. // Add fully opaque alpha channel.
  16824. rgbaData[newIndex + 3] = 1;
  16825. }
  16826. }
  16827. return rgbaData;
  16828. };
  16829. /** @hidden */
  16830. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16831. var gl = this._gl;
  16832. if (texture._framebuffer) {
  16833. gl.deleteFramebuffer(texture._framebuffer);
  16834. texture._framebuffer = null;
  16835. }
  16836. if (texture._depthStencilBuffer) {
  16837. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16838. texture._depthStencilBuffer = null;
  16839. }
  16840. if (texture._MSAAFramebuffer) {
  16841. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16842. texture._MSAAFramebuffer = null;
  16843. }
  16844. if (texture._MSAARenderBuffer) {
  16845. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16846. texture._MSAARenderBuffer = null;
  16847. }
  16848. };
  16849. /** @hidden */
  16850. Engine.prototype._releaseTexture = function (texture) {
  16851. var gl = this._gl;
  16852. this._releaseFramebufferObjects(texture);
  16853. gl.deleteTexture(texture._webGLTexture);
  16854. // Unbind channels
  16855. this.unbindAllTextures();
  16856. var index = this._internalTexturesCache.indexOf(texture);
  16857. if (index !== -1) {
  16858. this._internalTexturesCache.splice(index, 1);
  16859. }
  16860. // Integrated fixed lod samplers.
  16861. if (texture._lodTextureHigh) {
  16862. texture._lodTextureHigh.dispose();
  16863. }
  16864. if (texture._lodTextureMid) {
  16865. texture._lodTextureMid.dispose();
  16866. }
  16867. if (texture._lodTextureLow) {
  16868. texture._lodTextureLow.dispose();
  16869. }
  16870. // Set output texture of post process to null if the texture has been released/disposed
  16871. this.scenes.forEach(function (scene) {
  16872. scene.postProcesses.forEach(function (postProcess) {
  16873. if (postProcess._outputTexture == texture) {
  16874. postProcess._outputTexture = null;
  16875. }
  16876. });
  16877. scene.cameras.forEach(function (camera) {
  16878. camera._postProcesses.forEach(function (postProcess) {
  16879. if (postProcess) {
  16880. if (postProcess._outputTexture == texture) {
  16881. postProcess._outputTexture = null;
  16882. }
  16883. }
  16884. });
  16885. });
  16886. });
  16887. };
  16888. Engine.prototype.setProgram = function (program) {
  16889. if (this._currentProgram !== program) {
  16890. this._gl.useProgram(program);
  16891. this._currentProgram = program;
  16892. }
  16893. };
  16894. /**
  16895. * Binds an effect to the webGL context
  16896. * @param effect defines the effect to bind
  16897. */
  16898. Engine.prototype.bindSamplers = function (effect) {
  16899. this.setProgram(effect.getProgram());
  16900. var samplers = effect.getSamplers();
  16901. for (var index = 0; index < samplers.length; index++) {
  16902. var uniform = effect.getUniform(samplers[index]);
  16903. if (uniform) {
  16904. this._boundUniforms[index] = uniform;
  16905. }
  16906. }
  16907. this._currentEffect = null;
  16908. };
  16909. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16910. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16911. return;
  16912. }
  16913. // Remove
  16914. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16915. // Bind last to it
  16916. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16917. // Bind to dummy
  16918. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16919. };
  16920. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16921. if (!internalTexture) {
  16922. return -1;
  16923. }
  16924. internalTexture._initialSlot = channel;
  16925. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16926. if (channel !== internalTexture._designatedSlot) {
  16927. this._textureCollisions.addCount(1, false);
  16928. }
  16929. }
  16930. else {
  16931. if (channel !== internalTexture._designatedSlot) {
  16932. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16933. return internalTexture._designatedSlot;
  16934. }
  16935. else {
  16936. // No slot for this texture, let's pick a new one (if we find a free slot)
  16937. if (this._nextFreeTextureSlots.length) {
  16938. return this._nextFreeTextureSlots[0];
  16939. }
  16940. // We need to recycle the oldest bound texture, sorry.
  16941. this._textureCollisions.addCount(1, false);
  16942. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16943. }
  16944. }
  16945. }
  16946. return channel;
  16947. };
  16948. Engine.prototype._linkTrackers = function (previous, next) {
  16949. previous.next = next;
  16950. next.previous = previous;
  16951. };
  16952. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16953. var currentSlot = internalTexture._designatedSlot;
  16954. if (currentSlot === -1) {
  16955. return -1;
  16956. }
  16957. internalTexture._designatedSlot = -1;
  16958. if (this.disableTextureBindingOptimization) {
  16959. return -1;
  16960. }
  16961. // Remove from bound list
  16962. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16963. // Free the slot
  16964. this._boundTexturesCache[currentSlot] = null;
  16965. this._nextFreeTextureSlots.push(currentSlot);
  16966. return currentSlot;
  16967. };
  16968. Engine.prototype._activateCurrentTexture = function () {
  16969. if (this._currentTextureChannel !== this._activeChannel) {
  16970. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16971. this._currentTextureChannel = this._activeChannel;
  16972. }
  16973. };
  16974. /** @hidden */
  16975. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16976. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16977. if (force === void 0) { force = false; }
  16978. var wasPreviouslyBound = false;
  16979. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16980. this._activeChannel = texture._designatedSlot;
  16981. }
  16982. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16983. var isTextureForRendering = texture && texture._initialSlot > -1;
  16984. if (currentTextureBound !== texture || force) {
  16985. if (currentTextureBound) {
  16986. this._removeDesignatedSlot(currentTextureBound);
  16987. }
  16988. this._activateCurrentTexture();
  16989. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16990. this._boundTexturesCache[this._activeChannel] = texture;
  16991. if (texture) {
  16992. if (!this.disableTextureBindingOptimization) {
  16993. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16994. if (slotIndex > -1) {
  16995. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16996. }
  16997. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16998. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16999. }
  17000. texture._designatedSlot = this._activeChannel;
  17001. }
  17002. }
  17003. else if (forTextureDataUpdate) {
  17004. wasPreviouslyBound = true;
  17005. this._activateCurrentTexture();
  17006. }
  17007. if (isTextureForRendering && !forTextureDataUpdate) {
  17008. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  17009. }
  17010. return wasPreviouslyBound;
  17011. };
  17012. /** @hidden */
  17013. Engine.prototype._bindTexture = function (channel, texture) {
  17014. if (channel < 0) {
  17015. return;
  17016. }
  17017. if (texture) {
  17018. channel = this._getCorrectTextureChannel(channel, texture);
  17019. }
  17020. this._activeChannel = channel;
  17021. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  17022. };
  17023. /**
  17024. * Sets a texture to the webGL context from a postprocess
  17025. * @param channel defines the channel to use
  17026. * @param postProcess defines the source postprocess
  17027. */
  17028. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17029. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  17030. };
  17031. /**
  17032. * Binds the output of the passed in post process to the texture channel specified
  17033. * @param channel The channel the texture should be bound to
  17034. * @param postProcess The post process which's output should be bound
  17035. */
  17036. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  17037. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  17038. };
  17039. /**
  17040. * Unbind all textures from the webGL context
  17041. */
  17042. Engine.prototype.unbindAllTextures = function () {
  17043. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  17044. this._activeChannel = channel;
  17045. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17046. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17047. if (this.webGLVersion > 1) {
  17048. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17049. }
  17050. }
  17051. };
  17052. /**
  17053. * Sets a texture to the according uniform.
  17054. * @param channel The texture channel
  17055. * @param uniform The uniform to set
  17056. * @param texture The texture to apply
  17057. */
  17058. Engine.prototype.setTexture = function (channel, uniform, texture) {
  17059. if (channel < 0) {
  17060. return;
  17061. }
  17062. if (uniform) {
  17063. this._boundUniforms[channel] = uniform;
  17064. }
  17065. this._setTexture(channel, texture);
  17066. };
  17067. /**
  17068. * Sets a depth stencil texture from a render target to the according uniform.
  17069. * @param channel The texture channel
  17070. * @param uniform The uniform to set
  17071. * @param texture The render target texture containing the depth stencil texture to apply
  17072. */
  17073. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  17074. if (channel < 0) {
  17075. return;
  17076. }
  17077. if (uniform) {
  17078. this._boundUniforms[channel] = uniform;
  17079. }
  17080. if (!texture || !texture.depthStencilTexture) {
  17081. this._setTexture(channel, null);
  17082. }
  17083. else {
  17084. this._setTexture(channel, texture, false, true);
  17085. }
  17086. };
  17087. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  17088. var uniform = this._boundUniforms[sourceSlot];
  17089. if (uniform._currentState === destination) {
  17090. return;
  17091. }
  17092. this._gl.uniform1i(uniform, destination);
  17093. uniform._currentState = destination;
  17094. };
  17095. Engine.prototype._getTextureWrapMode = function (mode) {
  17096. switch (mode) {
  17097. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  17098. return this._gl.REPEAT;
  17099. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  17100. return this._gl.CLAMP_TO_EDGE;
  17101. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  17102. return this._gl.MIRRORED_REPEAT;
  17103. }
  17104. return this._gl.REPEAT;
  17105. };
  17106. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  17107. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  17108. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  17109. // Not ready?
  17110. if (!texture) {
  17111. if (this._boundTexturesCache[channel] != null) {
  17112. this._activeChannel = channel;
  17113. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17114. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17115. if (this.webGLVersion > 1) {
  17116. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17117. }
  17118. }
  17119. return false;
  17120. }
  17121. // Video
  17122. if (texture.video) {
  17123. this._activeChannel = channel;
  17124. texture.update();
  17125. }
  17126. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  17127. texture.delayLoad();
  17128. return false;
  17129. }
  17130. var internalTexture;
  17131. if (depthStencilTexture) {
  17132. internalTexture = texture.depthStencilTexture;
  17133. }
  17134. else if (texture.isReady()) {
  17135. internalTexture = texture.getInternalTexture();
  17136. }
  17137. else if (texture.isCube) {
  17138. internalTexture = this.emptyCubeTexture;
  17139. }
  17140. else if (texture.is3D) {
  17141. internalTexture = this.emptyTexture3D;
  17142. }
  17143. else {
  17144. internalTexture = this.emptyTexture;
  17145. }
  17146. if (!isPartOfTextureArray) {
  17147. channel = this._getCorrectTextureChannel(channel, internalTexture);
  17148. }
  17149. var needToBind = true;
  17150. if (this._boundTexturesCache[channel] === internalTexture) {
  17151. this._moveBoundTextureOnTop(internalTexture);
  17152. if (!isPartOfTextureArray) {
  17153. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  17154. }
  17155. needToBind = false;
  17156. }
  17157. this._activeChannel = channel;
  17158. if (internalTexture && internalTexture.is3D) {
  17159. if (needToBind) {
  17160. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  17161. }
  17162. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17163. internalTexture._cachedWrapU = texture.wrapU;
  17164. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17165. }
  17166. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17167. internalTexture._cachedWrapV = texture.wrapV;
  17168. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17169. }
  17170. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  17171. internalTexture._cachedWrapR = texture.wrapR;
  17172. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  17173. }
  17174. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  17175. }
  17176. else if (internalTexture && internalTexture.isCube) {
  17177. if (needToBind) {
  17178. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  17179. }
  17180. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  17181. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  17182. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  17183. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  17184. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  17185. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  17186. }
  17187. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  17188. }
  17189. else {
  17190. if (needToBind) {
  17191. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  17192. }
  17193. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17194. internalTexture._cachedWrapU = texture.wrapU;
  17195. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17196. }
  17197. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17198. internalTexture._cachedWrapV = texture.wrapV;
  17199. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17200. }
  17201. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  17202. }
  17203. return true;
  17204. };
  17205. /**
  17206. * Sets an array of texture to the webGL context
  17207. * @param channel defines the channel where the texture array must be set
  17208. * @param uniform defines the associated uniform location
  17209. * @param textures defines the array of textures to bind
  17210. */
  17211. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  17212. if (channel < 0 || !uniform) {
  17213. return;
  17214. }
  17215. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  17216. this._textureUnits = new Int32Array(textures.length);
  17217. }
  17218. for (var i = 0; i < textures.length; i++) {
  17219. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  17220. }
  17221. this._gl.uniform1iv(uniform, this._textureUnits);
  17222. for (var index = 0; index < textures.length; index++) {
  17223. this._setTexture(this._textureUnits[index], textures[index], true);
  17224. }
  17225. };
  17226. /** @hidden */
  17227. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  17228. var internalTexture = texture.getInternalTexture();
  17229. if (!internalTexture) {
  17230. return;
  17231. }
  17232. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  17233. var value = texture.anisotropicFilteringLevel;
  17234. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  17235. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  17236. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  17237. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  17238. }
  17239. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  17240. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  17241. internalTexture._cachedAnisotropicFilteringLevel = value;
  17242. }
  17243. };
  17244. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  17245. this._bindTextureDirectly(target, texture, true, true);
  17246. this._gl.texParameterf(target, parameter, value);
  17247. };
  17248. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  17249. if (texture) {
  17250. this._bindTextureDirectly(target, texture, true, true);
  17251. }
  17252. this._gl.texParameteri(target, parameter, value);
  17253. };
  17254. /**
  17255. * Reads pixels from the current frame buffer. Please note that this function can be slow
  17256. * @param x defines the x coordinate of the rectangle where pixels must be read
  17257. * @param y defines the y coordinate of the rectangle where pixels must be read
  17258. * @param width defines the width of the rectangle where pixels must be read
  17259. * @param height defines the height of the rectangle where pixels must be read
  17260. * @returns a Uint8Array containing RGBA colors
  17261. */
  17262. Engine.prototype.readPixels = function (x, y, width, height) {
  17263. var data = new Uint8Array(height * width * 4);
  17264. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  17265. return data;
  17266. };
  17267. /**
  17268. * Add an externaly attached data from its key.
  17269. * This method call will fail and return false, if such key already exists.
  17270. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17271. * @param key the unique key that identifies the data
  17272. * @param data the data object to associate to the key for this Engine instance
  17273. * @return true if no such key were already present and the data was added successfully, false otherwise
  17274. */
  17275. Engine.prototype.addExternalData = function (key, data) {
  17276. if (!this._externalData) {
  17277. this._externalData = new BABYLON.StringDictionary();
  17278. }
  17279. return this._externalData.add(key, data);
  17280. };
  17281. /**
  17282. * Get an externaly attached data from its key
  17283. * @param key the unique key that identifies the data
  17284. * @return the associated data, if present (can be null), or undefined if not present
  17285. */
  17286. Engine.prototype.getExternalData = function (key) {
  17287. if (!this._externalData) {
  17288. this._externalData = new BABYLON.StringDictionary();
  17289. }
  17290. return this._externalData.get(key);
  17291. };
  17292. /**
  17293. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17294. * @param key the unique key that identifies the data
  17295. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17296. * @return the associated data, can be null if the factory returned null.
  17297. */
  17298. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17299. if (!this._externalData) {
  17300. this._externalData = new BABYLON.StringDictionary();
  17301. }
  17302. return this._externalData.getOrAddWithFactory(key, factory);
  17303. };
  17304. /**
  17305. * Remove an externaly attached data from the Engine instance
  17306. * @param key the unique key that identifies the data
  17307. * @return true if the data was successfully removed, false if it doesn't exist
  17308. */
  17309. Engine.prototype.removeExternalData = function (key) {
  17310. if (!this._externalData) {
  17311. this._externalData = new BABYLON.StringDictionary();
  17312. }
  17313. return this._externalData.remove(key);
  17314. };
  17315. /**
  17316. * Unbind all vertex attributes from the webGL context
  17317. */
  17318. Engine.prototype.unbindAllAttributes = function () {
  17319. if (this._mustWipeVertexAttributes) {
  17320. this._mustWipeVertexAttributes = false;
  17321. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  17322. this._gl.disableVertexAttribArray(i);
  17323. this._vertexAttribArraysEnabled[i] = false;
  17324. this._currentBufferPointers[i].active = false;
  17325. }
  17326. return;
  17327. }
  17328. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  17329. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  17330. continue;
  17331. }
  17332. this._gl.disableVertexAttribArray(i);
  17333. this._vertexAttribArraysEnabled[i] = false;
  17334. this._currentBufferPointers[i].active = false;
  17335. }
  17336. };
  17337. /**
  17338. * 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
  17339. */
  17340. Engine.prototype.releaseEffects = function () {
  17341. for (var name in this._compiledEffects) {
  17342. this._deleteProgram(this._compiledEffects[name]._program);
  17343. }
  17344. this._compiledEffects = {};
  17345. };
  17346. /**
  17347. * Dispose and release all associated resources
  17348. */
  17349. Engine.prototype.dispose = function () {
  17350. this.hideLoadingUI();
  17351. this.stopRenderLoop();
  17352. // Release postProcesses
  17353. while (this.postProcesses.length) {
  17354. this.postProcesses[0].dispose();
  17355. }
  17356. // Empty texture
  17357. if (this._emptyTexture) {
  17358. this._releaseTexture(this._emptyTexture);
  17359. this._emptyTexture = null;
  17360. }
  17361. if (this._emptyCubeTexture) {
  17362. this._releaseTexture(this._emptyCubeTexture);
  17363. this._emptyCubeTexture = null;
  17364. }
  17365. // Rescale PP
  17366. if (this._rescalePostProcess) {
  17367. this._rescalePostProcess.dispose();
  17368. }
  17369. // Release scenes
  17370. while (this.scenes.length) {
  17371. this.scenes[0].dispose();
  17372. }
  17373. // Release audio engine
  17374. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  17375. Engine.audioEngine.dispose();
  17376. }
  17377. // Release effects
  17378. this.releaseEffects();
  17379. // Unbind
  17380. this.unbindAllAttributes();
  17381. this._boundUniforms = [];
  17382. if (this._dummyFramebuffer) {
  17383. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  17384. }
  17385. //WebVR
  17386. this.disableVR();
  17387. // Events
  17388. if (BABYLON.Tools.IsWindowObjectExist()) {
  17389. window.removeEventListener("blur", this._onBlur);
  17390. window.removeEventListener("focus", this._onFocus);
  17391. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  17392. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  17393. if (this._renderingCanvas) {
  17394. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  17395. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  17396. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  17397. if (!this._doNotHandleContextLost) {
  17398. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  17399. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  17400. }
  17401. }
  17402. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  17403. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  17404. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  17405. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  17406. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  17407. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  17408. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  17409. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  17410. if (this._onVrDisplayConnect) {
  17411. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  17412. if (this._onVrDisplayDisconnect) {
  17413. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  17414. }
  17415. if (this._onVrDisplayPresentChange) {
  17416. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  17417. }
  17418. this._onVrDisplayConnect = null;
  17419. this._onVrDisplayDisconnect = null;
  17420. }
  17421. }
  17422. // Remove from Instances
  17423. var index = Engine.Instances.indexOf(this);
  17424. if (index >= 0) {
  17425. Engine.Instances.splice(index, 1);
  17426. }
  17427. this._workingCanvas = null;
  17428. this._workingContext = null;
  17429. this._currentBufferPointers = [];
  17430. this._renderingCanvas = null;
  17431. this._currentProgram = null;
  17432. this._bindedRenderFunction = null;
  17433. this.onResizeObservable.clear();
  17434. this.onCanvasBlurObservable.clear();
  17435. this.onCanvasFocusObservable.clear();
  17436. this.onCanvasPointerOutObservable.clear();
  17437. this.onBeginFrameObservable.clear();
  17438. this.onEndFrameObservable.clear();
  17439. BABYLON.Effect.ResetCache();
  17440. // Abort active requests
  17441. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  17442. var request = _a[_i];
  17443. request.abort();
  17444. }
  17445. };
  17446. // Loading screen
  17447. /**
  17448. * Display the loading screen
  17449. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17450. */
  17451. Engine.prototype.displayLoadingUI = function () {
  17452. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17453. return;
  17454. }
  17455. var loadingScreen = this.loadingScreen;
  17456. if (loadingScreen) {
  17457. loadingScreen.displayLoadingUI();
  17458. }
  17459. };
  17460. /**
  17461. * Hide the loading screen
  17462. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17463. */
  17464. Engine.prototype.hideLoadingUI = function () {
  17465. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17466. return;
  17467. }
  17468. var loadingScreen = this.loadingScreen;
  17469. if (loadingScreen) {
  17470. loadingScreen.hideLoadingUI();
  17471. }
  17472. };
  17473. Object.defineProperty(Engine.prototype, "loadingScreen", {
  17474. /**
  17475. * Gets the current loading screen object
  17476. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17477. */
  17478. get: function () {
  17479. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  17480. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  17481. return this._loadingScreen;
  17482. },
  17483. /**
  17484. * Sets the current loading screen object
  17485. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17486. */
  17487. set: function (loadingScreen) {
  17488. this._loadingScreen = loadingScreen;
  17489. },
  17490. enumerable: true,
  17491. configurable: true
  17492. });
  17493. Object.defineProperty(Engine.prototype, "loadingUIText", {
  17494. /**
  17495. * Sets the current loading screen text
  17496. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17497. */
  17498. set: function (text) {
  17499. this.loadingScreen.loadingUIText = text;
  17500. },
  17501. enumerable: true,
  17502. configurable: true
  17503. });
  17504. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  17505. /**
  17506. * Sets the current loading screen background color
  17507. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17508. */
  17509. set: function (color) {
  17510. this.loadingScreen.loadingUIBackgroundColor = color;
  17511. },
  17512. enumerable: true,
  17513. configurable: true
  17514. });
  17515. /**
  17516. * Attach a new callback raised when context lost event is fired
  17517. * @param callback defines the callback to call
  17518. */
  17519. Engine.prototype.attachContextLostEvent = function (callback) {
  17520. if (this._renderingCanvas) {
  17521. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  17522. }
  17523. };
  17524. /**
  17525. * Attach a new callback raised when context restored event is fired
  17526. * @param callback defines the callback to call
  17527. */
  17528. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17529. if (this._renderingCanvas) {
  17530. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17531. }
  17532. };
  17533. /**
  17534. * Gets the source code of the vertex shader associated with a specific webGL program
  17535. * @param program defines the program to use
  17536. * @returns a string containing the source code of the vertex shader associated with the program
  17537. */
  17538. Engine.prototype.getVertexShaderSource = function (program) {
  17539. var shaders = this._gl.getAttachedShaders(program);
  17540. if (!shaders) {
  17541. return null;
  17542. }
  17543. return this._gl.getShaderSource(shaders[0]);
  17544. };
  17545. /**
  17546. * Gets the source code of the fragment shader associated with a specific webGL program
  17547. * @param program defines the program to use
  17548. * @returns a string containing the source code of the fragment shader associated with the program
  17549. */
  17550. Engine.prototype.getFragmentShaderSource = function (program) {
  17551. var shaders = this._gl.getAttachedShaders(program);
  17552. if (!shaders) {
  17553. return null;
  17554. }
  17555. return this._gl.getShaderSource(shaders[1]);
  17556. };
  17557. /**
  17558. * Get the current error code of the webGL context
  17559. * @returns the error code
  17560. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17561. */
  17562. Engine.prototype.getError = function () {
  17563. return this._gl.getError();
  17564. };
  17565. // FPS
  17566. /**
  17567. * Gets the current framerate
  17568. * @returns a number representing the framerate
  17569. */
  17570. Engine.prototype.getFps = function () {
  17571. return this._fps;
  17572. };
  17573. /**
  17574. * Gets the time spent between current and previous frame
  17575. * @returns a number representing the delta time in ms
  17576. */
  17577. Engine.prototype.getDeltaTime = function () {
  17578. return this._deltaTime;
  17579. };
  17580. Engine.prototype._measureFps = function () {
  17581. this._performanceMonitor.sampleFrame();
  17582. this._fps = this._performanceMonitor.averageFPS;
  17583. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17584. };
  17585. /** @hidden */
  17586. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
  17587. if (faceIndex === void 0) { faceIndex = -1; }
  17588. if (level === void 0) { level = 0; }
  17589. if (buffer === void 0) { buffer = null; }
  17590. var gl = this._gl;
  17591. if (!this._dummyFramebuffer) {
  17592. var dummy = gl.createFramebuffer();
  17593. if (!dummy) {
  17594. throw new Error("Unable to create dummy framebuffer");
  17595. }
  17596. this._dummyFramebuffer = dummy;
  17597. }
  17598. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17599. if (faceIndex > -1) {
  17600. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17601. }
  17602. else {
  17603. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17604. }
  17605. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17606. switch (readType) {
  17607. case gl.UNSIGNED_BYTE:
  17608. if (!buffer) {
  17609. buffer = new Uint8Array(4 * width * height);
  17610. }
  17611. readType = gl.UNSIGNED_BYTE;
  17612. break;
  17613. default:
  17614. if (!buffer) {
  17615. buffer = new Float32Array(4 * width * height);
  17616. }
  17617. readType = gl.FLOAT;
  17618. break;
  17619. }
  17620. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17621. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17622. return buffer;
  17623. };
  17624. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17625. if (this._webGLVersion > 1) {
  17626. return this._caps.colorBufferFloat;
  17627. }
  17628. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17629. };
  17630. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17631. if (this._webGLVersion > 1) {
  17632. return this._caps.colorBufferFloat;
  17633. }
  17634. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17635. };
  17636. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17637. Engine.prototype._canRenderToFramebuffer = function (type) {
  17638. var gl = this._gl;
  17639. //clear existing errors
  17640. while (gl.getError() !== gl.NO_ERROR) { }
  17641. var successful = true;
  17642. var texture = gl.createTexture();
  17643. gl.bindTexture(gl.TEXTURE_2D, texture);
  17644. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17645. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17646. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17647. var fb = gl.createFramebuffer();
  17648. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17649. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17650. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17651. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17652. successful = successful && (gl.getError() === gl.NO_ERROR);
  17653. //try render by clearing frame buffer's color buffer
  17654. if (successful) {
  17655. gl.clear(gl.COLOR_BUFFER_BIT);
  17656. successful = successful && (gl.getError() === gl.NO_ERROR);
  17657. }
  17658. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17659. if (successful) {
  17660. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17661. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17662. var readFormat = gl.RGBA;
  17663. var readType = gl.UNSIGNED_BYTE;
  17664. var buffer = new Uint8Array(4);
  17665. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17666. successful = successful && (gl.getError() === gl.NO_ERROR);
  17667. }
  17668. //clean up
  17669. gl.deleteTexture(texture);
  17670. gl.deleteFramebuffer(fb);
  17671. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17672. //clear accumulated errors
  17673. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17674. return successful;
  17675. };
  17676. /** @hidden */
  17677. Engine.prototype._getWebGLTextureType = function (type) {
  17678. if (this._webGLVersion === 1) {
  17679. switch (type) {
  17680. case Engine.TEXTURETYPE_FLOAT:
  17681. return this._gl.FLOAT;
  17682. case Engine.TEXTURETYPE_HALF_FLOAT:
  17683. return this._gl.HALF_FLOAT_OES;
  17684. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17685. return this._gl.UNSIGNED_BYTE;
  17686. }
  17687. return this._gl.UNSIGNED_BYTE;
  17688. }
  17689. switch (type) {
  17690. case Engine.TEXTURETYPE_BYTE:
  17691. return this._gl.BYTE;
  17692. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17693. return this._gl.UNSIGNED_BYTE;
  17694. case Engine.TEXTURETYPE_SHORT:
  17695. return this._gl.SHORT;
  17696. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17697. return this._gl.UNSIGNED_SHORT;
  17698. case Engine.TEXTURETYPE_INT:
  17699. return this._gl.INT;
  17700. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17701. return this._gl.UNSIGNED_INT;
  17702. case Engine.TEXTURETYPE_FLOAT:
  17703. return this._gl.FLOAT;
  17704. case Engine.TEXTURETYPE_HALF_FLOAT:
  17705. return this._gl.HALF_FLOAT;
  17706. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17707. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  17708. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17709. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  17710. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17711. return this._gl.UNSIGNED_SHORT_5_6_5;
  17712. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17713. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  17714. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  17715. return this._gl.UNSIGNED_INT_24_8;
  17716. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17717. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  17718. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17719. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  17720. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  17721. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  17722. }
  17723. return this._gl.UNSIGNED_BYTE;
  17724. };
  17725. ;
  17726. Engine.prototype._getInternalFormat = function (format) {
  17727. var internalFormat = this._gl.RGBA;
  17728. switch (format) {
  17729. case Engine.TEXTUREFORMAT_ALPHA:
  17730. internalFormat = this._gl.ALPHA;
  17731. break;
  17732. case Engine.TEXTUREFORMAT_LUMINANCE:
  17733. internalFormat = this._gl.LUMINANCE;
  17734. break;
  17735. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17736. internalFormat = this._gl.LUMINANCE_ALPHA;
  17737. break;
  17738. case Engine.TEXTUREFORMAT_RED:
  17739. internalFormat = this._gl.RED;
  17740. break;
  17741. case Engine.TEXTUREFORMAT_RG:
  17742. internalFormat = this._gl.RG;
  17743. break;
  17744. case Engine.TEXTUREFORMAT_RGB:
  17745. internalFormat = this._gl.RGB;
  17746. break;
  17747. case Engine.TEXTUREFORMAT_RGBA:
  17748. internalFormat = this._gl.RGBA;
  17749. break;
  17750. }
  17751. if (this._webGLVersion > 1) {
  17752. switch (format) {
  17753. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17754. internalFormat = this._gl.RED_INTEGER;
  17755. break;
  17756. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17757. internalFormat = this._gl.RG_INTEGER;
  17758. break;
  17759. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17760. internalFormat = this._gl.RGB_INTEGER;
  17761. break;
  17762. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17763. internalFormat = this._gl.RGBA_INTEGER;
  17764. break;
  17765. }
  17766. }
  17767. return internalFormat;
  17768. };
  17769. /** @hidden */
  17770. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17771. if (this._webGLVersion === 1) {
  17772. if (format !== undefined) {
  17773. switch (format) {
  17774. case Engine.TEXTUREFORMAT_ALPHA:
  17775. return this._gl.ALPHA;
  17776. case Engine.TEXTUREFORMAT_LUMINANCE:
  17777. return this._gl.LUMINANCE;
  17778. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17779. return this._gl.LUMINANCE_ALPHA;
  17780. }
  17781. }
  17782. return this._gl.RGBA;
  17783. }
  17784. switch (type) {
  17785. case Engine.TEXTURETYPE_BYTE:
  17786. switch (format) {
  17787. case Engine.TEXTUREFORMAT_RED:
  17788. return this._gl.R8_SNORM;
  17789. case Engine.TEXTUREFORMAT_RG:
  17790. return this._gl.RG8_SNORM;
  17791. case Engine.TEXTUREFORMAT_RGB:
  17792. return this._gl.RGB8_SNORM;
  17793. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17794. return this._gl.R8I;
  17795. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17796. return this._gl.RG8I;
  17797. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17798. return this._gl.RGB8I;
  17799. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17800. return this._gl.RGBA8I;
  17801. default:
  17802. return this._gl.RGBA8_SNORM;
  17803. }
  17804. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17805. switch (format) {
  17806. case Engine.TEXTUREFORMAT_RED:
  17807. return this._gl.R8;
  17808. case Engine.TEXTUREFORMAT_RG:
  17809. return this._gl.RG8;
  17810. case Engine.TEXTUREFORMAT_RGB:
  17811. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17812. case Engine.TEXTUREFORMAT_RGBA:
  17813. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17814. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17815. return this._gl.R8UI;
  17816. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17817. return this._gl.RG8UI;
  17818. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17819. return this._gl.RGB8UI;
  17820. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17821. return this._gl.RGBA8UI;
  17822. default:
  17823. return this._gl.RGBA8;
  17824. }
  17825. case Engine.TEXTURETYPE_SHORT:
  17826. switch (format) {
  17827. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17828. return this._gl.R16I;
  17829. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17830. return this._gl.RG16I;
  17831. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17832. return this._gl.RGB16I;
  17833. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17834. return this._gl.RGBA16I;
  17835. default:
  17836. return this._gl.RGBA16I;
  17837. }
  17838. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17839. switch (format) {
  17840. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17841. return this._gl.R16UI;
  17842. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17843. return this._gl.RG16UI;
  17844. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17845. return this._gl.RGB16UI;
  17846. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17847. return this._gl.RGBA16UI;
  17848. default:
  17849. return this._gl.RGBA16UI;
  17850. }
  17851. case Engine.TEXTURETYPE_INT:
  17852. switch (format) {
  17853. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17854. return this._gl.R32I;
  17855. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17856. return this._gl.RG32I;
  17857. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17858. return this._gl.RGB32I;
  17859. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17860. return this._gl.RGBA32I;
  17861. default:
  17862. return this._gl.RGBA32I;
  17863. }
  17864. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17865. switch (format) {
  17866. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17867. return this._gl.R32UI;
  17868. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17869. return this._gl.RG32UI;
  17870. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17871. return this._gl.RGB32UI;
  17872. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17873. return this._gl.RGBA32UI;
  17874. default:
  17875. return this._gl.RGBA32UI;
  17876. }
  17877. case Engine.TEXTURETYPE_FLOAT:
  17878. switch (format) {
  17879. case Engine.TEXTUREFORMAT_RED:
  17880. return this._gl.R32F; // By default. Other possibility is R16F.
  17881. case Engine.TEXTUREFORMAT_RG:
  17882. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17883. case Engine.TEXTUREFORMAT_RGB:
  17884. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17885. case Engine.TEXTUREFORMAT_RGBA:
  17886. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17887. default:
  17888. return this._gl.RGBA32F;
  17889. }
  17890. case Engine.TEXTURETYPE_HALF_FLOAT:
  17891. switch (format) {
  17892. case Engine.TEXTUREFORMAT_RED:
  17893. return this._gl.R16F;
  17894. case Engine.TEXTUREFORMAT_RG:
  17895. return this._gl.RG16F;
  17896. case Engine.TEXTUREFORMAT_RGB:
  17897. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17898. case Engine.TEXTUREFORMAT_RGBA:
  17899. return this._gl.RGBA16F;
  17900. default:
  17901. return this._gl.RGBA16F;
  17902. }
  17903. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17904. return this._gl.RGB565;
  17905. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17906. return this._gl.R11F_G11F_B10F;
  17907. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17908. return this._gl.RGB9_E5;
  17909. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17910. return this._gl.RGBA4;
  17911. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17912. return this._gl.RGB5_A1;
  17913. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17914. switch (format) {
  17915. case Engine.TEXTUREFORMAT_RGBA:
  17916. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  17917. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17918. return this._gl.RGB10_A2UI;
  17919. default:
  17920. return this._gl.RGB10_A2;
  17921. }
  17922. }
  17923. return this._gl.RGBA8;
  17924. };
  17925. ;
  17926. /** @hidden */
  17927. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17928. if (type === Engine.TEXTURETYPE_FLOAT) {
  17929. return this._gl.RGBA32F;
  17930. }
  17931. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17932. return this._gl.RGBA16F;
  17933. }
  17934. return this._gl.RGBA8;
  17935. };
  17936. ;
  17937. /** @hidden */
  17938. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17939. var _this = this;
  17940. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17941. this._activeRequests.push(request);
  17942. request.onCompleteObservable.add(function (request) {
  17943. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17944. });
  17945. return request;
  17946. };
  17947. /** @hidden */
  17948. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17949. var _this = this;
  17950. return new Promise(function (resolve, reject) {
  17951. _this._loadFile(url, function (data) {
  17952. resolve(data);
  17953. }, undefined, database, useArrayBuffer, function (request, exception) {
  17954. reject(exception);
  17955. });
  17956. });
  17957. };
  17958. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17959. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17960. var onload = function (data) {
  17961. loadedFiles[index] = data;
  17962. loadedFiles._internalCount++;
  17963. if (loadedFiles._internalCount === 6) {
  17964. onfinish(loadedFiles);
  17965. }
  17966. };
  17967. var onerror = function (request, exception) {
  17968. if (onErrorCallBack && request) {
  17969. onErrorCallBack(request.status + " " + request.statusText, exception);
  17970. }
  17971. };
  17972. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17973. };
  17974. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17975. if (onError === void 0) { onError = null; }
  17976. var loadedFiles = [];
  17977. loadedFiles._internalCount = 0;
  17978. for (var index = 0; index < 6; index++) {
  17979. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17980. }
  17981. };
  17982. // Statics
  17983. /**
  17984. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17985. * @returns true if the engine can be created
  17986. * @ignorenaming
  17987. */
  17988. Engine.isSupported = function () {
  17989. try {
  17990. var tempcanvas = document.createElement("canvas");
  17991. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17992. return gl != null && !!window.WebGLRenderingContext;
  17993. }
  17994. catch (e) {
  17995. return false;
  17996. }
  17997. };
  17998. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17999. Engine.ExceptionList = [
  18000. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  18001. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  18002. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  18003. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  18004. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  18005. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  18006. ];
  18007. /** Gets the list of created engines */
  18008. Engine.Instances = new Array();
  18009. /**
  18010. * Hidden
  18011. */
  18012. Engine._TextureLoaders = [];
  18013. // Const statics
  18014. /** Defines that alpha blending is disabled */
  18015. Engine.ALPHA_DISABLE = 0;
  18016. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  18017. Engine.ALPHA_ADD = 1;
  18018. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  18019. Engine.ALPHA_COMBINE = 2;
  18020. /** Defines that alpha blending to DEST - SRC * DEST */
  18021. Engine.ALPHA_SUBTRACT = 3;
  18022. /** Defines that alpha blending to SRC * DEST */
  18023. Engine.ALPHA_MULTIPLY = 4;
  18024. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  18025. Engine.ALPHA_MAXIMIZED = 5;
  18026. /** Defines that alpha blending to SRC + DEST */
  18027. Engine.ALPHA_ONEONE = 6;
  18028. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  18029. Engine.ALPHA_PREMULTIPLIED = 7;
  18030. /**
  18031. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  18032. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  18033. */
  18034. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  18035. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  18036. Engine.ALPHA_INTERPOLATE = 9;
  18037. /**
  18038. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  18039. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  18040. */
  18041. Engine.ALPHA_SCREENMODE = 10;
  18042. /** Defines that the ressource is not delayed*/
  18043. Engine.DELAYLOADSTATE_NONE = 0;
  18044. /** Defines that the ressource was successfully delay loaded */
  18045. Engine.DELAYLOADSTATE_LOADED = 1;
  18046. /** Defines that the ressource is currently delay loading */
  18047. Engine.DELAYLOADSTATE_LOADING = 2;
  18048. /** Defines that the ressource is delayed and has not started loading */
  18049. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  18050. // Depht or Stencil test Constants.
  18051. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  18052. Engine.NEVER = 0x0200;
  18053. /** 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 */
  18054. Engine.ALWAYS = 0x0207;
  18055. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  18056. Engine.LESS = 0x0201;
  18057. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  18058. Engine.EQUAL = 0x0202;
  18059. /** 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 */
  18060. Engine.LEQUAL = 0x0203;
  18061. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  18062. Engine.GREATER = 0x0204;
  18063. /** 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 */
  18064. Engine.GEQUAL = 0x0206;
  18065. /** 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 */
  18066. Engine.NOTEQUAL = 0x0205;
  18067. // Stencil Actions Constants.
  18068. /** Passed to stencilOperation to specify that stencil value must be kept */
  18069. Engine.KEEP = 0x1E00;
  18070. /** Passed to stencilOperation to specify that stencil value must be replaced */
  18071. Engine.REPLACE = 0x1E01;
  18072. /** Passed to stencilOperation to specify that stencil value must be incremented */
  18073. Engine.INCR = 0x1E02;
  18074. /** Passed to stencilOperation to specify that stencil value must be decremented */
  18075. Engine.DECR = 0x1E03;
  18076. /** Passed to stencilOperation to specify that stencil value must be inverted */
  18077. Engine.INVERT = 0x150A;
  18078. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  18079. Engine.INCR_WRAP = 0x8507;
  18080. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  18081. Engine.DECR_WRAP = 0x8508;
  18082. /** Texture is not repeating outside of 0..1 UVs */
  18083. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  18084. /** Texture is repeating outside of 0..1 UVs */
  18085. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  18086. /** Texture is repeating and mirrored */
  18087. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  18088. /** ALPHA */
  18089. Engine.TEXTUREFORMAT_ALPHA = 0;
  18090. /** LUMINANCE */
  18091. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  18092. /** LUMINANCE_ALPHA */
  18093. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  18094. /** RGB */
  18095. Engine.TEXTUREFORMAT_RGB = 4;
  18096. /** RGBA */
  18097. Engine.TEXTUREFORMAT_RGBA = 5;
  18098. /** RED */
  18099. Engine.TEXTUREFORMAT_RED = 6;
  18100. /** RED (2nd reference) */
  18101. Engine.TEXTUREFORMAT_R = 6;
  18102. /** RG */
  18103. Engine.TEXTUREFORMAT_RG = 7;
  18104. /** RED_INTEGER */
  18105. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  18106. /** RED_INTEGER (2nd reference) */
  18107. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  18108. /** RG_INTEGER */
  18109. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  18110. /** RGB_INTEGER */
  18111. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  18112. /** RGBA_INTEGER */
  18113. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  18114. /** UNSIGNED_BYTE */
  18115. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  18116. /** UNSIGNED_BYTE (2nd reference) */
  18117. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  18118. /** FLOAT */
  18119. Engine.TEXTURETYPE_FLOAT = 1;
  18120. /** HALF_FLOAT */
  18121. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  18122. /** BYTE */
  18123. Engine.TEXTURETYPE_BYTE = 3;
  18124. /** SHORT */
  18125. Engine.TEXTURETYPE_SHORT = 4;
  18126. /** UNSIGNED_SHORT */
  18127. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  18128. /** INT */
  18129. Engine.TEXTURETYPE_INT = 6;
  18130. /** UNSIGNED_INT */
  18131. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  18132. /** UNSIGNED_SHORT_4_4_4_4 */
  18133. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  18134. /** UNSIGNED_SHORT_5_5_5_1 */
  18135. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  18136. /** UNSIGNED_SHORT_5_6_5 */
  18137. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  18138. /** UNSIGNED_INT_2_10_10_10_REV */
  18139. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  18140. /** UNSIGNED_INT_24_8 */
  18141. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  18142. /** UNSIGNED_INT_10F_11F_11F_REV */
  18143. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  18144. /** UNSIGNED_INT_5_9_9_9_REV */
  18145. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  18146. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  18147. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  18148. /** nearest is mag = nearest and min = nearest and mip = linear */
  18149. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  18150. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18151. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  18152. /** Trilinear is mag = linear and min = linear and mip = linear */
  18153. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  18154. /** nearest is mag = nearest and min = nearest and mip = linear */
  18155. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  18156. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18157. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  18158. /** Trilinear is mag = linear and min = linear and mip = linear */
  18159. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  18160. /** mag = nearest and min = nearest and mip = nearest */
  18161. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  18162. /** mag = nearest and min = linear and mip = nearest */
  18163. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  18164. /** mag = nearest and min = linear and mip = linear */
  18165. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  18166. /** mag = nearest and min = linear and mip = none */
  18167. Engine.TEXTURE_NEAREST_LINEAR = 7;
  18168. /** mag = nearest and min = nearest and mip = none */
  18169. Engine.TEXTURE_NEAREST_NEAREST = 8;
  18170. /** mag = linear and min = nearest and mip = nearest */
  18171. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  18172. /** mag = linear and min = nearest and mip = linear */
  18173. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  18174. /** mag = linear and min = linear and mip = none */
  18175. Engine.TEXTURE_LINEAR_LINEAR = 11;
  18176. /** mag = linear and min = nearest and mip = none */
  18177. Engine.TEXTURE_LINEAR_NEAREST = 12;
  18178. /** Explicit coordinates mode */
  18179. Engine.TEXTURE_EXPLICIT_MODE = 0;
  18180. /** Spherical coordinates mode */
  18181. Engine.TEXTURE_SPHERICAL_MODE = 1;
  18182. /** Planar coordinates mode */
  18183. Engine.TEXTURE_PLANAR_MODE = 2;
  18184. /** Cubic coordinates mode */
  18185. Engine.TEXTURE_CUBIC_MODE = 3;
  18186. /** Projection coordinates mode */
  18187. Engine.TEXTURE_PROJECTION_MODE = 4;
  18188. /** Skybox coordinates mode */
  18189. Engine.TEXTURE_SKYBOX_MODE = 5;
  18190. /** Inverse Cubic coordinates mode */
  18191. Engine.TEXTURE_INVCUBIC_MODE = 6;
  18192. /** Equirectangular coordinates mode */
  18193. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  18194. /** Equirectangular Fixed coordinates mode */
  18195. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  18196. /** Equirectangular Fixed Mirrored coordinates mode */
  18197. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  18198. // Texture rescaling mode
  18199. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  18200. Engine.SCALEMODE_FLOOR = 1;
  18201. /** Defines that texture rescaling will look for the nearest power of 2 size */
  18202. Engine.SCALEMODE_NEAREST = 2;
  18203. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  18204. Engine.SCALEMODE_CEILING = 3;
  18205. // Updatable statics so stick with vars here
  18206. /**
  18207. * Gets or sets the epsilon value used by collision engine
  18208. */
  18209. Engine.CollisionsEpsilon = 0.001;
  18210. /**
  18211. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  18212. */
  18213. Engine.CodeRepository = "src/";
  18214. /**
  18215. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  18216. */
  18217. Engine.ShadersRepository = "src/Shaders/";
  18218. return Engine;
  18219. }());
  18220. BABYLON.Engine = Engine;
  18221. })(BABYLON || (BABYLON = {}));
  18222. //# sourceMappingURL=babylon.engine.js.map
  18223. var BABYLON;
  18224. (function (BABYLON) {
  18225. /**
  18226. * Node is the basic class for all scene objects (Mesh, Light, Camera.)
  18227. */
  18228. var Node = /** @class */ (function () {
  18229. /**
  18230. * Creates a new Node
  18231. * @param {string} name - the name and id to be given to this node
  18232. * @param {BABYLON.Scene} the scene this node will be added to
  18233. */
  18234. function Node(name, scene) {
  18235. if (scene === void 0) { scene = null; }
  18236. /**
  18237. * Gets or sets a string used to store user defined state for the node
  18238. */
  18239. this.state = "";
  18240. /**
  18241. * Gets or sets an object used to store user defined information for the node
  18242. */
  18243. this.metadata = null;
  18244. /**
  18245. * Gets or sets a boolean used to define if the node must be serialized
  18246. */
  18247. this.doNotSerialize = false;
  18248. /** @hidden */
  18249. this._isDisposed = false;
  18250. /**
  18251. * Gets a list of Animations associated with the node
  18252. */
  18253. this.animations = new Array();
  18254. this._ranges = {};
  18255. this._isEnabled = true;
  18256. this._isParentEnabled = true;
  18257. this._isReady = true;
  18258. /** @hidden */
  18259. this._currentRenderId = -1;
  18260. this._parentRenderId = -1;
  18261. this._childRenderId = -1;
  18262. /** @hidden */
  18263. this._worldMatrix = BABYLON.Matrix.Identity();
  18264. /** @hidden */
  18265. this._worldMatrixDeterminant = 0;
  18266. /** @hidden */
  18267. this._sceneRootNodesIndex = -1;
  18268. this._animationPropertiesOverride = null;
  18269. /**
  18270. * An event triggered when the mesh is disposed
  18271. */
  18272. this.onDisposeObservable = new BABYLON.Observable();
  18273. // Behaviors
  18274. this._behaviors = new Array();
  18275. this.name = name;
  18276. this.id = name;
  18277. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  18278. this.uniqueId = this._scene.getUniqueId();
  18279. this._initCache();
  18280. this.addToSceneRootNodes();
  18281. }
  18282. /**
  18283. * Add a new node constructor
  18284. * @param type defines the type name of the node to construct
  18285. * @param constructorFunc defines the constructor function
  18286. */
  18287. Node.AddNodeConstructor = function (type, constructorFunc) {
  18288. this._NodeConstructors[type] = constructorFunc;
  18289. };
  18290. /**
  18291. * Returns a node constructor based on type name
  18292. * @param type defines the type name
  18293. * @param name defines the new node name
  18294. * @param scene defines the hosting scene
  18295. * @param options defines optional options to transmit to constructors
  18296. * @returns the new constructor or null
  18297. */
  18298. Node.Construct = function (type, name, scene, options) {
  18299. var constructorFunc = this._NodeConstructors[type];
  18300. if (!constructorFunc) {
  18301. return null;
  18302. }
  18303. return constructorFunc(name, scene, options);
  18304. };
  18305. /**
  18306. * Gets a boolean indicating if the node has been disposed
  18307. * @returns true if the node was disposed
  18308. */
  18309. Node.prototype.isDisposed = function () {
  18310. return this._isDisposed;
  18311. };
  18312. Object.defineProperty(Node.prototype, "parent", {
  18313. get: function () {
  18314. return this._parentNode;
  18315. },
  18316. /**
  18317. * Gets or sets the parent of the node
  18318. */
  18319. set: function (parent) {
  18320. if (this._parentNode === parent) {
  18321. return;
  18322. }
  18323. var previousParentNode = this._parentNode;
  18324. // Remove self from list of children of parent
  18325. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  18326. var index = this._parentNode._children.indexOf(this);
  18327. if (index !== -1) {
  18328. this._parentNode._children.splice(index, 1);
  18329. }
  18330. if (!parent) {
  18331. this.addToSceneRootNodes();
  18332. }
  18333. }
  18334. // Store new parent
  18335. this._parentNode = parent;
  18336. // Add as child to new parent
  18337. if (this._parentNode) {
  18338. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  18339. this._parentNode._children = new Array();
  18340. }
  18341. this._parentNode._children.push(this);
  18342. if (!previousParentNode) {
  18343. this.removeFromSceneRootNodes();
  18344. }
  18345. }
  18346. // Enabled state
  18347. this._syncParentEnabledState();
  18348. },
  18349. enumerable: true,
  18350. configurable: true
  18351. });
  18352. Node.prototype.addToSceneRootNodes = function () {
  18353. if (this._sceneRootNodesIndex === -1) {
  18354. this._sceneRootNodesIndex = this._scene.rootNodes.length;
  18355. this._scene.rootNodes.push(this);
  18356. }
  18357. };
  18358. Node.prototype.removeFromSceneRootNodes = function () {
  18359. if (this._sceneRootNodesIndex !== -1) {
  18360. var rootNodes = this._scene.rootNodes;
  18361. var lastIdx = rootNodes.length - 1;
  18362. rootNodes[this._sceneRootNodesIndex] = rootNodes[lastIdx];
  18363. rootNodes[this._sceneRootNodesIndex]._sceneRootNodesIndex = this._sceneRootNodesIndex;
  18364. this._scene.rootNodes.pop();
  18365. this._sceneRootNodesIndex = -1;
  18366. }
  18367. };
  18368. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  18369. /**
  18370. * Gets or sets the animation properties override
  18371. */
  18372. get: function () {
  18373. if (!this._animationPropertiesOverride) {
  18374. return this._scene.animationPropertiesOverride;
  18375. }
  18376. return this._animationPropertiesOverride;
  18377. },
  18378. set: function (value) {
  18379. this._animationPropertiesOverride = value;
  18380. },
  18381. enumerable: true,
  18382. configurable: true
  18383. });
  18384. /**
  18385. * Gets a string idenfifying the name of the class
  18386. * @returns "Node" string
  18387. */
  18388. Node.prototype.getClassName = function () {
  18389. return "Node";
  18390. };
  18391. Object.defineProperty(Node.prototype, "onDispose", {
  18392. /**
  18393. * Sets a callback that will be raised when the node will be disposed
  18394. */
  18395. set: function (callback) {
  18396. if (this._onDisposeObserver) {
  18397. this.onDisposeObservable.remove(this._onDisposeObserver);
  18398. }
  18399. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18400. },
  18401. enumerable: true,
  18402. configurable: true
  18403. });
  18404. /**
  18405. * Gets the scene of the node
  18406. * @returns a {BABYLON.Scene}
  18407. */
  18408. Node.prototype.getScene = function () {
  18409. return this._scene;
  18410. };
  18411. /**
  18412. * Gets the engine of the node
  18413. * @returns a {BABYLON.Engine}
  18414. */
  18415. Node.prototype.getEngine = function () {
  18416. return this._scene.getEngine();
  18417. };
  18418. /**
  18419. * Attach a behavior to the node
  18420. * @see http://doc.babylonjs.com/features/behaviour
  18421. * @param behavior defines the behavior to attach
  18422. * @param attachImmediately defines that the behavior must be attached even if the scene is still loading
  18423. * @returns the current Node
  18424. */
  18425. Node.prototype.addBehavior = function (behavior, attachImmediately) {
  18426. var _this = this;
  18427. if (attachImmediately === void 0) { attachImmediately = false; }
  18428. var index = this._behaviors.indexOf(behavior);
  18429. if (index !== -1) {
  18430. return this;
  18431. }
  18432. behavior.init();
  18433. if (this._scene.isLoading && !attachImmediately) {
  18434. // We defer the attach when the scene will be loaded
  18435. this._scene.onDataLoadedObservable.addOnce(function () {
  18436. behavior.attach(_this);
  18437. });
  18438. }
  18439. else {
  18440. behavior.attach(this);
  18441. }
  18442. this._behaviors.push(behavior);
  18443. return this;
  18444. };
  18445. /**
  18446. * Remove an attached behavior
  18447. * @see http://doc.babylonjs.com/features/behaviour
  18448. * @param behavior defines the behavior to attach
  18449. * @returns the current Node
  18450. */
  18451. Node.prototype.removeBehavior = function (behavior) {
  18452. var index = this._behaviors.indexOf(behavior);
  18453. if (index === -1) {
  18454. return this;
  18455. }
  18456. this._behaviors[index].detach();
  18457. this._behaviors.splice(index, 1);
  18458. return this;
  18459. };
  18460. Object.defineProperty(Node.prototype, "behaviors", {
  18461. /**
  18462. * Gets the list of attached behaviors
  18463. * @see http://doc.babylonjs.com/features/behaviour
  18464. */
  18465. get: function () {
  18466. return this._behaviors;
  18467. },
  18468. enumerable: true,
  18469. configurable: true
  18470. });
  18471. /**
  18472. * Gets an attached behavior by name
  18473. * @param name defines the name of the behavior to look for
  18474. * @see http://doc.babylonjs.com/features/behaviour
  18475. * @returns null if behavior was not found else the requested behavior
  18476. */
  18477. Node.prototype.getBehaviorByName = function (name) {
  18478. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  18479. var behavior = _a[_i];
  18480. if (behavior.name === name) {
  18481. return behavior;
  18482. }
  18483. }
  18484. return null;
  18485. };
  18486. /**
  18487. * Returns the latest update of the World matrix
  18488. * @returns a Matrix
  18489. */
  18490. Node.prototype.getWorldMatrix = function () {
  18491. if (this._currentRenderId !== this._scene.getRenderId()) {
  18492. this.computeWorldMatrix();
  18493. }
  18494. return this._worldMatrix;
  18495. };
  18496. /** @hidden */
  18497. Node.prototype._getWorldMatrixDeterminant = function () {
  18498. return this._worldMatrixDeterminant;
  18499. };
  18500. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  18501. /**
  18502. * Returns directly the latest state of the mesh World matrix.
  18503. * A Matrix is returned.
  18504. */
  18505. get: function () {
  18506. return this._worldMatrix;
  18507. },
  18508. enumerable: true,
  18509. configurable: true
  18510. });
  18511. // override it in derived class if you add new variables to the cache
  18512. // and call the parent class method
  18513. /** @hidden */
  18514. Node.prototype._initCache = function () {
  18515. this._cache = {};
  18516. this._cache.parent = undefined;
  18517. };
  18518. /** @hidden */
  18519. Node.prototype.updateCache = function (force) {
  18520. if (!force && this.isSynchronized())
  18521. return;
  18522. this._cache.parent = this.parent;
  18523. this._updateCache();
  18524. };
  18525. // override it in derived class if you add new variables to the cache
  18526. // and call the parent class method if !ignoreParentClass
  18527. /** @hidden */
  18528. Node.prototype._updateCache = function (ignoreParentClass) {
  18529. };
  18530. // override it in derived class if you add new variables to the cache
  18531. /** @hidden */
  18532. Node.prototype._isSynchronized = function () {
  18533. return true;
  18534. };
  18535. /** @hidden */
  18536. Node.prototype._markSyncedWithParent = function () {
  18537. if (this._parentNode) {
  18538. this._parentRenderId = this._parentNode._childRenderId;
  18539. }
  18540. };
  18541. /** @hidden */
  18542. Node.prototype.isSynchronizedWithParent = function () {
  18543. if (!this._parentNode) {
  18544. return true;
  18545. }
  18546. if (this._parentRenderId !== this._parentNode._childRenderId) {
  18547. return false;
  18548. }
  18549. return this._parentNode.isSynchronized();
  18550. };
  18551. /** @hidden */
  18552. Node.prototype.isSynchronized = function () {
  18553. if (this._cache.parent != this._parentNode) {
  18554. this._cache.parent = this._parentNode;
  18555. return false;
  18556. }
  18557. if (this._parentNode && !this.isSynchronizedWithParent()) {
  18558. return false;
  18559. }
  18560. return this._isSynchronized();
  18561. };
  18562. /**
  18563. * Is this node ready to be used/rendered
  18564. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  18565. * @return true if the node is ready
  18566. */
  18567. Node.prototype.isReady = function (completeCheck) {
  18568. if (completeCheck === void 0) { completeCheck = false; }
  18569. return this._isReady;
  18570. };
  18571. /**
  18572. * Is this node enabled?
  18573. * 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
  18574. * @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
  18575. * @return whether this node (and its parent) is enabled
  18576. */
  18577. Node.prototype.isEnabled = function (checkAncestors) {
  18578. if (checkAncestors === void 0) { checkAncestors = true; }
  18579. if (checkAncestors === false) {
  18580. return this._isEnabled;
  18581. }
  18582. if (!this._isEnabled) {
  18583. return false;
  18584. }
  18585. return this._isParentEnabled;
  18586. };
  18587. /** @hidden */
  18588. Node.prototype._syncParentEnabledState = function () {
  18589. this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
  18590. if (this._children) {
  18591. this._children.forEach(function (c) {
  18592. c._syncParentEnabledState(); // Force children to update accordingly
  18593. });
  18594. }
  18595. };
  18596. /**
  18597. * Set the enabled state of this node
  18598. * @param value defines the new enabled state
  18599. */
  18600. Node.prototype.setEnabled = function (value) {
  18601. this._isEnabled = value;
  18602. this._syncParentEnabledState();
  18603. };
  18604. /**
  18605. * Is this node a descendant of the given node?
  18606. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  18607. * @param ancestor defines the parent node to inspect
  18608. * @returns a boolean indicating if this node is a descendant of the given node
  18609. */
  18610. Node.prototype.isDescendantOf = function (ancestor) {
  18611. if (this.parent) {
  18612. if (this.parent === ancestor) {
  18613. return true;
  18614. }
  18615. return this.parent.isDescendantOf(ancestor);
  18616. }
  18617. return false;
  18618. };
  18619. /** @hidden */
  18620. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18621. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18622. if (!this._children) {
  18623. return;
  18624. }
  18625. for (var index = 0; index < this._children.length; index++) {
  18626. var item = this._children[index];
  18627. if (!predicate || predicate(item)) {
  18628. results.push(item);
  18629. }
  18630. if (!directDescendantsOnly) {
  18631. item._getDescendants(results, false, predicate);
  18632. }
  18633. }
  18634. };
  18635. /**
  18636. * Will return all nodes that have this node as ascendant
  18637. * @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
  18638. * @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
  18639. * @return all children nodes of all types
  18640. */
  18641. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18642. var results = new Array();
  18643. this._getDescendants(results, directDescendantsOnly, predicate);
  18644. return results;
  18645. };
  18646. /**
  18647. * Get all child-meshes of this node
  18648. * @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
  18649. * @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
  18650. * @returns an array of {BABYLON.AbstractMesh}
  18651. */
  18652. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18653. var results = [];
  18654. this._getDescendants(results, directDescendantsOnly, function (node) {
  18655. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18656. });
  18657. return results;
  18658. };
  18659. /**
  18660. * Get all child-transformNodes of this node
  18661. * @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
  18662. * @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
  18663. * @returns an array of {BABYLON.TransformNode}
  18664. */
  18665. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18666. var results = [];
  18667. this._getDescendants(results, directDescendantsOnly, function (node) {
  18668. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18669. });
  18670. return results;
  18671. };
  18672. /**
  18673. * Get all direct children of this node
  18674. * @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
  18675. * @returns an array of {BABYLON.Node}
  18676. */
  18677. Node.prototype.getChildren = function (predicate) {
  18678. return this.getDescendants(true, predicate);
  18679. };
  18680. /** @hidden */
  18681. Node.prototype._setReady = function (state) {
  18682. if (state === this._isReady) {
  18683. return;
  18684. }
  18685. if (!state) {
  18686. this._isReady = false;
  18687. return;
  18688. }
  18689. if (this.onReady) {
  18690. this.onReady(this);
  18691. }
  18692. this._isReady = true;
  18693. };
  18694. /**
  18695. * Get an animation by name
  18696. * @param name defines the name of the animation to look for
  18697. * @returns null if not found else the requested animation
  18698. */
  18699. Node.prototype.getAnimationByName = function (name) {
  18700. for (var i = 0; i < this.animations.length; i++) {
  18701. var animation = this.animations[i];
  18702. if (animation.name === name) {
  18703. return animation;
  18704. }
  18705. }
  18706. return null;
  18707. };
  18708. /**
  18709. * Creates an animation range for this node
  18710. * @param name defines the name of the range
  18711. * @param from defines the starting key
  18712. * @param to defines the end key
  18713. */
  18714. Node.prototype.createAnimationRange = function (name, from, to) {
  18715. // check name not already in use
  18716. if (!this._ranges[name]) {
  18717. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18718. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18719. if (this.animations[i]) {
  18720. this.animations[i].createRange(name, from, to);
  18721. }
  18722. }
  18723. }
  18724. };
  18725. /**
  18726. * Delete a specific animation range
  18727. * @param name defines the name of the range to delete
  18728. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18729. */
  18730. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18731. if (deleteFrames === void 0) { deleteFrames = true; }
  18732. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18733. if (this.animations[i]) {
  18734. this.animations[i].deleteRange(name, deleteFrames);
  18735. }
  18736. }
  18737. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18738. };
  18739. /**
  18740. * Get an animation range by name
  18741. * @param name defines the name of the animation range to look for
  18742. * @returns null if not found else the requested animation range
  18743. */
  18744. Node.prototype.getAnimationRange = function (name) {
  18745. return this._ranges[name];
  18746. };
  18747. /**
  18748. * Will start the animation sequence
  18749. * @param name defines the range frames for animation sequence
  18750. * @param loop defines if the animation should loop (false by default)
  18751. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18752. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18753. * @returns the object created for this animation. If range does not exist, it will return null
  18754. */
  18755. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18756. var range = this.getAnimationRange(name);
  18757. if (!range) {
  18758. return null;
  18759. }
  18760. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18761. };
  18762. /**
  18763. * Serialize animation ranges into a JSON compatible object
  18764. * @returns serialization object
  18765. */
  18766. Node.prototype.serializeAnimationRanges = function () {
  18767. var serializationRanges = [];
  18768. for (var name in this._ranges) {
  18769. var localRange = this._ranges[name];
  18770. if (!localRange) {
  18771. continue;
  18772. }
  18773. var range = {};
  18774. range.name = name;
  18775. range.from = localRange.from;
  18776. range.to = localRange.to;
  18777. serializationRanges.push(range);
  18778. }
  18779. return serializationRanges;
  18780. };
  18781. /**
  18782. * Computes the world matrix of the node
  18783. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18784. * @returns the world matrix
  18785. */
  18786. Node.prototype.computeWorldMatrix = function (force) {
  18787. if (!this._worldMatrix) {
  18788. this._worldMatrix = BABYLON.Matrix.Identity();
  18789. }
  18790. return this._worldMatrix;
  18791. };
  18792. /**
  18793. * Releases resources associated with this node.
  18794. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18795. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18796. */
  18797. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18798. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18799. if (!doNotRecurse) {
  18800. var nodes = this.getDescendants(true);
  18801. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18802. var node = nodes_1[_i];
  18803. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18804. }
  18805. }
  18806. else {
  18807. var transformNodes = this.getChildTransformNodes(true);
  18808. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18809. var transformNode = transformNodes_1[_a];
  18810. transformNode.parent = null;
  18811. transformNode.computeWorldMatrix(true);
  18812. }
  18813. }
  18814. if (!this.parent) {
  18815. this.removeFromSceneRootNodes();
  18816. }
  18817. else {
  18818. this.parent = null;
  18819. }
  18820. // Callback
  18821. this.onDisposeObservable.notifyObservers(this);
  18822. this.onDisposeObservable.clear();
  18823. // Behaviors
  18824. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18825. var behavior = _c[_b];
  18826. behavior.detach();
  18827. }
  18828. this._behaviors = [];
  18829. this._isDisposed = true;
  18830. };
  18831. /**
  18832. * Parse animation range data from a serialization object and store them into a given node
  18833. * @param node defines where to store the animation ranges
  18834. * @param parsedNode defines the serialization object to read data from
  18835. * @param scene defines the hosting scene
  18836. */
  18837. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18838. if (parsedNode.ranges) {
  18839. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18840. var data = parsedNode.ranges[index];
  18841. node.createAnimationRange(data.name, data.from, data.to);
  18842. }
  18843. }
  18844. };
  18845. Node._NodeConstructors = {};
  18846. __decorate([
  18847. BABYLON.serialize()
  18848. ], Node.prototype, "name", void 0);
  18849. __decorate([
  18850. BABYLON.serialize()
  18851. ], Node.prototype, "id", void 0);
  18852. __decorate([
  18853. BABYLON.serialize()
  18854. ], Node.prototype, "uniqueId", void 0);
  18855. __decorate([
  18856. BABYLON.serialize()
  18857. ], Node.prototype, "state", void 0);
  18858. __decorate([
  18859. BABYLON.serialize()
  18860. ], Node.prototype, "metadata", void 0);
  18861. return Node;
  18862. }());
  18863. BABYLON.Node = Node;
  18864. })(BABYLON || (BABYLON = {}));
  18865. //# sourceMappingURL=babylon.node.js.map
  18866. var BABYLON;
  18867. (function (BABYLON) {
  18868. // This matrix is used as a value to reset the bounding box.
  18869. var _identityMatrix = BABYLON.Matrix.Identity();
  18870. /**
  18871. * Class used to store bounding sphere information
  18872. */
  18873. var BoundingSphere = /** @class */ (function () {
  18874. /**
  18875. * Creates a new bounding sphere
  18876. * @param min defines the minimum vector (in local space)
  18877. * @param max defines the maximum vector (in local space)
  18878. */
  18879. function BoundingSphere(min, max) {
  18880. /**
  18881. * Gets the center of the bounding sphere in local space
  18882. */
  18883. this.center = BABYLON.Vector3.Zero();
  18884. /**
  18885. * Gets the center of the bounding sphere in world space
  18886. */
  18887. this.centerWorld = BABYLON.Vector3.Zero();
  18888. /**
  18889. * Gets the minimum vector in local space
  18890. */
  18891. this.minimum = BABYLON.Vector3.Zero();
  18892. /**
  18893. * Gets the maximum vector in local space
  18894. */
  18895. this.maximum = BABYLON.Vector3.Zero();
  18896. this.reConstruct(min, max);
  18897. }
  18898. /**
  18899. * Recreates the entire bounding sphere from scratch
  18900. * @param min defines the new minimum vector (in local space)
  18901. * @param max defines the new maximum vector (in local space)
  18902. */
  18903. BoundingSphere.prototype.reConstruct = function (min, max) {
  18904. this.minimum.copyFrom(min);
  18905. this.maximum.copyFrom(max);
  18906. var distance = BABYLON.Vector3.Distance(min, max);
  18907. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  18908. this.radius = distance * 0.5;
  18909. this.centerWorld.set(0, 0, 0);
  18910. this._update(_identityMatrix);
  18911. };
  18912. /**
  18913. * Scale the current bounding sphere by applying a scale factor
  18914. * @param factor defines the scale factor to apply
  18915. * @returns the current bounding box
  18916. */
  18917. BoundingSphere.prototype.scale = function (factor) {
  18918. var newRadius = this.radius * factor;
  18919. var tempRadiusVector = BABYLON.Tmp.Vector3[0].set(newRadius, newRadius, newRadius);
  18920. var min = BABYLON.Tmp.Vector3[1].copyFrom(this.center).subtractInPlace(tempRadiusVector);
  18921. var max = BABYLON.Tmp.Vector3[2].copyFrom(this.center).addInPlace(tempRadiusVector);
  18922. this.reConstruct(min, max);
  18923. return this;
  18924. };
  18925. // Methods
  18926. /** @hidden */
  18927. BoundingSphere.prototype._update = function (world) {
  18928. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18929. var tempVector = BABYLON.Tmp.Vector3[0];
  18930. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, tempVector);
  18931. this.radiusWorld = Math.max(Math.abs(tempVector.x), Math.abs(tempVector.y), Math.abs(tempVector.z)) * this.radius;
  18932. };
  18933. /**
  18934. * Tests if the bounding sphere is intersecting the frustum planes
  18935. * @param frustumPlanes defines the frustum planes to test
  18936. * @returns true if there is an intersection
  18937. */
  18938. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18939. for (var i = 0; i < 6; i++) {
  18940. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18941. return false;
  18942. }
  18943. return true;
  18944. };
  18945. /**
  18946. * Tests if a point is inside the bounding sphere
  18947. * @param point defines the point to test
  18948. * @returns true if the point is inside the bounding sphere
  18949. */
  18950. BoundingSphere.prototype.intersectsPoint = function (point) {
  18951. var x = this.centerWorld.x - point.x;
  18952. var y = this.centerWorld.y - point.y;
  18953. var z = this.centerWorld.z - point.z;
  18954. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18955. if (this.radiusWorld < distance)
  18956. return false;
  18957. return true;
  18958. };
  18959. // Statics
  18960. /**
  18961. * Checks if two sphere intersct
  18962. * @param sphere0 sphere 0
  18963. * @param sphere1 sphere 1
  18964. * @returns true if the speres intersect
  18965. */
  18966. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18967. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18968. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18969. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18970. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18971. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18972. return false;
  18973. return true;
  18974. };
  18975. return BoundingSphere;
  18976. }());
  18977. BABYLON.BoundingSphere = BoundingSphere;
  18978. })(BABYLON || (BABYLON = {}));
  18979. //# sourceMappingURL=babylon.boundingSphere.js.map
  18980. var BABYLON;
  18981. (function (BABYLON) {
  18982. /**
  18983. * Class used to store bounding box information
  18984. */
  18985. var BoundingBox = /** @class */ (function () {
  18986. /**
  18987. * Creates a new bounding box
  18988. * @param min defines the minimum vector (in local space)
  18989. * @param max defines the maximum vector (in local space)
  18990. */
  18991. function BoundingBox(min, max) {
  18992. /**
  18993. * Gets the 8 vectors representing the bounding box in local space
  18994. */
  18995. this.vectors = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18996. /**
  18997. * Gets the center of the bounding box in local space
  18998. */
  18999. this.center = BABYLON.Vector3.Zero();
  19000. /**
  19001. * Gets the center of the bounding box in world space
  19002. */
  19003. this.centerWorld = BABYLON.Vector3.Zero();
  19004. /**
  19005. * Gets the extend size in local space
  19006. */
  19007. this.extendSize = BABYLON.Vector3.Zero();
  19008. /**
  19009. * Gets the extend size in world space
  19010. */
  19011. this.extendSizeWorld = BABYLON.Vector3.Zero();
  19012. /**
  19013. * Gets the OBB (object bounding box) directions
  19014. */
  19015. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  19016. /**
  19017. * Gets the 8 vectors representing the bounding box in world space
  19018. */
  19019. this.vectorsWorld = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  19020. /**
  19021. * Gets the minimum vector in world space
  19022. */
  19023. this.minimumWorld = BABYLON.Vector3.Zero();
  19024. /**
  19025. * Gets the maximum vector in world space
  19026. */
  19027. this.maximumWorld = BABYLON.Vector3.Zero();
  19028. /**
  19029. * Gets the minimum vector in local space
  19030. */
  19031. this.minimum = BABYLON.Vector3.Zero();
  19032. /**
  19033. * Gets the maximum vector in local space
  19034. */
  19035. this.maximum = BABYLON.Vector3.Zero();
  19036. this.reConstruct(min, max);
  19037. }
  19038. ;
  19039. // Methods
  19040. /**
  19041. * Recreates the entire bounding box from scratch
  19042. * @param min defines the new minimum vector (in local space)
  19043. * @param max defines the new maximum vector (in local space)
  19044. */
  19045. BoundingBox.prototype.reConstruct = function (min, max) {
  19046. this.minimum.copyFrom(min);
  19047. this.maximum.copyFrom(max);
  19048. // Bounding vectors
  19049. this.vectors[0].copyFrom(this.minimum);
  19050. this.vectors[1].copyFrom(this.maximum);
  19051. this.vectors[2].copyFrom(this.minimum);
  19052. this.vectors[3].copyFrom(this.minimum);
  19053. this.vectors[4].copyFrom(this.minimum);
  19054. this.vectors[5].copyFrom(this.maximum);
  19055. this.vectors[6].copyFrom(this.maximum);
  19056. this.vectors[7].copyFrom(this.maximum);
  19057. this.vectors[2].x = this.maximum.x;
  19058. this.vectors[3].y = this.maximum.y;
  19059. this.vectors[4].z = this.maximum.z;
  19060. this.vectors[5].z = this.minimum.z;
  19061. this.vectors[6].x = this.minimum.x;
  19062. this.vectors[7].y = this.minimum.y;
  19063. // OBB
  19064. this.center.copyFrom(this.maximum).addInPlace(this.minimum).scaleInPlace(0.5);
  19065. this.extendSize.copyFrom(this.maximum).subtractInPlace(this.minimum).scaleInPlace(0.5);
  19066. for (var index = 0; index < 3; index++) {
  19067. this.directions[index].copyFromFloats(0, 0, 0);
  19068. }
  19069. // World
  19070. for (var index = 0; index < 8; index++) {
  19071. this.vectorsWorld[index].copyFromFloats(0, 0, 0);
  19072. }
  19073. this.minimumWorld.copyFromFloats(0, 0, 0);
  19074. this.maximumWorld.copyFromFloats(0, 0, 0);
  19075. this.centerWorld.copyFromFloats(0, 0, 0);
  19076. this.extendSizeWorld.copyFromFloats(0, 0, 0);
  19077. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  19078. };
  19079. /**
  19080. * Scale the current bounding box by applying a scale factor
  19081. * @param factor defines the scale factor to apply
  19082. * @returns the current bounding box
  19083. */
  19084. BoundingBox.prototype.scale = function (factor) {
  19085. var diff = BABYLON.Tmp.Vector3[0].copyFrom(this.maximum).subtractInPlace(this.minimum);
  19086. var distance = diff.length() * factor;
  19087. diff.normalize();
  19088. var newRadius = diff.scaleInPlace(distance * 0.5);
  19089. var min = BABYLON.Tmp.Vector3[1].copyFrom(this.center).subtractInPlace(newRadius);
  19090. var max = BABYLON.Tmp.Vector3[2].copyFrom(this.center).addInPlace(newRadius);
  19091. this.reConstruct(min, max);
  19092. return this;
  19093. };
  19094. /**
  19095. * Gets the world matrix of the bounding box
  19096. * @returns a matrix
  19097. */
  19098. BoundingBox.prototype.getWorldMatrix = function () {
  19099. return this._worldMatrix;
  19100. };
  19101. /**
  19102. * Sets the world matrix stored in the bounding box
  19103. * @param matrix defines the matrix to store
  19104. * @returns current bounding box
  19105. */
  19106. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  19107. this._worldMatrix.copyFrom(matrix);
  19108. return this;
  19109. };
  19110. /** @hidden */
  19111. BoundingBox.prototype._update = function (world) {
  19112. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  19113. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  19114. for (var index = 0; index < 8; index++) {
  19115. var v = this.vectorsWorld[index];
  19116. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  19117. this.minimumWorld.minimizeInPlace(v);
  19118. this.maximumWorld.maximizeInPlace(v);
  19119. }
  19120. // Extend
  19121. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  19122. this.extendSizeWorld.scaleInPlace(0.5);
  19123. // OBB
  19124. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  19125. this.centerWorld.scaleInPlace(0.5);
  19126. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  19127. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  19128. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  19129. this._worldMatrix = world;
  19130. };
  19131. /**
  19132. * Tests if the bounding box is intersecting the frustum planes
  19133. * @param frustumPlanes defines the frustum planes to test
  19134. * @returns true if there is an intersection
  19135. */
  19136. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  19137. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  19138. };
  19139. /**
  19140. * Tests if the bounding box is entirely inside the frustum planes
  19141. * @param frustumPlanes defines the frustum planes to test
  19142. * @returns true if there is an inclusion
  19143. */
  19144. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19145. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  19146. };
  19147. /**
  19148. * Tests if a point is inside the bounding box
  19149. * @param point defines the point to test
  19150. * @returns true if the point is inside the bounding box
  19151. */
  19152. BoundingBox.prototype.intersectsPoint = function (point) {
  19153. var delta = -BABYLON.Epsilon;
  19154. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  19155. return false;
  19156. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  19157. return false;
  19158. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  19159. return false;
  19160. return true;
  19161. };
  19162. /**
  19163. * Tests if the bounding box intersects with a bounding sphere
  19164. * @param sphere defines the sphere to test
  19165. * @returns true if there is an intersection
  19166. */
  19167. BoundingBox.prototype.intersectsSphere = function (sphere) {
  19168. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  19169. };
  19170. /**
  19171. * Tests if the bounding box intersects with a box defined by a min and max vectors
  19172. * @param min defines the min vector to use
  19173. * @param max defines the max vector to use
  19174. * @returns true if there is an intersection
  19175. */
  19176. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  19177. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  19178. return false;
  19179. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  19180. return false;
  19181. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  19182. return false;
  19183. return true;
  19184. };
  19185. // Statics
  19186. /**
  19187. * Tests if two bounding boxes are intersections
  19188. * @param box0 defines the first box to test
  19189. * @param box1 defines the second box to test
  19190. * @returns true if there is an intersection
  19191. */
  19192. BoundingBox.Intersects = function (box0, box1) {
  19193. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  19194. return false;
  19195. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  19196. return false;
  19197. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  19198. return false;
  19199. return true;
  19200. };
  19201. /**
  19202. * Tests if a bounding box defines by a min/max vectors intersects a sphere
  19203. * @param minPoint defines the minimum vector of the bounding box
  19204. * @param maxPoint defines the maximum vector of the bounding box
  19205. * @param sphereCenter defines the sphere center
  19206. * @param sphereRadius defines the sphere radius
  19207. * @returns true if there is an intersection
  19208. */
  19209. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  19210. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  19211. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  19212. return (num <= (sphereRadius * sphereRadius));
  19213. };
  19214. /**
  19215. * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes
  19216. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19217. * @param frustumPlanes defines the frustum planes to test
  19218. * @return true if there is an inclusion
  19219. */
  19220. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  19221. for (var p = 0; p < 6; p++) {
  19222. for (var i = 0; i < 8; i++) {
  19223. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  19224. return false;
  19225. }
  19226. }
  19227. }
  19228. return true;
  19229. };
  19230. /**
  19231. * Tests if a bounding box defined with 8 vectors intersects frustum planes
  19232. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19233. * @param frustumPlanes defines the frustum planes to test
  19234. * @return true if there is an intersection
  19235. */
  19236. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  19237. for (var p = 0; p < 6; p++) {
  19238. var inCount = 8;
  19239. for (var i = 0; i < 8; i++) {
  19240. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  19241. --inCount;
  19242. }
  19243. else {
  19244. break;
  19245. }
  19246. }
  19247. if (inCount === 0)
  19248. return false;
  19249. }
  19250. return true;
  19251. };
  19252. return BoundingBox;
  19253. }());
  19254. BABYLON.BoundingBox = BoundingBox;
  19255. })(BABYLON || (BABYLON = {}));
  19256. //# sourceMappingURL=babylon.boundingBox.js.map
  19257. var BABYLON;
  19258. (function (BABYLON) {
  19259. var computeBoxExtents = function (axis, box) {
  19260. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  19261. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  19262. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  19263. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  19264. var r = r0 + r1 + r2;
  19265. return {
  19266. min: p - r,
  19267. max: p + r
  19268. };
  19269. };
  19270. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  19271. var axisOverlap = function (axis, box0, box1) {
  19272. var result0 = computeBoxExtents(axis, box0);
  19273. var result1 = computeBoxExtents(axis, box1);
  19274. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  19275. };
  19276. /**
  19277. * Info for a bounding data of a mesh
  19278. */
  19279. var BoundingInfo = /** @class */ (function () {
  19280. /**
  19281. * Constructs bounding info
  19282. * @param minimum min vector of the bounding box/sphere
  19283. * @param maximum max vector of the bounding box/sphere
  19284. */
  19285. function BoundingInfo(minimum, maximum) {
  19286. this._isLocked = false;
  19287. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  19288. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  19289. }
  19290. Object.defineProperty(BoundingInfo.prototype, "minimum", {
  19291. /**
  19292. * min vector of the bounding box/sphere
  19293. */
  19294. get: function () {
  19295. return this.boundingBox.minimum;
  19296. },
  19297. enumerable: true,
  19298. configurable: true
  19299. });
  19300. Object.defineProperty(BoundingInfo.prototype, "maximum", {
  19301. /**
  19302. * max vector of the bounding box/sphere
  19303. */
  19304. get: function () {
  19305. return this.boundingBox.maximum;
  19306. },
  19307. enumerable: true,
  19308. configurable: true
  19309. });
  19310. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  19311. /**
  19312. * If the info is locked and won't be updated to avoid perf overhead
  19313. */
  19314. get: function () {
  19315. return this._isLocked;
  19316. },
  19317. set: function (value) {
  19318. this._isLocked = value;
  19319. },
  19320. enumerable: true,
  19321. configurable: true
  19322. });
  19323. // Methods
  19324. /**
  19325. * Updates the boudning sphere and box
  19326. * @param world world matrix to be used to update
  19327. */
  19328. BoundingInfo.prototype.update = function (world) {
  19329. if (this._isLocked) {
  19330. return;
  19331. }
  19332. this.boundingBox._update(world);
  19333. this.boundingSphere._update(world);
  19334. };
  19335. /**
  19336. * Recreate the bounding info to be centered around a specific point given a specific extend.
  19337. * @param center New center of the bounding info
  19338. * @param extend New extend of the bounding info
  19339. * @returns the current bounding info
  19340. */
  19341. BoundingInfo.prototype.centerOn = function (center, extend) {
  19342. var minimum = BABYLON.Tmp.Vector3[0].copyFrom(center).subtractInPlace(extend);
  19343. var maximum = BABYLON.Tmp.Vector3[1].copyFrom(center).addInPlace(extend);
  19344. this.boundingBox.reConstruct(minimum, maximum);
  19345. this.boundingSphere.reConstruct(minimum, maximum);
  19346. return this;
  19347. };
  19348. /**
  19349. * Scale the current bounding info by applying a scale factor
  19350. * @param factor defines the scale factor to apply
  19351. * @returns the current bounding info
  19352. */
  19353. BoundingInfo.prototype.scale = function (factor) {
  19354. this.boundingBox.scale(factor);
  19355. this.boundingSphere.scale(factor);
  19356. return this;
  19357. };
  19358. /**
  19359. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  19360. * @param frustumPlanes defines the frustum to test
  19361. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  19362. * @returns true if the bounding info is in the frustum planes
  19363. */
  19364. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  19365. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  19366. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  19367. return false;
  19368. }
  19369. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  19370. return true;
  19371. }
  19372. return this.boundingBox.isInFrustum(frustumPlanes);
  19373. };
  19374. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  19375. /**
  19376. * Gets the world distance between the min and max points of the bounding box
  19377. */
  19378. get: function () {
  19379. var boundingBox = this.boundingBox;
  19380. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  19381. return size.length();
  19382. },
  19383. enumerable: true,
  19384. configurable: true
  19385. });
  19386. /**
  19387. * Checks if a cullable object (mesh...) is in the camera frustum
  19388. * Unlike isInFrustum this cheks the full bounding box
  19389. * @param frustumPlanes Camera near/planes
  19390. * @returns true if the object is in frustum otherwise false
  19391. */
  19392. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19393. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  19394. };
  19395. /** @hidden */
  19396. BoundingInfo.prototype._checkCollision = function (collider) {
  19397. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  19398. };
  19399. /**
  19400. * Checks if a point is inside the bounding box and bounding sphere or the mesh
  19401. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19402. * @param point the point to check intersection with
  19403. * @returns if the point intersects
  19404. */
  19405. BoundingInfo.prototype.intersectsPoint = function (point) {
  19406. if (!this.boundingSphere.centerWorld) {
  19407. return false;
  19408. }
  19409. if (!this.boundingSphere.intersectsPoint(point)) {
  19410. return false;
  19411. }
  19412. if (!this.boundingBox.intersectsPoint(point)) {
  19413. return false;
  19414. }
  19415. return true;
  19416. };
  19417. /**
  19418. * Checks if another bounding info intersects the bounding box and bounding sphere or the mesh
  19419. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19420. * @param boundingInfo the bounding info to check intersection with
  19421. * @param precise if the intersection should be done using OBB
  19422. * @returns if the bounding info intersects
  19423. */
  19424. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  19425. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  19426. return false;
  19427. }
  19428. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  19429. return false;
  19430. }
  19431. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  19432. return false;
  19433. }
  19434. if (!precise) {
  19435. return true;
  19436. }
  19437. var box0 = this.boundingBox;
  19438. var box1 = boundingInfo.boundingBox;
  19439. if (!axisOverlap(box0.directions[0], box0, box1))
  19440. return false;
  19441. if (!axisOverlap(box0.directions[1], box0, box1))
  19442. return false;
  19443. if (!axisOverlap(box0.directions[2], box0, box1))
  19444. return false;
  19445. if (!axisOverlap(box1.directions[0], box0, box1))
  19446. return false;
  19447. if (!axisOverlap(box1.directions[1], box0, box1))
  19448. return false;
  19449. if (!axisOverlap(box1.directions[2], box0, box1))
  19450. return false;
  19451. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  19452. return false;
  19453. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  19454. return false;
  19455. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  19456. return false;
  19457. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  19458. return false;
  19459. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  19460. return false;
  19461. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  19462. return false;
  19463. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  19464. return false;
  19465. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  19466. return false;
  19467. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  19468. return false;
  19469. return true;
  19470. };
  19471. return BoundingInfo;
  19472. }());
  19473. BABYLON.BoundingInfo = BoundingInfo;
  19474. })(BABYLON || (BABYLON = {}));
  19475. //# sourceMappingURL=babylon.boundingInfo.js.map
  19476. var BABYLON;
  19477. (function (BABYLON) {
  19478. var TransformNode = /** @class */ (function (_super) {
  19479. __extends(TransformNode, _super);
  19480. function TransformNode(name, scene, isPure) {
  19481. if (scene === void 0) { scene = null; }
  19482. if (isPure === void 0) { isPure = true; }
  19483. var _this = _super.call(this, name, scene) || this;
  19484. _this._forward = new BABYLON.Vector3(0, 0, 1);
  19485. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  19486. _this._up = new BABYLON.Vector3(0, 1, 0);
  19487. _this._right = new BABYLON.Vector3(1, 0, 0);
  19488. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  19489. // Properties
  19490. _this._position = BABYLON.Vector3.Zero();
  19491. _this._rotation = BABYLON.Vector3.Zero();
  19492. _this._scaling = BABYLON.Vector3.One();
  19493. _this._isDirty = false;
  19494. /**
  19495. * Set the billboard mode. Default is 0.
  19496. *
  19497. * | Value | Type | Description |
  19498. * | --- | --- | --- |
  19499. * | 0 | BILLBOARDMODE_NONE | |
  19500. * | 1 | BILLBOARDMODE_X | |
  19501. * | 2 | BILLBOARDMODE_Y | |
  19502. * | 4 | BILLBOARDMODE_Z | |
  19503. * | 7 | BILLBOARDMODE_ALL | |
  19504. *
  19505. */
  19506. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  19507. _this.scalingDeterminant = 1;
  19508. _this.infiniteDistance = false;
  19509. /**
  19510. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  19511. * By default the system will update normals to compensate
  19512. */
  19513. _this.ignoreNonUniformScaling = false;
  19514. _this._localWorld = BABYLON.Matrix.Zero();
  19515. _this._absolutePosition = BABYLON.Vector3.Zero();
  19516. _this._pivotMatrix = BABYLON.Matrix.Identity();
  19517. _this._postMultiplyPivotMatrix = false;
  19518. _this._isWorldMatrixFrozen = false;
  19519. /**
  19520. * An event triggered after the world matrix is updated
  19521. */
  19522. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  19523. _this._nonUniformScaling = false;
  19524. if (isPure) {
  19525. _this.getScene().addTransformNode(_this);
  19526. }
  19527. return _this;
  19528. }
  19529. /**
  19530. * Gets a string identifying the name of the class
  19531. * @returns "TransformNode" string
  19532. */
  19533. TransformNode.prototype.getClassName = function () {
  19534. return "TransformNode";
  19535. };
  19536. Object.defineProperty(TransformNode.prototype, "position", {
  19537. /**
  19538. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  19539. */
  19540. get: function () {
  19541. return this._position;
  19542. },
  19543. set: function (newPosition) {
  19544. this._position = newPosition;
  19545. this._isDirty = true;
  19546. },
  19547. enumerable: true,
  19548. configurable: true
  19549. });
  19550. Object.defineProperty(TransformNode.prototype, "rotation", {
  19551. /**
  19552. * 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)).
  19553. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  19554. */
  19555. get: function () {
  19556. return this._rotation;
  19557. },
  19558. set: function (newRotation) {
  19559. this._rotation = newRotation;
  19560. this._isDirty = true;
  19561. },
  19562. enumerable: true,
  19563. configurable: true
  19564. });
  19565. Object.defineProperty(TransformNode.prototype, "scaling", {
  19566. /**
  19567. * 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)).
  19568. */
  19569. get: function () {
  19570. return this._scaling;
  19571. },
  19572. set: function (newScaling) {
  19573. this._scaling = newScaling;
  19574. this._isDirty = true;
  19575. },
  19576. enumerable: true,
  19577. configurable: true
  19578. });
  19579. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  19580. /**
  19581. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  19582. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  19583. */
  19584. get: function () {
  19585. return this._rotationQuaternion;
  19586. },
  19587. set: function (quaternion) {
  19588. this._rotationQuaternion = quaternion;
  19589. //reset the rotation vector.
  19590. if (quaternion && this.rotation.length()) {
  19591. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  19592. }
  19593. },
  19594. enumerable: true,
  19595. configurable: true
  19596. });
  19597. Object.defineProperty(TransformNode.prototype, "forward", {
  19598. /**
  19599. * The forward direction of that transform in world space.
  19600. */
  19601. get: function () {
  19602. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  19603. },
  19604. enumerable: true,
  19605. configurable: true
  19606. });
  19607. Object.defineProperty(TransformNode.prototype, "up", {
  19608. /**
  19609. * The up direction of that transform in world space.
  19610. */
  19611. get: function () {
  19612. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  19613. },
  19614. enumerable: true,
  19615. configurable: true
  19616. });
  19617. Object.defineProperty(TransformNode.prototype, "right", {
  19618. /**
  19619. * The right direction of that transform in world space.
  19620. */
  19621. get: function () {
  19622. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  19623. },
  19624. enumerable: true,
  19625. configurable: true
  19626. });
  19627. /**
  19628. * Copies the parameter passed Matrix into the mesh Pose matrix.
  19629. * Returns the TransformNode.
  19630. */
  19631. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  19632. this._poseMatrix.copyFrom(matrix);
  19633. return this;
  19634. };
  19635. /**
  19636. * Returns the mesh Pose matrix.
  19637. * Returned object : Matrix
  19638. */
  19639. TransformNode.prototype.getPoseMatrix = function () {
  19640. return this._poseMatrix;
  19641. };
  19642. /** @hidden */
  19643. TransformNode.prototype._isSynchronized = function () {
  19644. if (this._isDirty) {
  19645. return false;
  19646. }
  19647. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  19648. return false;
  19649. if (this._cache.pivotMatrixUpdated) {
  19650. return false;
  19651. }
  19652. if (this.infiniteDistance) {
  19653. return false;
  19654. }
  19655. if (!this._cache.position.equals(this._position))
  19656. return false;
  19657. if (this._rotationQuaternion) {
  19658. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion))
  19659. return false;
  19660. }
  19661. if (!this._cache.rotation.equals(this._rotation))
  19662. return false;
  19663. if (!this._cache.scaling.equals(this._scaling))
  19664. return false;
  19665. return true;
  19666. };
  19667. /** @hidden */
  19668. TransformNode.prototype._initCache = function () {
  19669. _super.prototype._initCache.call(this);
  19670. this._cache.localMatrixUpdated = false;
  19671. this._cache.position = BABYLON.Vector3.Zero();
  19672. this._cache.scaling = BABYLON.Vector3.Zero();
  19673. this._cache.rotation = BABYLON.Vector3.Zero();
  19674. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  19675. this._cache.billboardMode = -1;
  19676. };
  19677. TransformNode.prototype.markAsDirty = function (property) {
  19678. if (property === "rotation") {
  19679. this.rotationQuaternion = null;
  19680. }
  19681. this._currentRenderId = Number.MAX_VALUE;
  19682. this._isDirty = true;
  19683. return this;
  19684. };
  19685. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  19686. /**
  19687. * Returns the current mesh absolute position.
  19688. * Returns a Vector3.
  19689. */
  19690. get: function () {
  19691. return this._absolutePosition;
  19692. },
  19693. enumerable: true,
  19694. configurable: true
  19695. });
  19696. /**
  19697. * Sets a new matrix to apply before all other transformation
  19698. * @param matrix defines the transform matrix
  19699. * @returns the current TransformNode
  19700. */
  19701. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  19702. return this.setPivotMatrix(matrix, false);
  19703. };
  19704. /**
  19705. * Sets a new pivot matrix to the current node
  19706. * @param matrix defines the new pivot matrix to use
  19707. * @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
  19708. * @returns the current TransformNode
  19709. */
  19710. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  19711. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  19712. this._pivotMatrix = matrix.clone();
  19713. this._cache.pivotMatrixUpdated = true;
  19714. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  19715. if (this._postMultiplyPivotMatrix) {
  19716. if (!this._pivotMatrixInverse) {
  19717. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  19718. }
  19719. else {
  19720. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  19721. }
  19722. }
  19723. return this;
  19724. };
  19725. /**
  19726. * Returns the mesh pivot matrix.
  19727. * Default : Identity.
  19728. * A Matrix is returned.
  19729. */
  19730. TransformNode.prototype.getPivotMatrix = function () {
  19731. return this._pivotMatrix;
  19732. };
  19733. /**
  19734. * Prevents the World matrix to be computed any longer.
  19735. * Returns the TransformNode.
  19736. */
  19737. TransformNode.prototype.freezeWorldMatrix = function () {
  19738. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  19739. this.computeWorldMatrix(true);
  19740. this._isWorldMatrixFrozen = true;
  19741. return this;
  19742. };
  19743. /**
  19744. * Allows back the World matrix computation.
  19745. * Returns the TransformNode.
  19746. */
  19747. TransformNode.prototype.unfreezeWorldMatrix = function () {
  19748. this._isWorldMatrixFrozen = false;
  19749. this.computeWorldMatrix(true);
  19750. return this;
  19751. };
  19752. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  19753. /**
  19754. * True if the World matrix has been frozen.
  19755. * Returns a boolean.
  19756. */
  19757. get: function () {
  19758. return this._isWorldMatrixFrozen;
  19759. },
  19760. enumerable: true,
  19761. configurable: true
  19762. });
  19763. /**
  19764. * Retuns the mesh absolute position in the World.
  19765. * Returns a Vector3.
  19766. */
  19767. TransformNode.prototype.getAbsolutePosition = function () {
  19768. this.computeWorldMatrix();
  19769. return this._absolutePosition;
  19770. };
  19771. /**
  19772. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  19773. * Returns the TransformNode.
  19774. */
  19775. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  19776. if (!absolutePosition) {
  19777. return this;
  19778. }
  19779. var absolutePositionX;
  19780. var absolutePositionY;
  19781. var absolutePositionZ;
  19782. if (absolutePosition.x === undefined) {
  19783. if (arguments.length < 3) {
  19784. return this;
  19785. }
  19786. absolutePositionX = arguments[0];
  19787. absolutePositionY = arguments[1];
  19788. absolutePositionZ = arguments[2];
  19789. }
  19790. else {
  19791. absolutePositionX = absolutePosition.x;
  19792. absolutePositionY = absolutePosition.y;
  19793. absolutePositionZ = absolutePosition.z;
  19794. }
  19795. if (this.parent) {
  19796. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19797. invertParentWorldMatrix.invert();
  19798. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  19799. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  19800. }
  19801. else {
  19802. this.position.x = absolutePositionX;
  19803. this.position.y = absolutePositionY;
  19804. this.position.z = absolutePositionZ;
  19805. }
  19806. return this;
  19807. };
  19808. /**
  19809. * Sets the mesh position in its local space.
  19810. * Returns the TransformNode.
  19811. */
  19812. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  19813. this.computeWorldMatrix();
  19814. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  19815. return this;
  19816. };
  19817. /**
  19818. * Returns the mesh position in the local space from the current World matrix values.
  19819. * Returns a new Vector3.
  19820. */
  19821. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  19822. this.computeWorldMatrix();
  19823. var invLocalWorldMatrix = this._localWorld.clone();
  19824. invLocalWorldMatrix.invert();
  19825. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  19826. };
  19827. /**
  19828. * Translates the mesh along the passed Vector3 in its local space.
  19829. * Returns the TransformNode.
  19830. */
  19831. TransformNode.prototype.locallyTranslate = function (vector3) {
  19832. this.computeWorldMatrix(true);
  19833. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  19834. return this;
  19835. };
  19836. /**
  19837. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  19838. * @param targetPoint the position (must be in same space as current mesh) to look at
  19839. * @param yawCor optional yaw (y-axis) correction in radians
  19840. * @param pitchCor optional pitch (x-axis) correction in radians
  19841. * @param rollCor optional roll (z-axis) correction in radians
  19842. * @param space the choosen space of the target
  19843. * @returns the TransformNode.
  19844. */
  19845. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  19846. if (yawCor === void 0) { yawCor = 0; }
  19847. if (pitchCor === void 0) { pitchCor = 0; }
  19848. if (rollCor === void 0) { rollCor = 0; }
  19849. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19850. var dv = TransformNode._lookAtVectorCache;
  19851. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  19852. targetPoint.subtractToRef(pos, dv);
  19853. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  19854. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  19855. var pitch = Math.atan2(dv.y, len);
  19856. if (this.rotationQuaternion) {
  19857. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  19858. }
  19859. else {
  19860. this.rotation.x = pitch + pitchCor;
  19861. this.rotation.y = yaw + yawCor;
  19862. this.rotation.z = rollCor;
  19863. }
  19864. return this;
  19865. };
  19866. /**
  19867. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19868. * This Vector3 is expressed in the World space.
  19869. */
  19870. TransformNode.prototype.getDirection = function (localAxis) {
  19871. var result = BABYLON.Vector3.Zero();
  19872. this.getDirectionToRef(localAxis, result);
  19873. return result;
  19874. };
  19875. /**
  19876. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19877. * localAxis is expressed in the mesh local space.
  19878. * result is computed in the Wordl space from the mesh World matrix.
  19879. * Returns the TransformNode.
  19880. */
  19881. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19882. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19883. return this;
  19884. };
  19885. /**
  19886. * Sets a new pivot point to the current node
  19887. * @param point defines the new pivot point to use
  19888. * @param space defines if the point is in world or local space (local by default)
  19889. * @returns the current TransformNode
  19890. */
  19891. TransformNode.prototype.setPivotPoint = function (point, space) {
  19892. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19893. if (this.getScene().getRenderId() == 0) {
  19894. this.computeWorldMatrix(true);
  19895. }
  19896. var wm = this.getWorldMatrix();
  19897. if (space == BABYLON.Space.WORLD) {
  19898. var tmat = BABYLON.Tmp.Matrix[0];
  19899. wm.invertToRef(tmat);
  19900. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19901. }
  19902. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19903. };
  19904. /**
  19905. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19906. */
  19907. TransformNode.prototype.getPivotPoint = function () {
  19908. var point = BABYLON.Vector3.Zero();
  19909. this.getPivotPointToRef(point);
  19910. return point;
  19911. };
  19912. /**
  19913. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19914. * Returns the TransformNode.
  19915. */
  19916. TransformNode.prototype.getPivotPointToRef = function (result) {
  19917. result.x = -this._pivotMatrix.m[12];
  19918. result.y = -this._pivotMatrix.m[13];
  19919. result.z = -this._pivotMatrix.m[14];
  19920. return this;
  19921. };
  19922. /**
  19923. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19924. */
  19925. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19926. var point = BABYLON.Vector3.Zero();
  19927. this.getAbsolutePivotPointToRef(point);
  19928. return point;
  19929. };
  19930. /**
  19931. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19932. * Returns the TransformNode.
  19933. */
  19934. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19935. result.x = this._pivotMatrix.m[12];
  19936. result.y = this._pivotMatrix.m[13];
  19937. result.z = this._pivotMatrix.m[14];
  19938. this.getPivotPointToRef(result);
  19939. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19940. return this;
  19941. };
  19942. /**
  19943. * Defines the passed node as the parent of the current node.
  19944. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19945. * Returns the TransformNode.
  19946. */
  19947. TransformNode.prototype.setParent = function (node) {
  19948. if (!node && !this.parent) {
  19949. return this;
  19950. }
  19951. if (!node) {
  19952. var rotation = BABYLON.Tmp.Quaternion[0];
  19953. var position = BABYLON.Tmp.Vector3[0];
  19954. var scale = BABYLON.Tmp.Vector3[1];
  19955. if (this.parent && this.parent.computeWorldMatrix) {
  19956. this.parent.computeWorldMatrix(true);
  19957. }
  19958. this.computeWorldMatrix(true);
  19959. this.getWorldMatrix().decompose(scale, rotation, position);
  19960. if (this.rotationQuaternion) {
  19961. this.rotationQuaternion.copyFrom(rotation);
  19962. }
  19963. else {
  19964. rotation.toEulerAnglesToRef(this.rotation);
  19965. }
  19966. this.scaling.x = scale.x;
  19967. this.scaling.y = scale.y;
  19968. this.scaling.z = scale.z;
  19969. this.position.x = position.x;
  19970. this.position.y = position.y;
  19971. this.position.z = position.z;
  19972. }
  19973. else {
  19974. var rotation = BABYLON.Tmp.Quaternion[0];
  19975. var position = BABYLON.Tmp.Vector3[0];
  19976. var scale = BABYLON.Tmp.Vector3[1];
  19977. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19978. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19979. this.computeWorldMatrix(true);
  19980. node.computeWorldMatrix(true);
  19981. node.getWorldMatrix().invertToRef(invParentMatrix);
  19982. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19983. diffMatrix.decompose(scale, rotation, position);
  19984. if (this.rotationQuaternion) {
  19985. this.rotationQuaternion.copyFrom(rotation);
  19986. }
  19987. else {
  19988. rotation.toEulerAnglesToRef(this.rotation);
  19989. }
  19990. this.position.x = position.x;
  19991. this.position.y = position.y;
  19992. this.position.z = position.z;
  19993. this.scaling.x = scale.x;
  19994. this.scaling.y = scale.y;
  19995. this.scaling.z = scale.z;
  19996. }
  19997. this.parent = node;
  19998. return this;
  19999. };
  20000. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  20001. get: function () {
  20002. return this._nonUniformScaling;
  20003. },
  20004. enumerable: true,
  20005. configurable: true
  20006. });
  20007. /** @hidden */
  20008. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  20009. if (this._nonUniformScaling === value) {
  20010. return false;
  20011. }
  20012. this._nonUniformScaling = value;
  20013. return true;
  20014. };
  20015. /**
  20016. * Attach the current TransformNode to another TransformNode associated with a bone
  20017. * @param bone Bone affecting the TransformNode
  20018. * @param affectedTransformNode TransformNode associated with the bone
  20019. */
  20020. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  20021. this._transformToBoneReferal = affectedTransformNode;
  20022. this.parent = bone;
  20023. if (bone.getWorldMatrix().determinant() < 0) {
  20024. this.scalingDeterminant *= -1;
  20025. }
  20026. return this;
  20027. };
  20028. TransformNode.prototype.detachFromBone = function () {
  20029. if (!this.parent) {
  20030. return this;
  20031. }
  20032. if (this.parent.getWorldMatrix().determinant() < 0) {
  20033. this.scalingDeterminant *= -1;
  20034. }
  20035. this._transformToBoneReferal = null;
  20036. this.parent = null;
  20037. return this;
  20038. };
  20039. /**
  20040. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  20041. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  20042. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  20043. * The passed axis is also normalized.
  20044. * Returns the TransformNode.
  20045. */
  20046. TransformNode.prototype.rotate = function (axis, amount, space) {
  20047. axis.normalize();
  20048. if (!this.rotationQuaternion) {
  20049. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20050. this.rotation = BABYLON.Vector3.Zero();
  20051. }
  20052. var rotationQuaternion;
  20053. if (!space || space === BABYLON.Space.LOCAL) {
  20054. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  20055. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  20056. }
  20057. else {
  20058. if (this.parent) {
  20059. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  20060. invertParentWorldMatrix.invert();
  20061. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  20062. }
  20063. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  20064. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20065. }
  20066. return this;
  20067. };
  20068. /**
  20069. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  20070. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  20071. * The passed axis is also normalized.
  20072. * Returns the TransformNode.
  20073. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  20074. */
  20075. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  20076. axis.normalize();
  20077. if (!this.rotationQuaternion) {
  20078. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20079. this.rotation.copyFromFloats(0, 0, 0);
  20080. }
  20081. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  20082. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  20083. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  20084. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  20085. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  20086. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  20087. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  20088. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  20089. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20090. return this;
  20091. };
  20092. /**
  20093. * Translates the mesh along the axis vector for the passed distance in the given space.
  20094. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  20095. * Returns the TransformNode.
  20096. */
  20097. TransformNode.prototype.translate = function (axis, distance, space) {
  20098. var displacementVector = axis.scale(distance);
  20099. if (!space || space === BABYLON.Space.LOCAL) {
  20100. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  20101. this.setPositionWithLocalVector(tempV3);
  20102. }
  20103. else {
  20104. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  20105. }
  20106. return this;
  20107. };
  20108. /**
  20109. * Adds a rotation step to the mesh current rotation.
  20110. * x, y, z are Euler angles expressed in radians.
  20111. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  20112. * This means this rotation is made in the mesh local space only.
  20113. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  20114. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  20115. * ```javascript
  20116. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  20117. * ```
  20118. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  20119. * 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.
  20120. * Returns the TransformNode.
  20121. */
  20122. TransformNode.prototype.addRotation = function (x, y, z) {
  20123. var rotationQuaternion;
  20124. if (this.rotationQuaternion) {
  20125. rotationQuaternion = this.rotationQuaternion;
  20126. }
  20127. else {
  20128. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  20129. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  20130. }
  20131. var accumulation = BABYLON.Tmp.Quaternion[0];
  20132. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  20133. rotationQuaternion.multiplyInPlace(accumulation);
  20134. if (!this.rotationQuaternion) {
  20135. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  20136. }
  20137. return this;
  20138. };
  20139. /**
  20140. * Computes the world matrix of the node
  20141. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  20142. * @returns the world matrix
  20143. */
  20144. TransformNode.prototype.computeWorldMatrix = function (force) {
  20145. if (this._isWorldMatrixFrozen) {
  20146. return this._worldMatrix;
  20147. }
  20148. if (!force && this.isSynchronized()) {
  20149. this._currentRenderId = this.getScene().getRenderId();
  20150. return this._worldMatrix;
  20151. }
  20152. this._updateCache();
  20153. this._cache.position.copyFrom(this.position);
  20154. this._cache.scaling.copyFrom(this.scaling);
  20155. this._cache.pivotMatrixUpdated = false;
  20156. this._cache.billboardMode = this.billboardMode;
  20157. this._currentRenderId = this.getScene().getRenderId();
  20158. this._childRenderId = this.getScene().getRenderId();
  20159. this._isDirty = false;
  20160. // Scaling
  20161. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  20162. // Rotation
  20163. //rotate, if quaternion is set and rotation was used
  20164. if (this.rotationQuaternion) {
  20165. var len = this.rotation.length();
  20166. if (len) {
  20167. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  20168. this.rotation.copyFromFloats(0, 0, 0);
  20169. }
  20170. }
  20171. if (this.rotationQuaternion) {
  20172. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  20173. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  20174. }
  20175. else {
  20176. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  20177. this._cache.rotation.copyFrom(this.rotation);
  20178. }
  20179. // Translation
  20180. var camera = this.getScene().activeCamera;
  20181. if (this.infiniteDistance && !this.parent && camera) {
  20182. var cameraWorldMatrix = camera.getWorldMatrix();
  20183. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  20184. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  20185. }
  20186. else {
  20187. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  20188. }
  20189. // Composing transformations
  20190. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  20191. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20192. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  20193. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  20194. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  20195. // Need to decompose each rotation here
  20196. var currentPosition = BABYLON.Tmp.Vector3[3];
  20197. if (this.parent && this.parent.getWorldMatrix) {
  20198. if (this._transformToBoneReferal) {
  20199. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20200. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  20201. }
  20202. else {
  20203. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  20204. }
  20205. }
  20206. else {
  20207. currentPosition.copyFrom(this.position);
  20208. }
  20209. currentPosition.subtractInPlace(camera.globalPosition);
  20210. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  20211. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  20212. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  20213. }
  20214. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  20215. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  20216. }
  20217. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  20218. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  20219. }
  20220. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  20221. }
  20222. else {
  20223. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  20224. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  20225. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  20226. }
  20227. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  20228. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20229. }
  20230. // Post multiply inverse of pivotMatrix
  20231. if (this._postMultiplyPivotMatrix) {
  20232. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  20233. }
  20234. // Local world
  20235. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  20236. // Parent
  20237. if (this.parent && this.parent.getWorldMatrix) {
  20238. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  20239. if (this._transformToBoneReferal) {
  20240. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20241. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  20242. }
  20243. else {
  20244. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  20245. }
  20246. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  20247. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  20248. this._worldMatrix.copyFrom(this._localWorld);
  20249. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  20250. }
  20251. else {
  20252. if (this._transformToBoneReferal) {
  20253. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20254. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  20255. }
  20256. else {
  20257. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  20258. }
  20259. }
  20260. this._markSyncedWithParent();
  20261. }
  20262. else {
  20263. this._worldMatrix.copyFrom(this._localWorld);
  20264. }
  20265. // Normal matrix
  20266. if (!this.ignoreNonUniformScaling) {
  20267. if (this.scaling.isNonUniform) {
  20268. this._updateNonUniformScalingState(true);
  20269. }
  20270. else if (this.parent && this.parent._nonUniformScaling) {
  20271. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  20272. }
  20273. else {
  20274. this._updateNonUniformScalingState(false);
  20275. }
  20276. }
  20277. else {
  20278. this._updateNonUniformScalingState(false);
  20279. }
  20280. this._afterComputeWorldMatrix();
  20281. // Absolute position
  20282. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  20283. // Callbacks
  20284. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  20285. if (!this._poseMatrix) {
  20286. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  20287. }
  20288. // Cache the determinant
  20289. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  20290. return this._worldMatrix;
  20291. };
  20292. TransformNode.prototype._afterComputeWorldMatrix = function () {
  20293. };
  20294. /**
  20295. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  20296. * @param func: callback function to add
  20297. *
  20298. * Returns the TransformNode.
  20299. */
  20300. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  20301. this.onAfterWorldMatrixUpdateObservable.add(func);
  20302. return this;
  20303. };
  20304. /**
  20305. * Removes a registered callback function.
  20306. * Returns the TransformNode.
  20307. */
  20308. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  20309. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  20310. return this;
  20311. };
  20312. /**
  20313. * Clone the current transform node
  20314. * Returns the new transform node
  20315. * @param name Name of the new clone
  20316. * @param newParent New parent for the clone
  20317. * @param doNotCloneChildren Do not clone children hierarchy
  20318. */
  20319. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20320. var _this = this;
  20321. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  20322. result.name = name;
  20323. result.id = name;
  20324. if (newParent) {
  20325. result.parent = newParent;
  20326. }
  20327. if (!doNotCloneChildren) {
  20328. // Children
  20329. var directDescendants = this.getDescendants(true);
  20330. for (var index = 0; index < directDescendants.length; index++) {
  20331. var child = directDescendants[index];
  20332. if (child.clone) {
  20333. child.clone(name + "." + child.name, result);
  20334. }
  20335. }
  20336. }
  20337. return result;
  20338. };
  20339. TransformNode.prototype.serialize = function (currentSerializationObject) {
  20340. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  20341. serializationObject.type = this.getClassName();
  20342. // Parent
  20343. if (this.parent) {
  20344. serializationObject.parentId = this.parent.id;
  20345. }
  20346. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  20347. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20348. }
  20349. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  20350. serializationObject.isEnabled = this.isEnabled();
  20351. // Parent
  20352. if (this.parent) {
  20353. serializationObject.parentId = this.parent.id;
  20354. }
  20355. return serializationObject;
  20356. };
  20357. // Statics
  20358. /**
  20359. * Returns a new TransformNode object parsed from the source provided.
  20360. * The parameter `parsedMesh` is the source.
  20361. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20362. */
  20363. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  20364. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  20365. if (BABYLON.Tags) {
  20366. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  20367. }
  20368. if (parsedTransformNode.localMatrix) {
  20369. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  20370. }
  20371. else if (parsedTransformNode.pivotMatrix) {
  20372. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  20373. }
  20374. transformNode.setEnabled(parsedTransformNode.isEnabled);
  20375. // Parent
  20376. if (parsedTransformNode.parentId) {
  20377. transformNode._waitingParentId = parsedTransformNode.parentId;
  20378. }
  20379. return transformNode;
  20380. };
  20381. /**
  20382. * Releases resources associated with this transform node.
  20383. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20384. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20385. */
  20386. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20387. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20388. // Animations
  20389. this.getScene().stopAnimation(this);
  20390. // Remove from scene
  20391. this.getScene().removeTransformNode(this);
  20392. this.onAfterWorldMatrixUpdateObservable.clear();
  20393. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20394. };
  20395. // Statics
  20396. TransformNode.BILLBOARDMODE_NONE = 0;
  20397. TransformNode.BILLBOARDMODE_X = 1;
  20398. TransformNode.BILLBOARDMODE_Y = 2;
  20399. TransformNode.BILLBOARDMODE_Z = 4;
  20400. TransformNode.BILLBOARDMODE_ALL = 7;
  20401. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  20402. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  20403. __decorate([
  20404. BABYLON.serializeAsVector3("position")
  20405. ], TransformNode.prototype, "_position", void 0);
  20406. __decorate([
  20407. BABYLON.serializeAsVector3("rotation")
  20408. ], TransformNode.prototype, "_rotation", void 0);
  20409. __decorate([
  20410. BABYLON.serializeAsQuaternion("rotationQuaternion")
  20411. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  20412. __decorate([
  20413. BABYLON.serializeAsVector3("scaling")
  20414. ], TransformNode.prototype, "_scaling", void 0);
  20415. __decorate([
  20416. BABYLON.serialize()
  20417. ], TransformNode.prototype, "billboardMode", void 0);
  20418. __decorate([
  20419. BABYLON.serialize()
  20420. ], TransformNode.prototype, "scalingDeterminant", void 0);
  20421. __decorate([
  20422. BABYLON.serialize()
  20423. ], TransformNode.prototype, "infiniteDistance", void 0);
  20424. __decorate([
  20425. BABYLON.serialize()
  20426. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  20427. return TransformNode;
  20428. }(BABYLON.Node));
  20429. BABYLON.TransformNode = TransformNode;
  20430. })(BABYLON || (BABYLON = {}));
  20431. //# sourceMappingURL=babylon.transformNode.js.map
  20432. var BABYLON;
  20433. (function (BABYLON) {
  20434. /** @hidden */
  20435. var _FacetDataStorage = /** @class */ (function () {
  20436. function _FacetDataStorage() {
  20437. this.facetNb = 0; // facet number
  20438. this.partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  20439. this.partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  20440. this.facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  20441. this.facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  20442. this.bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  20443. this.subDiv = {
  20444. max: 1,
  20445. X: 1,
  20446. Y: 1,
  20447. Z: 1
  20448. };
  20449. this.facetDepthSort = false; // is the facet depth sort to be computed
  20450. this.facetDepthSortEnabled = false; // is the facet depth sort initialized
  20451. }
  20452. return _FacetDataStorage;
  20453. }());
  20454. /**
  20455. * Class used to store all common mesh properties
  20456. */
  20457. var AbstractMesh = /** @class */ (function (_super) {
  20458. __extends(AbstractMesh, _super);
  20459. // Constructor
  20460. /**
  20461. * Creates a new AbstractMesh
  20462. * @param name defines the name of the mesh
  20463. * @param scene defines the hosting scene
  20464. */
  20465. function AbstractMesh(name, scene) {
  20466. if (scene === void 0) { scene = null; }
  20467. var _this = _super.call(this, name, scene, false) || this;
  20468. _this._facetData = new _FacetDataStorage();
  20469. /** Gets ot sets the culling strategy to use to find visible meshes */
  20470. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  20471. // Events
  20472. /**
  20473. * An event triggered when this mesh collides with another one
  20474. */
  20475. _this.onCollideObservable = new BABYLON.Observable();
  20476. /**
  20477. * An event triggered when the collision's position changes
  20478. */
  20479. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  20480. /**
  20481. * An event triggered when material is changed
  20482. */
  20483. _this.onMaterialChangedObservable = new BABYLON.Observable();
  20484. // Properties
  20485. /**
  20486. * Gets or sets the orientation for POV movement & rotation
  20487. */
  20488. _this.definedFacingForward = true;
  20489. _this._visibility = 1.0;
  20490. /** Gets or sets the alpha index used to sort transparent meshes
  20491. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  20492. */
  20493. _this.alphaIndex = Number.MAX_VALUE;
  20494. /**
  20495. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  20496. */
  20497. _this.isVisible = true;
  20498. /**
  20499. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  20500. */
  20501. _this.isPickable = true;
  20502. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  20503. _this.showSubMeshesBoundingBox = false;
  20504. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  20505. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  20506. */
  20507. _this.isBlocker = false;
  20508. /**
  20509. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  20510. */
  20511. _this.enablePointerMoveEvents = false;
  20512. /**
  20513. * Specifies the rendering group id for this mesh (0 by default)
  20514. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  20515. */
  20516. _this.renderingGroupId = 0;
  20517. _this._receiveShadows = false;
  20518. /** Defines color to use when rendering outline */
  20519. _this.outlineColor = BABYLON.Color3.Red();
  20520. /** Define width to use when rendering outline */
  20521. _this.outlineWidth = 0.02;
  20522. /** Defines color to use when rendering overlay */
  20523. _this.overlayColor = BABYLON.Color3.Red();
  20524. /** Defines alpha to use when rendering overlay */
  20525. _this.overlayAlpha = 0.5;
  20526. _this._hasVertexAlpha = false;
  20527. _this._useVertexColors = true;
  20528. _this._computeBonesUsingShaders = true;
  20529. _this._numBoneInfluencers = 4;
  20530. _this._applyFog = true;
  20531. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  20532. _this.useOctreeForRenderingSelection = true;
  20533. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  20534. _this.useOctreeForPicking = true;
  20535. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  20536. _this.useOctreeForCollisions = true;
  20537. _this._layerMask = 0x0FFFFFFF;
  20538. /**
  20539. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  20540. */
  20541. _this.alwaysSelectAsActiveMesh = false;
  20542. /**
  20543. * Gets or sets the current action manager
  20544. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  20545. */
  20546. _this.actionManager = null;
  20547. // Collisions
  20548. _this._checkCollisions = false;
  20549. _this._collisionMask = -1;
  20550. _this._collisionGroup = -1;
  20551. /**
  20552. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  20553. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20554. */
  20555. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  20556. /**
  20557. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  20558. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20559. */
  20560. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  20561. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20562. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20563. // Edges
  20564. /**
  20565. * Defines edge width used when edgesRenderer is enabled
  20566. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20567. */
  20568. _this.edgesWidth = 1;
  20569. /**
  20570. * Defines edge color used when edgesRenderer is enabled
  20571. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20572. */
  20573. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  20574. /** @hidden */
  20575. _this._renderId = 0;
  20576. /** @hidden */
  20577. _this._intersectionsInProgress = new Array();
  20578. /** @hidden */
  20579. _this._unIndexed = false;
  20580. /** @hidden */
  20581. _this._lightSources = new Array();
  20582. /**
  20583. * An event triggered when the mesh is rebuilt.
  20584. */
  20585. _this.onRebuildObservable = new BABYLON.Observable();
  20586. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  20587. if (collidedMesh === void 0) { collidedMesh = null; }
  20588. //TODO move this to the collision coordinator!
  20589. if (_this.getScene().workerCollisions)
  20590. newPosition.multiplyInPlace(_this._collider._radius);
  20591. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  20592. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  20593. _this.position.addInPlace(_this._diffPositionForCollisions);
  20594. }
  20595. if (collidedMesh) {
  20596. _this.onCollideObservable.notifyObservers(collidedMesh);
  20597. }
  20598. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  20599. };
  20600. _this.getScene().addMesh(_this);
  20601. _this._resyncLightSources();
  20602. return _this;
  20603. }
  20604. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  20605. /**
  20606. * No billboard
  20607. */
  20608. get: function () {
  20609. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  20610. },
  20611. enumerable: true,
  20612. configurable: true
  20613. });
  20614. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  20615. /** Billboard on X axis */
  20616. get: function () {
  20617. return BABYLON.TransformNode.BILLBOARDMODE_X;
  20618. },
  20619. enumerable: true,
  20620. configurable: true
  20621. });
  20622. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  20623. /** Billboard on Y axis */
  20624. get: function () {
  20625. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  20626. },
  20627. enumerable: true,
  20628. configurable: true
  20629. });
  20630. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  20631. /** Billboard on Z axis */
  20632. get: function () {
  20633. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  20634. },
  20635. enumerable: true,
  20636. configurable: true
  20637. });
  20638. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  20639. /** Billboard on all axes */
  20640. get: function () {
  20641. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  20642. },
  20643. enumerable: true,
  20644. configurable: true
  20645. });
  20646. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  20647. /**
  20648. * Gets the number of facets in the mesh
  20649. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20650. */
  20651. get: function () {
  20652. return this._facetData.facetNb;
  20653. },
  20654. enumerable: true,
  20655. configurable: true
  20656. });
  20657. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  20658. /**
  20659. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  20660. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20661. */
  20662. get: function () {
  20663. return this._facetData.partitioningSubdivisions;
  20664. },
  20665. set: function (nb) {
  20666. this._facetData.partitioningSubdivisions = nb;
  20667. },
  20668. enumerable: true,
  20669. configurable: true
  20670. });
  20671. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  20672. /**
  20673. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  20674. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  20675. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20676. */
  20677. get: function () {
  20678. return this._facetData.partitioningBBoxRatio;
  20679. },
  20680. set: function (ratio) {
  20681. this._facetData.partitioningBBoxRatio = ratio;
  20682. },
  20683. enumerable: true,
  20684. configurable: true
  20685. });
  20686. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  20687. /**
  20688. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  20689. * Works only for updatable meshes.
  20690. * Doesn't work with multi-materials
  20691. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20692. */
  20693. get: function () {
  20694. return this._facetData.facetDepthSort;
  20695. },
  20696. set: function (sort) {
  20697. this._facetData.facetDepthSort = sort;
  20698. },
  20699. enumerable: true,
  20700. configurable: true
  20701. });
  20702. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  20703. /**
  20704. * The location (Vector3) where the facet depth sort must be computed from.
  20705. * By default, the active camera position.
  20706. * Used only when facet depth sort is enabled
  20707. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20708. */
  20709. get: function () {
  20710. return this._facetData.facetDepthSortFrom;
  20711. },
  20712. set: function (location) {
  20713. this._facetData.facetDepthSortFrom = location;
  20714. },
  20715. enumerable: true,
  20716. configurable: true
  20717. });
  20718. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  20719. /**
  20720. * gets a boolean indicating if facetData is enabled
  20721. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20722. */
  20723. get: function () {
  20724. return this._facetData.facetDataEnabled;
  20725. },
  20726. enumerable: true,
  20727. configurable: true
  20728. });
  20729. /** @hidden */
  20730. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  20731. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  20732. return false;
  20733. }
  20734. this._markSubMeshesAsMiscDirty();
  20735. return true;
  20736. };
  20737. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  20738. /** Set a function to call when this mesh collides with another one */
  20739. set: function (callback) {
  20740. if (this._onCollideObserver) {
  20741. this.onCollideObservable.remove(this._onCollideObserver);
  20742. }
  20743. this._onCollideObserver = this.onCollideObservable.add(callback);
  20744. },
  20745. enumerable: true,
  20746. configurable: true
  20747. });
  20748. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  20749. /** Set a function to call when the collision's position changes */
  20750. set: function (callback) {
  20751. if (this._onCollisionPositionChangeObserver) {
  20752. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  20753. }
  20754. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  20755. },
  20756. enumerable: true,
  20757. configurable: true
  20758. });
  20759. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  20760. /**
  20761. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20762. */
  20763. get: function () {
  20764. return this._visibility;
  20765. },
  20766. /**
  20767. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20768. */
  20769. set: function (value) {
  20770. if (this._visibility === value) {
  20771. return;
  20772. }
  20773. this._visibility = value;
  20774. this._markSubMeshesAsMiscDirty();
  20775. },
  20776. enumerable: true,
  20777. configurable: true
  20778. });
  20779. Object.defineProperty(AbstractMesh.prototype, "material", {
  20780. /** Gets or sets current material */
  20781. get: function () {
  20782. return this._material;
  20783. },
  20784. set: function (value) {
  20785. if (this._material === value) {
  20786. return;
  20787. }
  20788. this._material = value;
  20789. if (this.onMaterialChangedObservable.hasObservers) {
  20790. this.onMaterialChangedObservable.notifyObservers(this);
  20791. }
  20792. if (!this.subMeshes) {
  20793. return;
  20794. }
  20795. this._unBindEffect();
  20796. },
  20797. enumerable: true,
  20798. configurable: true
  20799. });
  20800. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  20801. /**
  20802. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  20803. * @see http://doc.babylonjs.com/babylon101/shadows
  20804. */
  20805. get: function () {
  20806. return this._receiveShadows;
  20807. },
  20808. set: function (value) {
  20809. if (this._receiveShadows === value) {
  20810. return;
  20811. }
  20812. this._receiveShadows = value;
  20813. this._markSubMeshesAsLightDirty();
  20814. },
  20815. enumerable: true,
  20816. configurable: true
  20817. });
  20818. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20819. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20820. get: function () {
  20821. return this._hasVertexAlpha;
  20822. },
  20823. set: function (value) {
  20824. if (this._hasVertexAlpha === value) {
  20825. return;
  20826. }
  20827. this._hasVertexAlpha = value;
  20828. this._markSubMeshesAsAttributesDirty();
  20829. this._markSubMeshesAsMiscDirty();
  20830. },
  20831. enumerable: true,
  20832. configurable: true
  20833. });
  20834. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20835. /** 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) */
  20836. get: function () {
  20837. return this._useVertexColors;
  20838. },
  20839. set: function (value) {
  20840. if (this._useVertexColors === value) {
  20841. return;
  20842. }
  20843. this._useVertexColors = value;
  20844. this._markSubMeshesAsAttributesDirty();
  20845. },
  20846. enumerable: true,
  20847. configurable: true
  20848. });
  20849. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20850. /**
  20851. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20852. */
  20853. get: function () {
  20854. return this._computeBonesUsingShaders;
  20855. },
  20856. set: function (value) {
  20857. if (this._computeBonesUsingShaders === value) {
  20858. return;
  20859. }
  20860. this._computeBonesUsingShaders = value;
  20861. this._markSubMeshesAsAttributesDirty();
  20862. },
  20863. enumerable: true,
  20864. configurable: true
  20865. });
  20866. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20867. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20868. get: function () {
  20869. return this._numBoneInfluencers;
  20870. },
  20871. set: function (value) {
  20872. if (this._numBoneInfluencers === value) {
  20873. return;
  20874. }
  20875. this._numBoneInfluencers = value;
  20876. this._markSubMeshesAsAttributesDirty();
  20877. },
  20878. enumerable: true,
  20879. configurable: true
  20880. });
  20881. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20882. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20883. get: function () {
  20884. return this._applyFog;
  20885. },
  20886. set: function (value) {
  20887. if (this._applyFog === value) {
  20888. return;
  20889. }
  20890. this._applyFog = value;
  20891. this._markSubMeshesAsMiscDirty();
  20892. },
  20893. enumerable: true,
  20894. configurable: true
  20895. });
  20896. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20897. /**
  20898. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20899. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20900. */
  20901. get: function () {
  20902. return this._layerMask;
  20903. },
  20904. set: function (value) {
  20905. if (value === this._layerMask) {
  20906. return;
  20907. }
  20908. this._layerMask = value;
  20909. this._resyncLightSources();
  20910. },
  20911. enumerable: true,
  20912. configurable: true
  20913. });
  20914. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20915. /**
  20916. * Gets or sets a collision mask used to mask collisions (default is -1).
  20917. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20918. */
  20919. get: function () {
  20920. return this._collisionMask;
  20921. },
  20922. set: function (mask) {
  20923. this._collisionMask = !isNaN(mask) ? mask : -1;
  20924. },
  20925. enumerable: true,
  20926. configurable: true
  20927. });
  20928. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20929. /**
  20930. * Gets or sets the current collision group mask (-1 by default).
  20931. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20932. */
  20933. get: function () {
  20934. return this._collisionGroup;
  20935. },
  20936. set: function (mask) {
  20937. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20938. },
  20939. enumerable: true,
  20940. configurable: true
  20941. });
  20942. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20943. /** @hidden */
  20944. get: function () {
  20945. return null;
  20946. },
  20947. enumerable: true,
  20948. configurable: true
  20949. });
  20950. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20951. get: function () {
  20952. return this._skeleton;
  20953. },
  20954. /**
  20955. * Gets or sets a skeleton to apply skining transformations
  20956. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20957. */
  20958. set: function (value) {
  20959. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20960. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20961. }
  20962. if (value && value.needInitialSkinMatrix) {
  20963. value._registerMeshWithPoseMatrix(this);
  20964. }
  20965. this._skeleton = value;
  20966. if (!this._skeleton) {
  20967. this._bonesTransformMatrices = null;
  20968. }
  20969. this._markSubMeshesAsAttributesDirty();
  20970. },
  20971. enumerable: true,
  20972. configurable: true
  20973. });
  20974. /**
  20975. * Returns the string "AbstractMesh"
  20976. * @returns "AbstractMesh"
  20977. */
  20978. AbstractMesh.prototype.getClassName = function () {
  20979. return "AbstractMesh";
  20980. };
  20981. /**
  20982. * Gets a string representation of the current mesh
  20983. * @param fullDetails defines a boolean indicating if full details must be included
  20984. * @returns a string representation of the current mesh
  20985. */
  20986. AbstractMesh.prototype.toString = function (fullDetails) {
  20987. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20988. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20989. if (this._skeleton) {
  20990. ret += ", skeleton: " + this._skeleton.name;
  20991. }
  20992. if (fullDetails) {
  20993. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20994. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20995. }
  20996. return ret;
  20997. };
  20998. /** @hidden */
  20999. AbstractMesh.prototype._rebuild = function () {
  21000. this.onRebuildObservable.notifyObservers(this);
  21001. if (this._occlusionQuery) {
  21002. this._occlusionQuery = null;
  21003. }
  21004. if (!this.subMeshes) {
  21005. return;
  21006. }
  21007. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21008. var subMesh = _a[_i];
  21009. subMesh._rebuild();
  21010. }
  21011. };
  21012. /** @hidden */
  21013. AbstractMesh.prototype._resyncLightSources = function () {
  21014. this._lightSources.length = 0;
  21015. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  21016. var light = _a[_i];
  21017. if (!light.isEnabled()) {
  21018. continue;
  21019. }
  21020. if (light.canAffectMesh(this)) {
  21021. this._lightSources.push(light);
  21022. }
  21023. }
  21024. this._markSubMeshesAsLightDirty();
  21025. };
  21026. /** @hidden */
  21027. AbstractMesh.prototype._resyncLighSource = function (light) {
  21028. var isIn = light.isEnabled() && light.canAffectMesh(this);
  21029. var index = this._lightSources.indexOf(light);
  21030. if (index === -1) {
  21031. if (!isIn) {
  21032. return;
  21033. }
  21034. this._lightSources.push(light);
  21035. }
  21036. else {
  21037. if (isIn) {
  21038. return;
  21039. }
  21040. this._lightSources.splice(index, 1);
  21041. }
  21042. this._markSubMeshesAsLightDirty();
  21043. };
  21044. /** @hidden */
  21045. AbstractMesh.prototype._unBindEffect = function () {
  21046. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21047. var subMesh = _a[_i];
  21048. subMesh.setEffect(null);
  21049. }
  21050. };
  21051. /** @hidden */
  21052. AbstractMesh.prototype._removeLightSource = function (light) {
  21053. var index = this._lightSources.indexOf(light);
  21054. if (index === -1) {
  21055. return;
  21056. }
  21057. this._lightSources.splice(index, 1);
  21058. this._markSubMeshesAsLightDirty();
  21059. };
  21060. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  21061. if (!this.subMeshes) {
  21062. return;
  21063. }
  21064. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21065. var subMesh = _a[_i];
  21066. if (subMesh._materialDefines) {
  21067. func(subMesh._materialDefines);
  21068. }
  21069. }
  21070. };
  21071. /** @hidden */
  21072. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  21073. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  21074. };
  21075. /** @hidden */
  21076. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  21077. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  21078. };
  21079. /** @hidden */
  21080. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  21081. if (!this.subMeshes) {
  21082. return;
  21083. }
  21084. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21085. var subMesh = _a[_i];
  21086. var material = subMesh.getMaterial();
  21087. if (material) {
  21088. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  21089. }
  21090. }
  21091. };
  21092. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  21093. /**
  21094. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  21095. */
  21096. get: function () {
  21097. return this._scaling;
  21098. },
  21099. set: function (newScaling) {
  21100. this._scaling = newScaling;
  21101. if (this.physicsImpostor) {
  21102. this.physicsImpostor.forceUpdate();
  21103. }
  21104. },
  21105. enumerable: true,
  21106. configurable: true
  21107. });
  21108. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  21109. // Methods
  21110. /**
  21111. * Returns true if the mesh is blocked. Implemented by child classes
  21112. */
  21113. get: function () {
  21114. return false;
  21115. },
  21116. enumerable: true,
  21117. configurable: true
  21118. });
  21119. /**
  21120. * Returns the mesh itself by default. Implemented by child classes
  21121. * @param camera defines the camera to use to pick the right LOD level
  21122. * @returns the currentAbstractMesh
  21123. */
  21124. AbstractMesh.prototype.getLOD = function (camera) {
  21125. return this;
  21126. };
  21127. /**
  21128. * Returns 0 by default. Implemented by child classes
  21129. * @returns an integer
  21130. */
  21131. AbstractMesh.prototype.getTotalVertices = function () {
  21132. return 0;
  21133. };
  21134. /**
  21135. * Returns null by default. Implemented by child classes
  21136. * @returns null
  21137. */
  21138. AbstractMesh.prototype.getIndices = function () {
  21139. return null;
  21140. };
  21141. /**
  21142. * Returns the array of the requested vertex data kind. Implemented by child classes
  21143. * @param kind defines the vertex data kind to use
  21144. * @returns null
  21145. */
  21146. AbstractMesh.prototype.getVerticesData = function (kind) {
  21147. return null;
  21148. };
  21149. /**
  21150. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21151. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21152. * Note that a new underlying VertexBuffer object is created each call.
  21153. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21154. * @param kind defines vertex data kind:
  21155. * * BABYLON.VertexBuffer.PositionKind
  21156. * * BABYLON.VertexBuffer.UVKind
  21157. * * BABYLON.VertexBuffer.UV2Kind
  21158. * * BABYLON.VertexBuffer.UV3Kind
  21159. * * BABYLON.VertexBuffer.UV4Kind
  21160. * * BABYLON.VertexBuffer.UV5Kind
  21161. * * BABYLON.VertexBuffer.UV6Kind
  21162. * * BABYLON.VertexBuffer.ColorKind
  21163. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21164. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21165. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21166. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21167. * @param data defines the data source
  21168. * @param updatable defines if the data must be flagged as updatable (or static)
  21169. * @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
  21170. * @returns the current mesh
  21171. */
  21172. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21173. return this;
  21174. };
  21175. /**
  21176. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21177. * If the mesh has no geometry, it is simply returned as it is.
  21178. * @param kind defines vertex data kind:
  21179. * * BABYLON.VertexBuffer.PositionKind
  21180. * * BABYLON.VertexBuffer.UVKind
  21181. * * BABYLON.VertexBuffer.UV2Kind
  21182. * * BABYLON.VertexBuffer.UV3Kind
  21183. * * BABYLON.VertexBuffer.UV4Kind
  21184. * * BABYLON.VertexBuffer.UV5Kind
  21185. * * BABYLON.VertexBuffer.UV6Kind
  21186. * * BABYLON.VertexBuffer.ColorKind
  21187. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21188. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21189. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21190. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21191. * @param data defines the data source
  21192. * @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
  21193. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  21194. * @returns the current mesh
  21195. */
  21196. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21197. return this;
  21198. };
  21199. /**
  21200. * Sets the mesh indices,
  21201. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21202. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  21203. * @param totalVertices Defines the total number of vertices
  21204. * @returns the current mesh
  21205. */
  21206. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  21207. return this;
  21208. };
  21209. /**
  21210. * Gets a boolean indicating if specific vertex data is present
  21211. * @param kind defines the vertex data kind to use
  21212. * @returns true is data kind is present
  21213. */
  21214. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  21215. return false;
  21216. };
  21217. /**
  21218. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  21219. * @returns a BoundingInfo
  21220. */
  21221. AbstractMesh.prototype.getBoundingInfo = function () {
  21222. if (this._masterMesh) {
  21223. return this._masterMesh.getBoundingInfo();
  21224. }
  21225. if (!this._boundingInfo) {
  21226. // this._boundingInfo is being created here
  21227. this._updateBoundingInfo();
  21228. }
  21229. // cannot be null.
  21230. return this._boundingInfo;
  21231. };
  21232. /**
  21233. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  21234. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  21235. * @returns the current mesh
  21236. */
  21237. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  21238. if (includeDescendants === void 0) { includeDescendants = true; }
  21239. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  21240. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  21241. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  21242. if (maxDimension === 0) {
  21243. return this;
  21244. }
  21245. var scale = 1 / maxDimension;
  21246. this.scaling.scaleInPlace(scale);
  21247. return this;
  21248. };
  21249. /**
  21250. * Overwrite the current bounding info
  21251. * @param boundingInfo defines the new bounding info
  21252. * @returns the current mesh
  21253. */
  21254. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  21255. this._boundingInfo = boundingInfo;
  21256. return this;
  21257. };
  21258. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  21259. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  21260. get: function () {
  21261. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  21262. },
  21263. enumerable: true,
  21264. configurable: true
  21265. });
  21266. /** @hidden */
  21267. AbstractMesh.prototype._preActivate = function () {
  21268. };
  21269. /** @hidden */
  21270. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21271. };
  21272. /** @hidden */
  21273. AbstractMesh.prototype._activate = function (renderId) {
  21274. this._renderId = renderId;
  21275. };
  21276. /**
  21277. * Gets the current world matrix
  21278. * @returns a Matrix
  21279. */
  21280. AbstractMesh.prototype.getWorldMatrix = function () {
  21281. if (this._masterMesh) {
  21282. return this._masterMesh.getWorldMatrix();
  21283. }
  21284. return _super.prototype.getWorldMatrix.call(this);
  21285. };
  21286. /** @hidden */
  21287. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  21288. if (this._masterMesh) {
  21289. return this._masterMesh._getWorldMatrixDeterminant();
  21290. }
  21291. return _super.prototype._getWorldMatrixDeterminant.call(this);
  21292. };
  21293. // ================================== Point of View Movement =================================
  21294. /**
  21295. * Perform relative position change from the point of view of behind the front of the mesh.
  21296. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21297. * Supports definition of mesh facing forward or backward
  21298. * @param amountRight defines the distance on the right axis
  21299. * @param amountUp defines the distance on the up axis
  21300. * @param amountForward defines the distance on the forward axis
  21301. * @returns the current mesh
  21302. */
  21303. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  21304. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  21305. return this;
  21306. };
  21307. /**
  21308. * Calculate relative position change from the point of view of behind the front of the mesh.
  21309. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21310. * Supports definition of mesh facing forward or backward
  21311. * @param amountRight defines the distance on the right axis
  21312. * @param amountUp defines the distance on the up axis
  21313. * @param amountForward defines the distance on the forward axis
  21314. * @returns the new displacement vector
  21315. */
  21316. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  21317. var rotMatrix = new BABYLON.Matrix();
  21318. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  21319. rotQuaternion.toRotationMatrix(rotMatrix);
  21320. var translationDelta = BABYLON.Vector3.Zero();
  21321. var defForwardMult = this.definedFacingForward ? -1 : 1;
  21322. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  21323. return translationDelta;
  21324. };
  21325. // ================================== Point of View Rotation =================================
  21326. /**
  21327. * Perform relative rotation change from the point of view of behind the front of the mesh.
  21328. * Supports definition of mesh facing forward or backward
  21329. * @param flipBack defines the flip
  21330. * @param twirlClockwise defines the twirl
  21331. * @param tiltRight defines the tilt
  21332. * @returns the current mesh
  21333. */
  21334. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21335. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  21336. return this;
  21337. };
  21338. /**
  21339. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  21340. * Supports definition of mesh facing forward or backward.
  21341. * @param flipBack defines the flip
  21342. * @param twirlClockwise defines the twirl
  21343. * @param tiltRight defines the tilt
  21344. * @returns the new rotation vector
  21345. */
  21346. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21347. var defForwardMult = this.definedFacingForward ? 1 : -1;
  21348. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  21349. };
  21350. /**
  21351. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  21352. * @param includeDescendants Include bounding info from descendants as well (true by default)
  21353. * @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
  21354. * @returns the new bounding vectors
  21355. */
  21356. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  21357. if (includeDescendants === void 0) { includeDescendants = true; }
  21358. if (predicate === void 0) { predicate = null; }
  21359. // Ensures that all world matrix will be recomputed.
  21360. this.getScene().incrementRenderId();
  21361. this.computeWorldMatrix(true);
  21362. var min;
  21363. var max;
  21364. var boundingInfo = this.getBoundingInfo();
  21365. if (!this.subMeshes) {
  21366. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21367. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21368. }
  21369. else {
  21370. min = boundingInfo.boundingBox.minimumWorld;
  21371. max = boundingInfo.boundingBox.maximumWorld;
  21372. }
  21373. if (includeDescendants) {
  21374. var descendants = this.getDescendants(false);
  21375. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  21376. var descendant = descendants_1[_i];
  21377. var childMesh = descendant;
  21378. childMesh.computeWorldMatrix(true);
  21379. // Filters meshes based on custom predicate function.
  21380. if (predicate && !predicate(childMesh)) {
  21381. continue;
  21382. }
  21383. //make sure we have the needed params to get mix and max
  21384. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  21385. continue;
  21386. }
  21387. var childBoundingInfo = childMesh.getBoundingInfo();
  21388. var boundingBox = childBoundingInfo.boundingBox;
  21389. var minBox = boundingBox.minimumWorld;
  21390. var maxBox = boundingBox.maximumWorld;
  21391. BABYLON.Tools.CheckExtends(minBox, min, max);
  21392. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21393. }
  21394. }
  21395. return {
  21396. min: min,
  21397. max: max
  21398. };
  21399. };
  21400. /** @hidden */
  21401. AbstractMesh.prototype._updateBoundingInfo = function () {
  21402. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  21403. this._boundingInfo.update(this.worldMatrixFromCache);
  21404. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21405. return this;
  21406. };
  21407. /** @hidden */
  21408. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  21409. if (!this.subMeshes) {
  21410. return this;
  21411. }
  21412. var count = this.subMeshes.length;
  21413. for (var subIndex = 0; subIndex < count; subIndex++) {
  21414. var subMesh = this.subMeshes[subIndex];
  21415. if (count > 1 || !subMesh.IsGlobal) {
  21416. subMesh.updateBoundingInfo(matrix);
  21417. }
  21418. }
  21419. return this;
  21420. };
  21421. /** @hidden */
  21422. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  21423. // Bounding info
  21424. this._updateBoundingInfo();
  21425. };
  21426. /**
  21427. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  21428. * A mesh is in the frustum if its bounding box intersects the frustum
  21429. * @param frustumPlanes defines the frustum to test
  21430. * @returns true if the mesh is in the frustum planes
  21431. */
  21432. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  21433. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  21434. };
  21435. /**
  21436. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  21437. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  21438. * @param frustumPlanes defines the frustum to test
  21439. * @returns true if the mesh is completely in the frustum planes
  21440. */
  21441. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21442. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  21443. };
  21444. /**
  21445. * True if the mesh intersects another mesh or a SolidParticle object
  21446. * @param mesh defines a target mesh or SolidParticle to test
  21447. * @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)
  21448. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  21449. * @returns true if there is an intersection
  21450. */
  21451. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  21452. if (precise === void 0) { precise = false; }
  21453. if (!this._boundingInfo || !mesh._boundingInfo) {
  21454. return false;
  21455. }
  21456. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  21457. return true;
  21458. }
  21459. if (includeDescendants) {
  21460. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  21461. var child = _a[_i];
  21462. if (child.intersectsMesh(mesh, precise, true)) {
  21463. return true;
  21464. }
  21465. }
  21466. }
  21467. return false;
  21468. };
  21469. /**
  21470. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  21471. * @param point defines the point to test
  21472. * @returns true if there is an intersection
  21473. */
  21474. AbstractMesh.prototype.intersectsPoint = function (point) {
  21475. if (!this._boundingInfo) {
  21476. return false;
  21477. }
  21478. return this._boundingInfo.intersectsPoint(point);
  21479. };
  21480. /**
  21481. * Gets the position of the current mesh in camera space
  21482. * @param camera defines the camera to use
  21483. * @returns a position
  21484. */
  21485. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  21486. if (camera === void 0) { camera = null; }
  21487. if (!camera) {
  21488. camera = this.getScene().activeCamera;
  21489. }
  21490. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  21491. };
  21492. /**
  21493. * Returns the distance from the mesh to the active camera
  21494. * @param camera defines the camera to use
  21495. * @returns the distance
  21496. */
  21497. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  21498. if (camera === void 0) { camera = null; }
  21499. if (!camera) {
  21500. camera = this.getScene().activeCamera;
  21501. }
  21502. return this.absolutePosition.subtract(camera.position).length();
  21503. };
  21504. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  21505. // Collisions
  21506. /**
  21507. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  21508. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21509. */
  21510. get: function () {
  21511. return this._checkCollisions;
  21512. },
  21513. set: function (collisionEnabled) {
  21514. this._checkCollisions = collisionEnabled;
  21515. if (this.getScene().workerCollisions) {
  21516. this.getScene().collisionCoordinator.onMeshUpdated(this);
  21517. }
  21518. },
  21519. enumerable: true,
  21520. configurable: true
  21521. });
  21522. Object.defineProperty(AbstractMesh.prototype, "collider", {
  21523. /**
  21524. * Gets Collider object used to compute collisions (not physics)
  21525. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21526. */
  21527. get: function () {
  21528. return this._collider;
  21529. },
  21530. enumerable: true,
  21531. configurable: true
  21532. });
  21533. /**
  21534. * Move the mesh using collision engine
  21535. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21536. * @param displacement defines the requested displacement vector
  21537. * @returns the current mesh
  21538. */
  21539. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  21540. var globalPosition = this.getAbsolutePosition();
  21541. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  21542. if (!this._collider) {
  21543. this._collider = new BABYLON.Collider();
  21544. }
  21545. this._collider._radius = this.ellipsoid;
  21546. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  21547. return this;
  21548. };
  21549. // Collisions
  21550. /** @hidden */
  21551. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  21552. this._generatePointsArray();
  21553. if (!this._positions) {
  21554. return this;
  21555. }
  21556. // Transformation
  21557. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  21558. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  21559. subMesh._lastColliderWorldVertices = [];
  21560. subMesh._trianglePlanes = [];
  21561. var start = subMesh.verticesStart;
  21562. var end = (subMesh.verticesStart + subMesh.verticesCount);
  21563. for (var i = start; i < end; i++) {
  21564. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  21565. }
  21566. }
  21567. // Collide
  21568. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  21569. if (collider.collisionFound) {
  21570. collider.collidedMesh = this;
  21571. }
  21572. return this;
  21573. };
  21574. /** @hidden */
  21575. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  21576. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  21577. var len = subMeshes.length;
  21578. for (var index = 0; index < len; index++) {
  21579. var subMesh = subMeshes.data[index];
  21580. // Bounding test
  21581. if (len > 1 && !subMesh._checkCollision(collider))
  21582. continue;
  21583. this._collideForSubMesh(subMesh, transformMatrix, collider);
  21584. }
  21585. return this;
  21586. };
  21587. /** @hidden */
  21588. AbstractMesh.prototype._checkCollision = function (collider) {
  21589. // Bounding box test
  21590. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  21591. return this;
  21592. // Transformation matrix
  21593. var collisionsScalingMatrix = BABYLON.Tmp.Matrix[0];
  21594. var collisionsTransformMatrix = BABYLON.Tmp.Matrix[1];
  21595. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, collisionsScalingMatrix);
  21596. this.worldMatrixFromCache.multiplyToRef(collisionsScalingMatrix, collisionsTransformMatrix);
  21597. this._processCollisionsForSubMeshes(collider, collisionsTransformMatrix);
  21598. return this;
  21599. };
  21600. // Picking
  21601. /** @hidden */
  21602. AbstractMesh.prototype._generatePointsArray = function () {
  21603. return false;
  21604. };
  21605. /**
  21606. * Checks if the passed Ray intersects with the mesh
  21607. * @param ray defines the ray to use
  21608. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  21609. * @returns the picking info
  21610. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  21611. */
  21612. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  21613. var pickingInfo = new BABYLON.PickingInfo();
  21614. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  21615. return pickingInfo;
  21616. }
  21617. if (!this._generatePointsArray()) {
  21618. return pickingInfo;
  21619. }
  21620. var intersectInfo = null;
  21621. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  21622. var len = subMeshes.length;
  21623. for (var index = 0; index < len; index++) {
  21624. var subMesh = subMeshes.data[index];
  21625. // Bounding test
  21626. if (len > 1 && !subMesh.canIntersects(ray))
  21627. continue;
  21628. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  21629. if (currentIntersectInfo) {
  21630. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21631. intersectInfo = currentIntersectInfo;
  21632. intersectInfo.subMeshId = index;
  21633. if (fastCheck) {
  21634. break;
  21635. }
  21636. }
  21637. }
  21638. }
  21639. if (intersectInfo) {
  21640. // Get picked point
  21641. var world = this.getWorldMatrix();
  21642. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  21643. var direction = ray.direction.clone();
  21644. direction = direction.scale(intersectInfo.distance);
  21645. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  21646. var pickedPoint = worldOrigin.add(worldDirection);
  21647. // Return result
  21648. pickingInfo.hit = true;
  21649. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  21650. pickingInfo.pickedPoint = pickedPoint;
  21651. pickingInfo.pickedMesh = this;
  21652. pickingInfo.bu = intersectInfo.bu || 0;
  21653. pickingInfo.bv = intersectInfo.bv || 0;
  21654. pickingInfo.faceId = intersectInfo.faceId;
  21655. pickingInfo.subMeshId = intersectInfo.subMeshId;
  21656. return pickingInfo;
  21657. }
  21658. return pickingInfo;
  21659. };
  21660. /**
  21661. * Clones the current mesh
  21662. * @param name defines the mesh name
  21663. * @param newParent defines the new mesh parent
  21664. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  21665. * @returns the new mesh
  21666. */
  21667. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  21668. return null;
  21669. };
  21670. /**
  21671. * Disposes all the submeshes of the current meshnp
  21672. * @returns the current mesh
  21673. */
  21674. AbstractMesh.prototype.releaseSubMeshes = function () {
  21675. if (this.subMeshes) {
  21676. while (this.subMeshes.length) {
  21677. this.subMeshes[0].dispose();
  21678. }
  21679. }
  21680. else {
  21681. this.subMeshes = new Array();
  21682. }
  21683. return this;
  21684. };
  21685. /**
  21686. * Releases resources associated with this abstract mesh.
  21687. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21688. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21689. */
  21690. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21691. var _this = this;
  21692. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21693. var index;
  21694. // Smart Array Retainers.
  21695. this.getScene().freeActiveMeshes();
  21696. this.getScene().freeRenderingGroups();
  21697. // Action manager
  21698. if (this.actionManager !== undefined && this.actionManager !== null) {
  21699. this.actionManager.dispose();
  21700. this.actionManager = null;
  21701. }
  21702. // Skeleton
  21703. this._skeleton = null;
  21704. // Intersections in progress
  21705. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  21706. var other = this._intersectionsInProgress[index];
  21707. var pos = other._intersectionsInProgress.indexOf(this);
  21708. other._intersectionsInProgress.splice(pos, 1);
  21709. }
  21710. this._intersectionsInProgress = [];
  21711. // Lights
  21712. var lights = this.getScene().lights;
  21713. lights.forEach(function (light) {
  21714. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  21715. if (meshIndex !== -1) {
  21716. light.includedOnlyMeshes.splice(meshIndex, 1);
  21717. }
  21718. meshIndex = light.excludedMeshes.indexOf(_this);
  21719. if (meshIndex !== -1) {
  21720. light.excludedMeshes.splice(meshIndex, 1);
  21721. }
  21722. // Shadow generators
  21723. var generator = light.getShadowGenerator();
  21724. if (generator) {
  21725. var shadowMap = generator.getShadowMap();
  21726. if (shadowMap && shadowMap.renderList) {
  21727. meshIndex = shadowMap.renderList.indexOf(_this);
  21728. if (meshIndex !== -1) {
  21729. shadowMap.renderList.splice(meshIndex, 1);
  21730. }
  21731. }
  21732. }
  21733. });
  21734. // SubMeshes
  21735. if (this.getClassName() !== "InstancedMesh") {
  21736. this.releaseSubMeshes();
  21737. }
  21738. // Query
  21739. var engine = this.getScene().getEngine();
  21740. if (this._occlusionQuery) {
  21741. this.isOcclusionQueryInProgress = false;
  21742. engine.deleteQuery(this._occlusionQuery);
  21743. this._occlusionQuery = null;
  21744. }
  21745. // Engine
  21746. engine.wipeCaches();
  21747. // Remove from scene
  21748. this.getScene().removeMesh(this);
  21749. if (disposeMaterialAndTextures) {
  21750. if (this.material) {
  21751. this.material.dispose(false, true);
  21752. }
  21753. }
  21754. if (!doNotRecurse) {
  21755. // Particles
  21756. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21757. if (this.getScene().particleSystems[index].emitter === this) {
  21758. this.getScene().particleSystems[index].dispose();
  21759. index--;
  21760. }
  21761. }
  21762. }
  21763. // facet data
  21764. if (this._facetData.facetDataEnabled) {
  21765. this.disableFacetData();
  21766. }
  21767. this.onAfterWorldMatrixUpdateObservable.clear();
  21768. this.onCollideObservable.clear();
  21769. this.onCollisionPositionChangeObservable.clear();
  21770. this.onRebuildObservable.clear();
  21771. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21772. };
  21773. /**
  21774. * Adds the passed mesh as a child to the current mesh
  21775. * @param mesh defines the child mesh
  21776. * @returns the current mesh
  21777. */
  21778. AbstractMesh.prototype.addChild = function (mesh) {
  21779. mesh.setParent(this);
  21780. return this;
  21781. };
  21782. /**
  21783. * Removes the passed mesh from the current mesh children list
  21784. * @param mesh defines the child mesh
  21785. * @returns the current mesh
  21786. */
  21787. AbstractMesh.prototype.removeChild = function (mesh) {
  21788. mesh.setParent(null);
  21789. return this;
  21790. };
  21791. // Facet data
  21792. /** @hidden */
  21793. AbstractMesh.prototype._initFacetData = function () {
  21794. var data = this._facetData;
  21795. if (!data.facetNormals) {
  21796. data.facetNormals = new Array();
  21797. }
  21798. if (!data.facetPositions) {
  21799. data.facetPositions = new Array();
  21800. }
  21801. if (!data.facetPartitioning) {
  21802. data.facetPartitioning = new Array();
  21803. }
  21804. data.facetNb = (this.getIndices().length / 3) | 0;
  21805. data.partitioningSubdivisions = (data.partitioningSubdivisions) ? data.partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21806. data.partitioningBBoxRatio = (data.partitioningBBoxRatio) ? data.partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21807. for (var f = 0; f < data.facetNb; f++) {
  21808. data.facetNormals[f] = BABYLON.Vector3.Zero();
  21809. data.facetPositions[f] = BABYLON.Vector3.Zero();
  21810. }
  21811. data.facetDataEnabled = true;
  21812. return this;
  21813. };
  21814. /**
  21815. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21816. * This method can be called within the render loop.
  21817. * 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
  21818. * @returns the current mesh
  21819. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21820. */
  21821. AbstractMesh.prototype.updateFacetData = function () {
  21822. var data = this._facetData;
  21823. if (!data.facetDataEnabled) {
  21824. this._initFacetData();
  21825. }
  21826. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21827. var indices = this.getIndices();
  21828. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21829. var bInfo = this.getBoundingInfo();
  21830. if (data.facetDepthSort && !data.facetDepthSortEnabled) {
  21831. // init arrays, matrix and sort function on first call
  21832. data.facetDepthSortEnabled = true;
  21833. if (indices instanceof Uint16Array) {
  21834. data.depthSortedIndices = new Uint16Array(indices);
  21835. }
  21836. else if (indices instanceof Uint32Array) {
  21837. data.depthSortedIndices = new Uint32Array(indices);
  21838. }
  21839. else {
  21840. var needs32bits = false;
  21841. for (var i = 0; i < indices.length; i++) {
  21842. if (indices[i] > 65535) {
  21843. needs32bits = true;
  21844. break;
  21845. }
  21846. }
  21847. if (needs32bits) {
  21848. data.depthSortedIndices = new Uint32Array(indices);
  21849. }
  21850. else {
  21851. data.depthSortedIndices = new Uint16Array(indices);
  21852. }
  21853. }
  21854. data.facetDepthSortFunction = function (f1, f2) {
  21855. return (f2.sqDistance - f1.sqDistance);
  21856. };
  21857. if (!data.facetDepthSortFrom) {
  21858. var camera = this.getScene().activeCamera;
  21859. data.facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21860. }
  21861. data.depthSortedFacets = [];
  21862. for (var f = 0; f < data.facetNb; f++) {
  21863. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21864. data.depthSortedFacets.push(depthSortedFacet);
  21865. }
  21866. data.invertedMatrix = BABYLON.Matrix.Identity();
  21867. data.facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21868. }
  21869. data.bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21870. data.bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21871. data.bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21872. var bbSizeMax = (data.bbSize.x > data.bbSize.y) ? data.bbSize.x : data.bbSize.y;
  21873. bbSizeMax = (bbSizeMax > data.bbSize.z) ? bbSizeMax : data.bbSize.z;
  21874. data.subDiv.max = data.partitioningSubdivisions;
  21875. data.subDiv.X = Math.floor(data.subDiv.max * data.bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21876. data.subDiv.Y = Math.floor(data.subDiv.max * data.bbSize.y / bbSizeMax); // according to each bbox size per axis
  21877. data.subDiv.Z = Math.floor(data.subDiv.max * data.bbSize.z / bbSizeMax);
  21878. data.subDiv.X = data.subDiv.X < 1 ? 1 : data.subDiv.X; // at least one subdivision
  21879. data.subDiv.Y = data.subDiv.Y < 1 ? 1 : data.subDiv.Y;
  21880. data.subDiv.Z = data.subDiv.Z < 1 ? 1 : data.subDiv.Z;
  21881. // set the parameters for ComputeNormals()
  21882. data.facetParameters.facetNormals = this.getFacetLocalNormals();
  21883. data.facetParameters.facetPositions = this.getFacetLocalPositions();
  21884. data.facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21885. data.facetParameters.bInfo = bInfo;
  21886. data.facetParameters.bbSize = data.bbSize;
  21887. data.facetParameters.subDiv = data.subDiv;
  21888. data.facetParameters.ratio = this.partitioningBBoxRatio;
  21889. data.facetParameters.depthSort = data.facetDepthSort;
  21890. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  21891. this.computeWorldMatrix(true);
  21892. this._worldMatrix.invertToRef(data.invertedMatrix);
  21893. BABYLON.Vector3.TransformCoordinatesToRef(data.facetDepthSortFrom, data.invertedMatrix, data.facetDepthSortOrigin);
  21894. data.facetParameters.distanceTo = data.facetDepthSortOrigin;
  21895. }
  21896. data.facetParameters.depthSortedFacets = data.depthSortedFacets;
  21897. BABYLON.VertexData.ComputeNormals(positions, indices, normals, data.facetParameters);
  21898. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  21899. data.depthSortedFacets.sort(data.facetDepthSortFunction);
  21900. var l = (data.depthSortedIndices.length / 3) | 0;
  21901. for (var f = 0; f < l; f++) {
  21902. var sind = data.depthSortedFacets[f].ind;
  21903. data.depthSortedIndices[f * 3] = indices[sind];
  21904. data.depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21905. data.depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21906. }
  21907. this.updateIndices(data.depthSortedIndices);
  21908. }
  21909. return this;
  21910. };
  21911. /**
  21912. * Returns the facetLocalNormals array.
  21913. * The normals are expressed in the mesh local spac
  21914. * @returns an array of Vector3
  21915. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21916. */
  21917. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21918. if (!this._facetData.facetNormals) {
  21919. this.updateFacetData();
  21920. }
  21921. return this._facetData.facetNormals;
  21922. };
  21923. /**
  21924. * Returns the facetLocalPositions array.
  21925. * The facet positions are expressed in the mesh local space
  21926. * @returns an array of Vector3
  21927. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21928. */
  21929. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21930. if (!this._facetData.facetPositions) {
  21931. this.updateFacetData();
  21932. }
  21933. return this._facetData.facetPositions;
  21934. };
  21935. /**
  21936. * Returns the facetLocalPartioning array
  21937. * @returns an array of array of numbers
  21938. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21939. */
  21940. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21941. if (!this._facetData.facetPartitioning) {
  21942. this.updateFacetData();
  21943. }
  21944. return this._facetData.facetPartitioning;
  21945. };
  21946. /**
  21947. * Returns the i-th facet position in the world system.
  21948. * This method allocates a new Vector3 per call
  21949. * @param i defines the facet index
  21950. * @returns a new Vector3
  21951. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21952. */
  21953. AbstractMesh.prototype.getFacetPosition = function (i) {
  21954. var pos = BABYLON.Vector3.Zero();
  21955. this.getFacetPositionToRef(i, pos);
  21956. return pos;
  21957. };
  21958. /**
  21959. * Sets the reference Vector3 with the i-th facet position in the world system
  21960. * @param i defines the facet index
  21961. * @param ref defines the target vector
  21962. * @returns the current mesh
  21963. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21964. */
  21965. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21966. var localPos = (this.getFacetLocalPositions())[i];
  21967. var world = this.getWorldMatrix();
  21968. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21969. return this;
  21970. };
  21971. /**
  21972. * Returns the i-th facet normal in the world system.
  21973. * This method allocates a new Vector3 per call
  21974. * @param i defines the facet index
  21975. * @returns a new Vector3
  21976. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21977. */
  21978. AbstractMesh.prototype.getFacetNormal = function (i) {
  21979. var norm = BABYLON.Vector3.Zero();
  21980. this.getFacetNormalToRef(i, norm);
  21981. return norm;
  21982. };
  21983. /**
  21984. * Sets the reference Vector3 with the i-th facet normal in the world system
  21985. * @param i defines the facet index
  21986. * @param ref defines the target vector
  21987. * @returns the current mesh
  21988. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21989. */
  21990. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21991. var localNorm = (this.getFacetLocalNormals())[i];
  21992. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21993. return this;
  21994. };
  21995. /**
  21996. * 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)
  21997. * @param x defines x coordinate
  21998. * @param y defines y coordinate
  21999. * @param z defines z coordinate
  22000. * @returns the array of facet indexes
  22001. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22002. */
  22003. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  22004. var bInfo = this.getBoundingInfo();
  22005. var data = this._facetData;
  22006. var ox = Math.floor((x - bInfo.minimum.x * data.partitioningBBoxRatio) * data.subDiv.X * data.partitioningBBoxRatio / data.bbSize.x);
  22007. var oy = Math.floor((y - bInfo.minimum.y * data.partitioningBBoxRatio) * data.subDiv.Y * data.partitioningBBoxRatio / data.bbSize.y);
  22008. var oz = Math.floor((z - bInfo.minimum.z * data.partitioningBBoxRatio) * data.subDiv.Z * data.partitioningBBoxRatio / data.bbSize.z);
  22009. if (ox < 0 || ox > data.subDiv.max || oy < 0 || oy > data.subDiv.max || oz < 0 || oz > data.subDiv.max) {
  22010. return null;
  22011. }
  22012. return data.facetPartitioning[ox + data.subDiv.max * oy + data.subDiv.max * data.subDiv.max * oz];
  22013. };
  22014. /**
  22015. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  22016. * @param projected sets as the (x,y,z) world projection on the facet
  22017. * @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
  22018. * @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
  22019. * @param x defines x coordinate
  22020. * @param y defines y coordinate
  22021. * @param z defines z coordinate
  22022. * @returns the face index if found (or null instead)
  22023. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22024. */
  22025. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  22026. if (checkFace === void 0) { checkFace = false; }
  22027. if (facing === void 0) { facing = true; }
  22028. var world = this.getWorldMatrix();
  22029. var invMat = BABYLON.Tmp.Matrix[5];
  22030. world.invertToRef(invMat);
  22031. var invVect = BABYLON.Tmp.Vector3[8];
  22032. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  22033. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  22034. if (projected) {
  22035. // tranform the local computed projected vector to world coordinates
  22036. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  22037. }
  22038. return closest;
  22039. };
  22040. /**
  22041. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  22042. * @param projected sets as the (x,y,z) local projection on the facet
  22043. * @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
  22044. * @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
  22045. * @param x defines x coordinate
  22046. * @param y defines y coordinate
  22047. * @param z defines z coordinate
  22048. * @returns the face index if found (or null instead)
  22049. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22050. */
  22051. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  22052. if (checkFace === void 0) { checkFace = false; }
  22053. if (facing === void 0) { facing = true; }
  22054. var closest = null;
  22055. var tmpx = 0.0;
  22056. var tmpy = 0.0;
  22057. var tmpz = 0.0;
  22058. var d = 0.0; // tmp dot facet normal * facet position
  22059. var t0 = 0.0;
  22060. var projx = 0.0;
  22061. var projy = 0.0;
  22062. var projz = 0.0;
  22063. // Get all the facets in the same partitioning block than (x, y, z)
  22064. var facetPositions = this.getFacetLocalPositions();
  22065. var facetNormals = this.getFacetLocalNormals();
  22066. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  22067. if (!facetsInBlock) {
  22068. return null;
  22069. }
  22070. // Get the closest facet to (x, y, z)
  22071. var shortest = Number.MAX_VALUE; // init distance vars
  22072. var tmpDistance = shortest;
  22073. var fib; // current facet in the block
  22074. var norm; // current facet normal
  22075. var p0; // current facet barycenter position
  22076. // loop on all the facets in the current partitioning block
  22077. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  22078. fib = facetsInBlock[idx];
  22079. norm = facetNormals[fib];
  22080. p0 = facetPositions[fib];
  22081. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  22082. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  22083. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  22084. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  22085. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  22086. projx = x + norm.x * t0;
  22087. projy = y + norm.y * t0;
  22088. projz = z + norm.z * t0;
  22089. tmpx = projx - x;
  22090. tmpy = projy - y;
  22091. tmpz = projz - z;
  22092. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  22093. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  22094. shortest = tmpDistance;
  22095. closest = fib;
  22096. if (projected) {
  22097. projected.x = projx;
  22098. projected.y = projy;
  22099. projected.z = projz;
  22100. }
  22101. }
  22102. }
  22103. }
  22104. return closest;
  22105. };
  22106. /**
  22107. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  22108. * @returns the parameters
  22109. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22110. */
  22111. AbstractMesh.prototype.getFacetDataParameters = function () {
  22112. return this._facetData.facetParameters;
  22113. };
  22114. /**
  22115. * Disables the feature FacetData and frees the related memory
  22116. * @returns the current mesh
  22117. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22118. */
  22119. AbstractMesh.prototype.disableFacetData = function () {
  22120. if (this._facetData.facetDataEnabled) {
  22121. this._facetData.facetDataEnabled = false;
  22122. this._facetData.facetPositions = new Array();
  22123. this._facetData.facetNormals = new Array();
  22124. this._facetData.facetPartitioning = new Array();
  22125. this._facetData.facetParameters = null;
  22126. this._facetData.depthSortedIndices = new Uint32Array(0);
  22127. }
  22128. return this;
  22129. };
  22130. /**
  22131. * Updates the AbstractMesh indices array
  22132. * @param indices defines the data source
  22133. * @returns the current mesh
  22134. */
  22135. AbstractMesh.prototype.updateIndices = function (indices) {
  22136. return this;
  22137. };
  22138. /**
  22139. * Creates new normals data for the mesh
  22140. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  22141. * @returns the current mesh
  22142. */
  22143. AbstractMesh.prototype.createNormals = function (updatable) {
  22144. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22145. var indices = this.getIndices();
  22146. var normals;
  22147. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22148. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22149. }
  22150. else {
  22151. normals = [];
  22152. }
  22153. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  22154. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  22155. return this;
  22156. };
  22157. /**
  22158. * Align the mesh with a normal
  22159. * @param normal defines the normal to use
  22160. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  22161. * @returns the current mesh
  22162. */
  22163. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  22164. if (!upDirection) {
  22165. upDirection = BABYLON.Axis.Y;
  22166. }
  22167. var axisX = BABYLON.Tmp.Vector3[0];
  22168. var axisZ = BABYLON.Tmp.Vector3[1];
  22169. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  22170. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  22171. if (this.rotationQuaternion) {
  22172. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  22173. }
  22174. else {
  22175. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  22176. }
  22177. return this;
  22178. };
  22179. /** @hidden */
  22180. AbstractMesh.prototype._checkOcclusionQuery = function () {
  22181. return false;
  22182. };
  22183. /** No occlusion */
  22184. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  22185. /** Occlusion set to optimisitic */
  22186. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  22187. /** Occlusion set to strict */
  22188. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  22189. /** Use an accurante occlusion algorithm */
  22190. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  22191. /** Use a conservative occlusion algorithm */
  22192. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  22193. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  22194. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  22195. /** Culling strategy with bounding sphere only and then frustum culling */
  22196. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  22197. return AbstractMesh;
  22198. }(BABYLON.TransformNode));
  22199. BABYLON.AbstractMesh = AbstractMesh;
  22200. })(BABYLON || (BABYLON = {}));
  22201. //# sourceMappingURL=babylon.abstractMesh.js.map
  22202. var BABYLON;
  22203. (function (BABYLON) {
  22204. /**
  22205. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  22206. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  22207. * 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.
  22208. */
  22209. var Light = /** @class */ (function (_super) {
  22210. __extends(Light, _super);
  22211. /**
  22212. * Creates a Light object in the scene.
  22213. * Documentation : http://doc.babylonjs.com/tutorials/lights
  22214. * @param name The firendly name of the light
  22215. * @param scene The scene the light belongs too
  22216. */
  22217. function Light(name, scene) {
  22218. var _this = _super.call(this, name, scene) || this;
  22219. /**
  22220. * Diffuse gives the basic color to an object.
  22221. */
  22222. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  22223. /**
  22224. * Specular produces a highlight color on an object.
  22225. * Note: This is note affecting PBR materials.
  22226. */
  22227. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  22228. /**
  22229. * Defines the falloff type for this light. This lets overrriding how punctual light are
  22230. * falling off base on range or angle.
  22231. * This can be set to any values in Light.FALLOFF_x.
  22232. *
  22233. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  22234. * other types of materials.
  22235. */
  22236. _this.falloffType = Light.FALLOFF_DEFAULT;
  22237. /**
  22238. * Strength of the light.
  22239. * Note: By default it is define in the framework own unit.
  22240. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  22241. */
  22242. _this.intensity = 1.0;
  22243. _this._range = Number.MAX_VALUE;
  22244. _this._inverseSquaredRange = 0;
  22245. /**
  22246. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  22247. * of light.
  22248. */
  22249. _this._photometricScale = 1.0;
  22250. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  22251. _this._radius = 0.00001;
  22252. /**
  22253. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  22254. * exceeding the number allowed of the materials.
  22255. */
  22256. _this.renderPriority = 0;
  22257. _this._shadowEnabled = true;
  22258. _this._excludeWithLayerMask = 0;
  22259. _this._includeOnlyWithLayerMask = 0;
  22260. _this._lightmapMode = 0;
  22261. /**
  22262. * @hidden Internal use only.
  22263. */
  22264. _this._excludedMeshesIds = new Array();
  22265. /**
  22266. * @hidden Internal use only.
  22267. */
  22268. _this._includedOnlyMeshesIds = new Array();
  22269. _this.getScene().addLight(_this);
  22270. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  22271. _this._buildUniformLayout();
  22272. _this.includedOnlyMeshes = new Array();
  22273. _this.excludedMeshes = new Array();
  22274. _this._resyncMeshes();
  22275. return _this;
  22276. }
  22277. Object.defineProperty(Light.prototype, "range", {
  22278. /**
  22279. * Defines how far from the source the light is impacting in scene units.
  22280. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22281. */
  22282. get: function () {
  22283. return this._range;
  22284. },
  22285. /**
  22286. * Defines how far from the source the light is impacting in scene units.
  22287. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22288. */
  22289. set: function (value) {
  22290. this._range = value;
  22291. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  22292. },
  22293. enumerable: true,
  22294. configurable: true
  22295. });
  22296. Object.defineProperty(Light.prototype, "intensityMode", {
  22297. /**
  22298. * Gets the photometric scale used to interpret the intensity.
  22299. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22300. */
  22301. get: function () {
  22302. return this._intensityMode;
  22303. },
  22304. /**
  22305. * Sets the photometric scale used to interpret the intensity.
  22306. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22307. */
  22308. set: function (value) {
  22309. this._intensityMode = value;
  22310. this._computePhotometricScale();
  22311. },
  22312. enumerable: true,
  22313. configurable: true
  22314. });
  22315. ;
  22316. ;
  22317. Object.defineProperty(Light.prototype, "radius", {
  22318. /**
  22319. * Gets the light radius used by PBR Materials to simulate soft area lights.
  22320. */
  22321. get: function () {
  22322. return this._radius;
  22323. },
  22324. /**
  22325. * sets the light radius used by PBR Materials to simulate soft area lights.
  22326. */
  22327. set: function (value) {
  22328. this._radius = value;
  22329. this._computePhotometricScale();
  22330. },
  22331. enumerable: true,
  22332. configurable: true
  22333. });
  22334. ;
  22335. ;
  22336. Object.defineProperty(Light.prototype, "shadowEnabled", {
  22337. /**
  22338. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22339. * the current shadow generator.
  22340. */
  22341. get: function () {
  22342. return this._shadowEnabled;
  22343. },
  22344. /**
  22345. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22346. * the current shadow generator.
  22347. */
  22348. set: function (value) {
  22349. if (this._shadowEnabled === value) {
  22350. return;
  22351. }
  22352. this._shadowEnabled = value;
  22353. this._markMeshesAsLightDirty();
  22354. },
  22355. enumerable: true,
  22356. configurable: true
  22357. });
  22358. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  22359. /**
  22360. * Gets the only meshes impacted by this light.
  22361. */
  22362. get: function () {
  22363. return this._includedOnlyMeshes;
  22364. },
  22365. /**
  22366. * Sets the only meshes impacted by this light.
  22367. */
  22368. set: function (value) {
  22369. this._includedOnlyMeshes = value;
  22370. this._hookArrayForIncludedOnly(value);
  22371. },
  22372. enumerable: true,
  22373. configurable: true
  22374. });
  22375. Object.defineProperty(Light.prototype, "excludedMeshes", {
  22376. /**
  22377. * Gets the meshes not impacted by this light.
  22378. */
  22379. get: function () {
  22380. return this._excludedMeshes;
  22381. },
  22382. /**
  22383. * Sets the meshes not impacted by this light.
  22384. */
  22385. set: function (value) {
  22386. this._excludedMeshes = value;
  22387. this._hookArrayForExcluded(value);
  22388. },
  22389. enumerable: true,
  22390. configurable: true
  22391. });
  22392. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  22393. /**
  22394. * Gets the layer id use to find what meshes are not impacted by the light.
  22395. * Inactive if 0
  22396. */
  22397. get: function () {
  22398. return this._excludeWithLayerMask;
  22399. },
  22400. /**
  22401. * Sets the layer id use to find what meshes are not impacted by the light.
  22402. * Inactive if 0
  22403. */
  22404. set: function (value) {
  22405. this._excludeWithLayerMask = value;
  22406. this._resyncMeshes();
  22407. },
  22408. enumerable: true,
  22409. configurable: true
  22410. });
  22411. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  22412. /**
  22413. * Gets the layer id use to find what meshes are impacted by the light.
  22414. * Inactive if 0
  22415. */
  22416. get: function () {
  22417. return this._includeOnlyWithLayerMask;
  22418. },
  22419. /**
  22420. * Sets the layer id use to find what meshes are impacted by the light.
  22421. * Inactive if 0
  22422. */
  22423. set: function (value) {
  22424. this._includeOnlyWithLayerMask = value;
  22425. this._resyncMeshes();
  22426. },
  22427. enumerable: true,
  22428. configurable: true
  22429. });
  22430. Object.defineProperty(Light.prototype, "lightmapMode", {
  22431. /**
  22432. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22433. */
  22434. get: function () {
  22435. return this._lightmapMode;
  22436. },
  22437. /**
  22438. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22439. */
  22440. set: function (value) {
  22441. if (this._lightmapMode === value) {
  22442. return;
  22443. }
  22444. this._lightmapMode = value;
  22445. this._markMeshesAsLightDirty();
  22446. },
  22447. enumerable: true,
  22448. configurable: true
  22449. });
  22450. /**
  22451. * Returns the string "Light".
  22452. * @returns the class name
  22453. */
  22454. Light.prototype.getClassName = function () {
  22455. return "Light";
  22456. };
  22457. /**
  22458. * Converts the light information to a readable string for debug purpose.
  22459. * @param fullDetails Supports for multiple levels of logging within scene loading
  22460. * @returns the human readable light info
  22461. */
  22462. Light.prototype.toString = function (fullDetails) {
  22463. var ret = "Name: " + this.name;
  22464. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  22465. if (this.animations) {
  22466. for (var i = 0; i < this.animations.length; i++) {
  22467. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22468. }
  22469. }
  22470. if (fullDetails) {
  22471. }
  22472. return ret;
  22473. };
  22474. /** @hidden */
  22475. Light.prototype._syncParentEnabledState = function () {
  22476. _super.prototype._syncParentEnabledState.call(this);
  22477. this._resyncMeshes();
  22478. };
  22479. /**
  22480. * Set the enabled state of this node.
  22481. * @param value - the new enabled state
  22482. */
  22483. Light.prototype.setEnabled = function (value) {
  22484. _super.prototype.setEnabled.call(this, value);
  22485. this._resyncMeshes();
  22486. };
  22487. /**
  22488. * Returns the Light associated shadow generator if any.
  22489. * @return the associated shadow generator.
  22490. */
  22491. Light.prototype.getShadowGenerator = function () {
  22492. return this._shadowGenerator;
  22493. };
  22494. /**
  22495. * Returns a Vector3, the absolute light position in the World.
  22496. * @returns the world space position of the light
  22497. */
  22498. Light.prototype.getAbsolutePosition = function () {
  22499. return BABYLON.Vector3.Zero();
  22500. };
  22501. /**
  22502. * Specifies if the light will affect the passed mesh.
  22503. * @param mesh The mesh to test against the light
  22504. * @return true the mesh is affected otherwise, false.
  22505. */
  22506. Light.prototype.canAffectMesh = function (mesh) {
  22507. if (!mesh) {
  22508. return true;
  22509. }
  22510. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  22511. return false;
  22512. }
  22513. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  22514. return false;
  22515. }
  22516. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  22517. return false;
  22518. }
  22519. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  22520. return false;
  22521. }
  22522. return true;
  22523. };
  22524. /**
  22525. * Sort function to order lights for rendering.
  22526. * @param a First Light object to compare to second.
  22527. * @param b Second Light object to compare first.
  22528. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  22529. */
  22530. Light.CompareLightsPriority = function (a, b) {
  22531. //shadow-casting lights have priority over non-shadow-casting lights
  22532. //the renderPrioirty is a secondary sort criterion
  22533. if (a.shadowEnabled !== b.shadowEnabled) {
  22534. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  22535. }
  22536. return b.renderPriority - a.renderPriority;
  22537. };
  22538. /**
  22539. * Releases resources associated with this node.
  22540. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22541. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22542. */
  22543. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22544. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22545. if (this._shadowGenerator) {
  22546. this._shadowGenerator.dispose();
  22547. this._shadowGenerator = null;
  22548. }
  22549. // Animations
  22550. this.getScene().stopAnimation(this);
  22551. // Remove from meshes
  22552. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22553. var mesh = _a[_i];
  22554. mesh._removeLightSource(this);
  22555. }
  22556. this._uniformBuffer.dispose();
  22557. // Remove from scene
  22558. this.getScene().removeLight(this);
  22559. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22560. };
  22561. /**
  22562. * Returns the light type ID (integer).
  22563. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  22564. */
  22565. Light.prototype.getTypeID = function () {
  22566. return 0;
  22567. };
  22568. /**
  22569. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  22570. * @returns the scaled intensity in intensity mode unit
  22571. */
  22572. Light.prototype.getScaledIntensity = function () {
  22573. return this._photometricScale * this.intensity;
  22574. };
  22575. /**
  22576. * Returns a new Light object, named "name", from the current one.
  22577. * @param name The name of the cloned light
  22578. * @returns the new created light
  22579. */
  22580. Light.prototype.clone = function (name) {
  22581. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  22582. if (!constructor) {
  22583. return null;
  22584. }
  22585. return BABYLON.SerializationHelper.Clone(constructor, this);
  22586. };
  22587. /**
  22588. * Serializes the current light into a Serialization object.
  22589. * @returns the serialized object.
  22590. */
  22591. Light.prototype.serialize = function () {
  22592. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22593. // Type
  22594. serializationObject.type = this.getTypeID();
  22595. // Parent
  22596. if (this.parent) {
  22597. serializationObject.parentId = this.parent.id;
  22598. }
  22599. // Inclusion / exclusions
  22600. if (this.excludedMeshes.length > 0) {
  22601. serializationObject.excludedMeshesIds = [];
  22602. this.excludedMeshes.forEach(function (mesh) {
  22603. serializationObject.excludedMeshesIds.push(mesh.id);
  22604. });
  22605. }
  22606. if (this.includedOnlyMeshes.length > 0) {
  22607. serializationObject.includedOnlyMeshesIds = [];
  22608. this.includedOnlyMeshes.forEach(function (mesh) {
  22609. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22610. });
  22611. }
  22612. // Animations
  22613. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22614. serializationObject.ranges = this.serializeAnimationRanges();
  22615. return serializationObject;
  22616. };
  22617. /**
  22618. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22619. * This new light is named "name" and added to the passed scene.
  22620. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22621. * @param name The friendly name of the light
  22622. * @param scene The scene the new light will belong to
  22623. * @returns the constructor function
  22624. */
  22625. Light.GetConstructorFromName = function (type, name, scene) {
  22626. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  22627. if (constructorFunc) {
  22628. return constructorFunc;
  22629. }
  22630. // Default to no light for none present once.
  22631. return null;
  22632. };
  22633. /**
  22634. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22635. * @param parsedLight The JSON representation of the light
  22636. * @param scene The scene to create the parsed light in
  22637. * @returns the created light after parsing
  22638. */
  22639. Light.Parse = function (parsedLight, scene) {
  22640. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22641. if (!constructor) {
  22642. return null;
  22643. }
  22644. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22645. // Inclusion / exclusions
  22646. if (parsedLight.excludedMeshesIds) {
  22647. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22648. }
  22649. if (parsedLight.includedOnlyMeshesIds) {
  22650. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22651. }
  22652. // Parent
  22653. if (parsedLight.parentId) {
  22654. light._waitingParentId = parsedLight.parentId;
  22655. }
  22656. // Animations
  22657. if (parsedLight.animations) {
  22658. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22659. var parsedAnimation = parsedLight.animations[animationIndex];
  22660. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22661. }
  22662. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22663. }
  22664. if (parsedLight.autoAnimate) {
  22665. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22666. }
  22667. return light;
  22668. };
  22669. Light.prototype._hookArrayForExcluded = function (array) {
  22670. var _this = this;
  22671. var oldPush = array.push;
  22672. array.push = function () {
  22673. var items = [];
  22674. for (var _i = 0; _i < arguments.length; _i++) {
  22675. items[_i] = arguments[_i];
  22676. }
  22677. var result = oldPush.apply(array, items);
  22678. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22679. var item = items_1[_a];
  22680. item._resyncLighSource(_this);
  22681. }
  22682. return result;
  22683. };
  22684. var oldSplice = array.splice;
  22685. array.splice = function (index, deleteCount) {
  22686. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22687. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22688. var item = deleted_1[_i];
  22689. item._resyncLighSource(_this);
  22690. }
  22691. return deleted;
  22692. };
  22693. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22694. var item = array_1[_i];
  22695. item._resyncLighSource(this);
  22696. }
  22697. };
  22698. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22699. var _this = this;
  22700. var oldPush = array.push;
  22701. array.push = function () {
  22702. var items = [];
  22703. for (var _i = 0; _i < arguments.length; _i++) {
  22704. items[_i] = arguments[_i];
  22705. }
  22706. var result = oldPush.apply(array, items);
  22707. _this._resyncMeshes();
  22708. return result;
  22709. };
  22710. var oldSplice = array.splice;
  22711. array.splice = function (index, deleteCount) {
  22712. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22713. _this._resyncMeshes();
  22714. return deleted;
  22715. };
  22716. this._resyncMeshes();
  22717. };
  22718. Light.prototype._resyncMeshes = function () {
  22719. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22720. var mesh = _a[_i];
  22721. mesh._resyncLighSource(this);
  22722. }
  22723. };
  22724. /**
  22725. * Forces the meshes to update their light related information in their rendering used effects
  22726. * @hidden Internal Use Only
  22727. */
  22728. Light.prototype._markMeshesAsLightDirty = function () {
  22729. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22730. var mesh = _a[_i];
  22731. if (mesh._lightSources.indexOf(this) !== -1) {
  22732. mesh._markSubMeshesAsLightDirty();
  22733. }
  22734. }
  22735. };
  22736. /**
  22737. * Recomputes the cached photometric scale if needed.
  22738. */
  22739. Light.prototype._computePhotometricScale = function () {
  22740. this._photometricScale = this._getPhotometricScale();
  22741. this.getScene().resetCachedMaterial();
  22742. };
  22743. /**
  22744. * Returns the Photometric Scale according to the light type and intensity mode.
  22745. */
  22746. Light.prototype._getPhotometricScale = function () {
  22747. var photometricScale = 0.0;
  22748. var lightTypeID = this.getTypeID();
  22749. //get photometric mode
  22750. var photometricMode = this.intensityMode;
  22751. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22752. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22753. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22754. }
  22755. else {
  22756. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22757. }
  22758. }
  22759. //compute photometric scale
  22760. switch (lightTypeID) {
  22761. case Light.LIGHTTYPEID_POINTLIGHT:
  22762. case Light.LIGHTTYPEID_SPOTLIGHT:
  22763. switch (photometricMode) {
  22764. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22765. photometricScale = 1.0 / (4.0 * Math.PI);
  22766. break;
  22767. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22768. photometricScale = 1.0;
  22769. break;
  22770. case Light.INTENSITYMODE_LUMINANCE:
  22771. photometricScale = this.radius * this.radius;
  22772. break;
  22773. }
  22774. break;
  22775. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22776. switch (photometricMode) {
  22777. case Light.INTENSITYMODE_ILLUMINANCE:
  22778. photometricScale = 1.0;
  22779. break;
  22780. case Light.INTENSITYMODE_LUMINANCE:
  22781. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22782. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22783. var apexAngleRadians = this.radius;
  22784. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22785. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22786. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22787. photometricScale = solidAngle;
  22788. break;
  22789. }
  22790. break;
  22791. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22792. // No fall off in hemisperic light.
  22793. photometricScale = 1.0;
  22794. break;
  22795. }
  22796. return photometricScale;
  22797. };
  22798. /**
  22799. * Reorder the light in the scene according to their defined priority.
  22800. * @hidden Internal Use Only
  22801. */
  22802. Light.prototype._reorderLightsInScene = function () {
  22803. var scene = this.getScene();
  22804. if (this._renderPriority != 0) {
  22805. scene.requireLightSorting = true;
  22806. }
  22807. this.getScene().sortLightsByPriority();
  22808. };
  22809. /**
  22810. * Falloff Default: light is falling off following the material specification:
  22811. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22812. */
  22813. Light.FALLOFF_DEFAULT = 0;
  22814. /**
  22815. * Falloff Physical: light is falling off following the inverse squared distance law.
  22816. */
  22817. Light.FALLOFF_PHYSICAL = 1;
  22818. /**
  22819. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22820. * to enhance interoperability with other engines.
  22821. */
  22822. Light.FALLOFF_GLTF = 2;
  22823. /**
  22824. * Falloff Standard: light is falling off like in the standard material
  22825. * to enhance interoperability with other materials.
  22826. */
  22827. Light.FALLOFF_STANDARD = 3;
  22828. //lightmapMode Consts
  22829. /**
  22830. * If every light affecting the material is in this lightmapMode,
  22831. * material.lightmapTexture adds or multiplies
  22832. * (depends on material.useLightmapAsShadowmap)
  22833. * after every other light calculations.
  22834. */
  22835. Light.LIGHTMAP_DEFAULT = 0;
  22836. /**
  22837. * material.lightmapTexture as only diffuse lighting from this light
  22838. * adds only specular lighting from this light
  22839. * adds dynamic shadows
  22840. */
  22841. Light.LIGHTMAP_SPECULAR = 1;
  22842. /**
  22843. * material.lightmapTexture as only lighting
  22844. * no light calculation from this light
  22845. * only adds dynamic shadows from this light
  22846. */
  22847. Light.LIGHTMAP_SHADOWSONLY = 2;
  22848. // Intensity Mode Consts
  22849. /**
  22850. * Each light type uses the default quantity according to its type:
  22851. * point/spot lights use luminous intensity
  22852. * directional lights use illuminance
  22853. */
  22854. Light.INTENSITYMODE_AUTOMATIC = 0;
  22855. /**
  22856. * lumen (lm)
  22857. */
  22858. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  22859. /**
  22860. * candela (lm/sr)
  22861. */
  22862. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22863. /**
  22864. * lux (lm/m^2)
  22865. */
  22866. Light.INTENSITYMODE_ILLUMINANCE = 3;
  22867. /**
  22868. * nit (cd/m^2)
  22869. */
  22870. Light.INTENSITYMODE_LUMINANCE = 4;
  22871. // Light types ids const.
  22872. /**
  22873. * Light type const id of the point light.
  22874. */
  22875. Light.LIGHTTYPEID_POINTLIGHT = 0;
  22876. /**
  22877. * Light type const id of the directional light.
  22878. */
  22879. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22880. /**
  22881. * Light type const id of the spot light.
  22882. */
  22883. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  22884. /**
  22885. * Light type const id of the hemispheric light.
  22886. */
  22887. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22888. __decorate([
  22889. BABYLON.serializeAsColor3()
  22890. ], Light.prototype, "diffuse", void 0);
  22891. __decorate([
  22892. BABYLON.serializeAsColor3()
  22893. ], Light.prototype, "specular", void 0);
  22894. __decorate([
  22895. BABYLON.serialize()
  22896. ], Light.prototype, "falloffType", void 0);
  22897. __decorate([
  22898. BABYLON.serialize()
  22899. ], Light.prototype, "intensity", void 0);
  22900. __decorate([
  22901. BABYLON.serialize()
  22902. ], Light.prototype, "range", null);
  22903. __decorate([
  22904. BABYLON.serialize()
  22905. ], Light.prototype, "intensityMode", null);
  22906. __decorate([
  22907. BABYLON.serialize()
  22908. ], Light.prototype, "radius", null);
  22909. __decorate([
  22910. BABYLON.serialize()
  22911. ], Light.prototype, "_renderPriority", void 0);
  22912. __decorate([
  22913. BABYLON.expandToProperty("_reorderLightsInScene")
  22914. ], Light.prototype, "renderPriority", void 0);
  22915. __decorate([
  22916. BABYLON.serialize("shadowEnabled")
  22917. ], Light.prototype, "_shadowEnabled", void 0);
  22918. __decorate([
  22919. BABYLON.serialize("excludeWithLayerMask")
  22920. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22921. __decorate([
  22922. BABYLON.serialize("includeOnlyWithLayerMask")
  22923. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22924. __decorate([
  22925. BABYLON.serialize("lightmapMode")
  22926. ], Light.prototype, "_lightmapMode", void 0);
  22927. return Light;
  22928. }(BABYLON.Node));
  22929. BABYLON.Light = Light;
  22930. })(BABYLON || (BABYLON = {}));
  22931. //# sourceMappingURL=babylon.light.js.map
  22932. var BABYLON;
  22933. (function (BABYLON) {
  22934. /**
  22935. * This is the base class of all the camera used in the application.
  22936. * @see http://doc.babylonjs.com/features/cameras
  22937. */
  22938. var Camera = /** @class */ (function (_super) {
  22939. __extends(Camera, _super);
  22940. /**
  22941. * Instantiates a new camera object.
  22942. * This should not be used directly but through the inherited cameras: ArcRotate, Free...
  22943. * @see http://doc.babylonjs.com/features/cameras
  22944. * @param name Defines the name of the camera in the scene
  22945. * @param position Defines the position of the camera
  22946. * @param scene Defines the scene the camera belongs too
  22947. * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene
  22948. */
  22949. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22950. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22951. var _this = _super.call(this, name, scene) || this;
  22952. /**
  22953. * The vector the camera should consider as up.
  22954. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22955. */
  22956. _this.upVector = BABYLON.Vector3.Up();
  22957. /**
  22958. * Define the current limit on the left side for an orthographic camera
  22959. * In scene unit
  22960. */
  22961. _this.orthoLeft = null;
  22962. /**
  22963. * Define the current limit on the right side for an orthographic camera
  22964. * In scene unit
  22965. */
  22966. _this.orthoRight = null;
  22967. /**
  22968. * Define the current limit on the bottom side for an orthographic camera
  22969. * In scene unit
  22970. */
  22971. _this.orthoBottom = null;
  22972. /**
  22973. * Define the current limit on the top side for an orthographic camera
  22974. * In scene unit
  22975. */
  22976. _this.orthoTop = null;
  22977. /**
  22978. * Field Of View is set in Radians. (default is 0.8)
  22979. */
  22980. _this.fov = 0.8;
  22981. /**
  22982. * Define the minimum distance the camera can see from.
  22983. * This is important to note that the depth buffer are not infinite and the closer it starts
  22984. * the more your scene might encounter depth fighting issue.
  22985. */
  22986. _this.minZ = 1;
  22987. /**
  22988. * Define the maximum distance the camera can see to.
  22989. * This is important to note that the depth buffer are not infinite and the further it end
  22990. * the more your scene might encounter depth fighting issue.
  22991. */
  22992. _this.maxZ = 10000.0;
  22993. /**
  22994. * Define the default inertia of the camera.
  22995. * This helps giving a smooth feeling to the camera movement.
  22996. */
  22997. _this.inertia = 0.9;
  22998. /**
  22999. * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.PERSPECTIVE_ORTHOGRAPHIC)
  23000. */
  23001. _this.mode = Camera.PERSPECTIVE_CAMERA;
  23002. /**
  23003. * Define wether the camera is intermediate.
  23004. * This is usefull to not present the output directly to the screen in case of rig without post process for instance
  23005. */
  23006. _this.isIntermediate = false;
  23007. /**
  23008. * Define the viewport of the camera.
  23009. * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.
  23010. */
  23011. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  23012. /**
  23013. * Restricts the camera to viewing objects with the same layerMask.
  23014. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  23015. */
  23016. _this.layerMask = 0x0FFFFFFF;
  23017. /**
  23018. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  23019. */
  23020. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  23021. /**
  23022. * Rig mode of the camera.
  23023. * This is usefull to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes.
  23024. * This is normally controlled byt the camera themselves as internal use.
  23025. */
  23026. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  23027. /**
  23028. * Defines the list of custom render target the camera should render to.
  23029. * This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere
  23030. * else in the scene.
  23031. */
  23032. _this.customRenderTargets = new Array();
  23033. /**
  23034. * Observable triggered when the camera view matrix has changed.
  23035. */
  23036. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  23037. /**
  23038. * Observable triggered when the camera Projection matrix has changed.
  23039. */
  23040. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  23041. /**
  23042. * Observable triggered when the inputs have been processed.
  23043. */
  23044. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  23045. /**
  23046. * Observable triggered when reset has been called and applied to the camera.
  23047. */
  23048. _this.onRestoreStateObservable = new BABYLON.Observable();
  23049. /** @hidden */
  23050. _this._rigCameras = new Array();
  23051. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  23052. /** @hidden */
  23053. _this._skipRendering = false;
  23054. /** @hidden */
  23055. _this._projectionMatrix = new BABYLON.Matrix();
  23056. /** @hidden */
  23057. _this._postProcesses = new Array();
  23058. /** @hidden */
  23059. _this._activeMeshes = new BABYLON.SmartArray(256);
  23060. _this._globalPosition = BABYLON.Vector3.Zero();
  23061. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  23062. _this._doNotComputeProjectionMatrix = false;
  23063. _this._transformMatrix = BABYLON.Matrix.Zero();
  23064. _this._refreshFrustumPlanes = true;
  23065. _this.getScene().addCamera(_this);
  23066. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  23067. _this.getScene().activeCamera = _this;
  23068. }
  23069. _this.position = position;
  23070. return _this;
  23071. }
  23072. /**
  23073. * Store current camera state (fov, position, etc..)
  23074. * @returns the camera
  23075. */
  23076. Camera.prototype.storeState = function () {
  23077. this._stateStored = true;
  23078. this._storedFov = this.fov;
  23079. return this;
  23080. };
  23081. /**
  23082. * Restores the camera state values if it has been stored. You must call storeState() first
  23083. */
  23084. Camera.prototype._restoreStateValues = function () {
  23085. if (!this._stateStored) {
  23086. return false;
  23087. }
  23088. this.fov = this._storedFov;
  23089. return true;
  23090. };
  23091. /**
  23092. * Restored camera state. You must call storeState() first.
  23093. * @returns true if restored and false otherwise
  23094. */
  23095. Camera.prototype.restoreState = function () {
  23096. if (this._restoreStateValues()) {
  23097. this.onRestoreStateObservable.notifyObservers(this);
  23098. return true;
  23099. }
  23100. return false;
  23101. };
  23102. /**
  23103. * Gets the class name of the camera.
  23104. * @returns the class name
  23105. */
  23106. Camera.prototype.getClassName = function () {
  23107. return "Camera";
  23108. };
  23109. /**
  23110. * Gets a string representation of the camera usefull for debug purpose.
  23111. * @param fullDetails Defines that a more verboe level of logging is required
  23112. * @returns the string representation
  23113. */
  23114. Camera.prototype.toString = function (fullDetails) {
  23115. var ret = "Name: " + this.name;
  23116. ret += ", type: " + this.getClassName();
  23117. if (this.animations) {
  23118. for (var i = 0; i < this.animations.length; i++) {
  23119. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23120. }
  23121. }
  23122. if (fullDetails) {
  23123. }
  23124. return ret;
  23125. };
  23126. Object.defineProperty(Camera.prototype, "globalPosition", {
  23127. /**
  23128. * Gets the current world space position of the camera.
  23129. */
  23130. get: function () {
  23131. return this._globalPosition;
  23132. },
  23133. enumerable: true,
  23134. configurable: true
  23135. });
  23136. /**
  23137. * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)
  23138. * @returns the active meshe list
  23139. */
  23140. Camera.prototype.getActiveMeshes = function () {
  23141. return this._activeMeshes;
  23142. };
  23143. /**
  23144. * Check wether a mesh is part of the current active mesh list of the camera
  23145. * @param mesh Defines the mesh to check
  23146. * @returns true if active, false otherwise
  23147. */
  23148. Camera.prototype.isActiveMesh = function (mesh) {
  23149. return (this._activeMeshes.indexOf(mesh) !== -1);
  23150. };
  23151. /**
  23152. * Is this camera ready to be used/rendered
  23153. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  23154. * @return true if the camera is ready
  23155. */
  23156. Camera.prototype.isReady = function (completeCheck) {
  23157. if (completeCheck === void 0) { completeCheck = false; }
  23158. if (completeCheck) {
  23159. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  23160. var pp = _a[_i];
  23161. if (pp && !pp.isReady()) {
  23162. return false;
  23163. }
  23164. }
  23165. }
  23166. return _super.prototype.isReady.call(this, completeCheck);
  23167. };
  23168. /** @hidden */
  23169. Camera.prototype._initCache = function () {
  23170. _super.prototype._initCache.call(this);
  23171. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23172. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23173. this._cache.mode = undefined;
  23174. this._cache.minZ = undefined;
  23175. this._cache.maxZ = undefined;
  23176. this._cache.fov = undefined;
  23177. this._cache.fovMode = undefined;
  23178. this._cache.aspectRatio = undefined;
  23179. this._cache.orthoLeft = undefined;
  23180. this._cache.orthoRight = undefined;
  23181. this._cache.orthoBottom = undefined;
  23182. this._cache.orthoTop = undefined;
  23183. this._cache.renderWidth = undefined;
  23184. this._cache.renderHeight = undefined;
  23185. };
  23186. /** @hidden */
  23187. Camera.prototype._updateCache = function (ignoreParentClass) {
  23188. if (!ignoreParentClass) {
  23189. _super.prototype._updateCache.call(this);
  23190. }
  23191. this._cache.position.copyFrom(this.position);
  23192. this._cache.upVector.copyFrom(this.upVector);
  23193. };
  23194. /** @hidden */
  23195. Camera.prototype._isSynchronized = function () {
  23196. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  23197. };
  23198. /** @hidden */
  23199. Camera.prototype._isSynchronizedViewMatrix = function () {
  23200. if (!_super.prototype._isSynchronized.call(this))
  23201. return false;
  23202. return this._cache.position.equals(this.position)
  23203. && this._cache.upVector.equals(this.upVector)
  23204. && this.isSynchronizedWithParent();
  23205. };
  23206. /** @hidden */
  23207. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  23208. var check = this._cache.mode === this.mode
  23209. && this._cache.minZ === this.minZ
  23210. && this._cache.maxZ === this.maxZ;
  23211. if (!check) {
  23212. return false;
  23213. }
  23214. var engine = this.getEngine();
  23215. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23216. check = this._cache.fov === this.fov
  23217. && this._cache.fovMode === this.fovMode
  23218. && this._cache.aspectRatio === engine.getAspectRatio(this);
  23219. }
  23220. else {
  23221. check = this._cache.orthoLeft === this.orthoLeft
  23222. && this._cache.orthoRight === this.orthoRight
  23223. && this._cache.orthoBottom === this.orthoBottom
  23224. && this._cache.orthoTop === this.orthoTop
  23225. && this._cache.renderWidth === engine.getRenderWidth()
  23226. && this._cache.renderHeight === engine.getRenderHeight();
  23227. }
  23228. return check;
  23229. };
  23230. /**
  23231. * Attach the input controls to a specific dom element to get the input from.
  23232. * @param element Defines the element the controls should be listened from
  23233. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  23234. */
  23235. Camera.prototype.attachControl = function (element, noPreventDefault) {
  23236. };
  23237. /**
  23238. * Detach the current controls from the specified dom element.
  23239. * @param element Defines the element to stop listening the inputs from
  23240. */
  23241. Camera.prototype.detachControl = function (element) {
  23242. };
  23243. /**
  23244. * Update the camera state according to the different inputs gathered during the frame.
  23245. */
  23246. Camera.prototype.update = function () {
  23247. this._checkInputs();
  23248. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23249. this._updateRigCameras();
  23250. }
  23251. };
  23252. /** @hidden */
  23253. Camera.prototype._checkInputs = function () {
  23254. this.onAfterCheckInputsObservable.notifyObservers(this);
  23255. };
  23256. Object.defineProperty(Camera.prototype, "rigCameras", {
  23257. /** @hidden */
  23258. get: function () {
  23259. return this._rigCameras;
  23260. },
  23261. enumerable: true,
  23262. configurable: true
  23263. });
  23264. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  23265. /**
  23266. * Gets the post process used by the rig cameras
  23267. */
  23268. get: function () {
  23269. return this._rigPostProcess;
  23270. },
  23271. enumerable: true,
  23272. configurable: true
  23273. });
  23274. /**
  23275. * Internal, gets the first post proces.
  23276. * @returns the first post process to be run on this camera.
  23277. */
  23278. Camera.prototype._getFirstPostProcess = function () {
  23279. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  23280. if (this._postProcesses[ppIndex] !== null) {
  23281. return this._postProcesses[ppIndex];
  23282. }
  23283. }
  23284. return null;
  23285. };
  23286. Camera.prototype._cascadePostProcessesToRigCams = function () {
  23287. // invalidate framebuffer
  23288. var firstPostProcess = this._getFirstPostProcess();
  23289. if (firstPostProcess) {
  23290. firstPostProcess.markTextureDirty();
  23291. }
  23292. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  23293. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  23294. var cam = this._rigCameras[i];
  23295. var rigPostProcess = cam._rigPostProcess;
  23296. // for VR rig, there does not have to be a post process
  23297. if (rigPostProcess) {
  23298. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  23299. if (isPass) {
  23300. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  23301. cam.isIntermediate = this._postProcesses.length === 0;
  23302. }
  23303. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  23304. rigPostProcess.markTextureDirty();
  23305. }
  23306. else {
  23307. cam._postProcesses = this._postProcesses.slice(0);
  23308. }
  23309. }
  23310. };
  23311. /**
  23312. * Attach a post process to the camera.
  23313. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23314. * @param postProcess The post process to attach to the camera
  23315. * @param insertAt The position of the post process in case several of them are in use in the scene
  23316. * @returns the position the post process has been inserted at
  23317. */
  23318. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  23319. if (insertAt === void 0) { insertAt = null; }
  23320. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  23321. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  23322. return 0;
  23323. }
  23324. if (insertAt == null || insertAt < 0) {
  23325. this._postProcesses.push(postProcess);
  23326. }
  23327. else if (this._postProcesses[insertAt] === null) {
  23328. this._postProcesses[insertAt] = postProcess;
  23329. }
  23330. else {
  23331. this._postProcesses.splice(insertAt, 0, postProcess);
  23332. }
  23333. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23334. return this._postProcesses.indexOf(postProcess);
  23335. };
  23336. /**
  23337. * Detach a post process to the camera.
  23338. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23339. * @param postProcess The post process to detach from the camera
  23340. */
  23341. Camera.prototype.detachPostProcess = function (postProcess) {
  23342. var idx = this._postProcesses.indexOf(postProcess);
  23343. if (idx !== -1) {
  23344. this._postProcesses[idx] = null;
  23345. }
  23346. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23347. };
  23348. /**
  23349. * Gets the current world matrix of the camera
  23350. */
  23351. Camera.prototype.getWorldMatrix = function () {
  23352. if (this._isSynchronizedViewMatrix()) {
  23353. return this._worldMatrix;
  23354. }
  23355. // Getting the the view matrix will also compute the world matrix.
  23356. this.getViewMatrix();
  23357. return this._worldMatrix;
  23358. };
  23359. /** @hidden */
  23360. Camera.prototype._getViewMatrix = function () {
  23361. return BABYLON.Matrix.Identity();
  23362. };
  23363. /**
  23364. * Gets the current view matrix of the camera.
  23365. * @param force forces the camera to recompute the matrix without looking at the cached state
  23366. * @returns the view matrix
  23367. */
  23368. Camera.prototype.getViewMatrix = function (force) {
  23369. if (!force && this._isSynchronizedViewMatrix()) {
  23370. return this._computedViewMatrix;
  23371. }
  23372. this.updateCache();
  23373. this._computedViewMatrix = this._getViewMatrix();
  23374. this._currentRenderId = this.getScene().getRenderId();
  23375. this._childRenderId = this._currentRenderId;
  23376. this._refreshFrustumPlanes = true;
  23377. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  23378. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  23379. }
  23380. this.onViewMatrixChangedObservable.notifyObservers(this);
  23381. this._computedViewMatrix.invertToRef(this._worldMatrix);
  23382. return this._computedViewMatrix;
  23383. };
  23384. /**
  23385. * Freeze the projection matrix.
  23386. * It will prevent the cache check of the camera projection compute and can speed up perf
  23387. * if no parameter of the camera are meant to change
  23388. * @param projection Defines manually a projection if necessary
  23389. */
  23390. Camera.prototype.freezeProjectionMatrix = function (projection) {
  23391. this._doNotComputeProjectionMatrix = true;
  23392. if (projection !== undefined) {
  23393. this._projectionMatrix = projection;
  23394. }
  23395. };
  23396. ;
  23397. /**
  23398. * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
  23399. */
  23400. Camera.prototype.unfreezeProjectionMatrix = function () {
  23401. this._doNotComputeProjectionMatrix = false;
  23402. };
  23403. ;
  23404. /**
  23405. * Gets the current projection matrix of the camera.
  23406. * @param force forces the camera to recompute the matrix without looking at the cached state
  23407. * @returns the projection matrix
  23408. */
  23409. Camera.prototype.getProjectionMatrix = function (force) {
  23410. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  23411. return this._projectionMatrix;
  23412. }
  23413. // Cache
  23414. this._cache.mode = this.mode;
  23415. this._cache.minZ = this.minZ;
  23416. this._cache.maxZ = this.maxZ;
  23417. // Matrix
  23418. this._refreshFrustumPlanes = true;
  23419. var engine = this.getEngine();
  23420. var scene = this.getScene();
  23421. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23422. this._cache.fov = this.fov;
  23423. this._cache.fovMode = this.fovMode;
  23424. this._cache.aspectRatio = engine.getAspectRatio(this);
  23425. if (this.minZ <= 0) {
  23426. this.minZ = 0.1;
  23427. }
  23428. if (scene.useRightHandedSystem) {
  23429. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23430. }
  23431. else {
  23432. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23433. }
  23434. }
  23435. else {
  23436. var halfWidth = engine.getRenderWidth() / 2.0;
  23437. var halfHeight = engine.getRenderHeight() / 2.0;
  23438. if (scene.useRightHandedSystem) {
  23439. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23440. }
  23441. else {
  23442. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23443. }
  23444. this._cache.orthoLeft = this.orthoLeft;
  23445. this._cache.orthoRight = this.orthoRight;
  23446. this._cache.orthoBottom = this.orthoBottom;
  23447. this._cache.orthoTop = this.orthoTop;
  23448. this._cache.renderWidth = engine.getRenderWidth();
  23449. this._cache.renderHeight = engine.getRenderHeight();
  23450. }
  23451. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  23452. return this._projectionMatrix;
  23453. };
  23454. /**
  23455. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  23456. * @returns a Matrix
  23457. */
  23458. Camera.prototype.getTransformationMatrix = function () {
  23459. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23460. return this._transformMatrix;
  23461. };
  23462. Camera.prototype._updateFrustumPlanes = function () {
  23463. if (!this._refreshFrustumPlanes) {
  23464. return;
  23465. }
  23466. this.getTransformationMatrix();
  23467. if (!this._frustumPlanes) {
  23468. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23469. }
  23470. else {
  23471. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23472. }
  23473. this._refreshFrustumPlanes = false;
  23474. };
  23475. /**
  23476. * Checks if a cullable object (mesh...) is in the camera frustum
  23477. * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
  23478. * @param target The object to check
  23479. * @returns true if the object is in frustum otherwise false
  23480. */
  23481. Camera.prototype.isInFrustum = function (target) {
  23482. this._updateFrustumPlanes();
  23483. return target.isInFrustum(this._frustumPlanes);
  23484. };
  23485. /**
  23486. * Checks if a cullable object (mesh...) is in the camera frustum
  23487. * Unlike isInFrustum this cheks the full bounding box
  23488. * @param target The object to check
  23489. * @returns true if the object is in frustum otherwise false
  23490. */
  23491. Camera.prototype.isCompletelyInFrustum = function (target) {
  23492. this._updateFrustumPlanes();
  23493. return target.isCompletelyInFrustum(this._frustumPlanes);
  23494. };
  23495. /**
  23496. * Gets a ray in the forward direction from the camera.
  23497. * @param length Defines the length of the ray to create
  23498. * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
  23499. * @param origin Defines the start point of the ray which defaults to the camera position
  23500. * @returns the forward ray
  23501. */
  23502. Camera.prototype.getForwardRay = function (length, transform, origin) {
  23503. if (length === void 0) { length = 100; }
  23504. if (!transform) {
  23505. transform = this.getWorldMatrix();
  23506. }
  23507. if (!origin) {
  23508. origin = this.position;
  23509. }
  23510. var forward = new BABYLON.Vector3(0, 0, 1);
  23511. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  23512. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  23513. return new BABYLON.Ray(origin, direction, length);
  23514. };
  23515. /**
  23516. * Releases resources associated with this node.
  23517. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  23518. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  23519. */
  23520. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  23521. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  23522. // Observables
  23523. this.onViewMatrixChangedObservable.clear();
  23524. this.onProjectionMatrixChangedObservable.clear();
  23525. this.onAfterCheckInputsObservable.clear();
  23526. this.onRestoreStateObservable.clear();
  23527. // Inputs
  23528. if (this.inputs) {
  23529. this.inputs.clear();
  23530. }
  23531. // Animations
  23532. this.getScene().stopAnimation(this);
  23533. // Remove from scene
  23534. this.getScene().removeCamera(this);
  23535. while (this._rigCameras.length > 0) {
  23536. var camera = this._rigCameras.pop();
  23537. if (camera) {
  23538. camera.dispose();
  23539. }
  23540. }
  23541. // Postprocesses
  23542. if (this._rigPostProcess) {
  23543. this._rigPostProcess.dispose(this);
  23544. this._rigPostProcess = null;
  23545. this._postProcesses = [];
  23546. }
  23547. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23548. this._rigPostProcess = null;
  23549. this._postProcesses = [];
  23550. }
  23551. else {
  23552. var i = this._postProcesses.length;
  23553. while (--i >= 0) {
  23554. var postProcess = this._postProcesses[i];
  23555. if (postProcess) {
  23556. postProcess.dispose(this);
  23557. }
  23558. }
  23559. }
  23560. // Render targets
  23561. var i = this.customRenderTargets.length;
  23562. while (--i >= 0) {
  23563. this.customRenderTargets[i].dispose();
  23564. }
  23565. this.customRenderTargets = [];
  23566. // Active Meshes
  23567. this._activeMeshes.dispose();
  23568. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  23569. };
  23570. Object.defineProperty(Camera.prototype, "leftCamera", {
  23571. /**
  23572. * Gets the left camera of a rig setup in case of Rigged Camera
  23573. */
  23574. get: function () {
  23575. if (this._rigCameras.length < 1) {
  23576. return null;
  23577. }
  23578. return this._rigCameras[0];
  23579. },
  23580. enumerable: true,
  23581. configurable: true
  23582. });
  23583. Object.defineProperty(Camera.prototype, "rightCamera", {
  23584. /**
  23585. * Gets the right camera of a rig setup in case of Rigged Camera
  23586. */
  23587. get: function () {
  23588. if (this._rigCameras.length < 2) {
  23589. return null;
  23590. }
  23591. return this._rigCameras[1];
  23592. },
  23593. enumerable: true,
  23594. configurable: true
  23595. });
  23596. /**
  23597. * Gets the left camera target of a rig setup in case of Rigged Camera
  23598. * @returns the target position
  23599. */
  23600. Camera.prototype.getLeftTarget = function () {
  23601. if (this._rigCameras.length < 1) {
  23602. return null;
  23603. }
  23604. return this._rigCameras[0].getTarget();
  23605. };
  23606. /**
  23607. * Gets the right camera target of a rig setup in case of Rigged Camera
  23608. * @returns the target position
  23609. */
  23610. Camera.prototype.getRightTarget = function () {
  23611. if (this._rigCameras.length < 2) {
  23612. return null;
  23613. }
  23614. return this._rigCameras[1].getTarget();
  23615. };
  23616. /**
  23617. * @hidden
  23618. */
  23619. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  23620. if (this.cameraRigMode === mode) {
  23621. return;
  23622. }
  23623. while (this._rigCameras.length > 0) {
  23624. var camera = this._rigCameras.pop();
  23625. if (camera) {
  23626. camera.dispose();
  23627. }
  23628. }
  23629. this.cameraRigMode = mode;
  23630. this._cameraRigParams = {};
  23631. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  23632. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  23633. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  23634. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  23635. // create the rig cameras, unless none
  23636. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23637. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  23638. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  23639. if (leftCamera && rightCamera) {
  23640. this._rigCameras.push(leftCamera);
  23641. this._rigCameras.push(rightCamera);
  23642. }
  23643. }
  23644. switch (this.cameraRigMode) {
  23645. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  23646. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23647. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  23648. break;
  23649. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  23650. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  23651. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  23652. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  23653. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23654. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  23655. break;
  23656. case Camera.RIG_MODE_VR:
  23657. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  23658. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  23659. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23660. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23661. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  23662. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  23663. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  23664. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  23665. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23666. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23667. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  23668. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  23669. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  23670. if (metrics.compensateDistortion) {
  23671. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  23672. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  23673. }
  23674. break;
  23675. case Camera.RIG_MODE_WEBVR:
  23676. if (rigParams.vrDisplay) {
  23677. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  23678. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  23679. //Left eye
  23680. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23681. this._rigCameras[0].setCameraRigParameter("left", true);
  23682. //leaving this for future reference
  23683. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  23684. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  23685. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  23686. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23687. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23688. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23689. this._rigCameras[0].parent = this;
  23690. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  23691. //Right eye
  23692. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23693. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  23694. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  23695. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  23696. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23697. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23698. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23699. this._rigCameras[1].parent = this;
  23700. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  23701. if (Camera.UseAlternateWebVRRendering) {
  23702. this._rigCameras[1]._skipRendering = true;
  23703. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  23704. }
  23705. }
  23706. break;
  23707. }
  23708. this._cascadePostProcessesToRigCams();
  23709. this.update();
  23710. };
  23711. Camera.prototype._getVRProjectionMatrix = function () {
  23712. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  23713. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  23714. return this._projectionMatrix;
  23715. };
  23716. Camera.prototype._updateCameraRotationMatrix = function () {
  23717. //Here for WebVR
  23718. };
  23719. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  23720. //Here for WebVR
  23721. };
  23722. /**
  23723. * This function MUST be overwritten by the different WebVR cameras available.
  23724. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23725. */
  23726. Camera.prototype._getWebVRProjectionMatrix = function () {
  23727. return BABYLON.Matrix.Identity();
  23728. };
  23729. /**
  23730. * This function MUST be overwritten by the different WebVR cameras available.
  23731. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23732. */
  23733. Camera.prototype._getWebVRViewMatrix = function () {
  23734. return BABYLON.Matrix.Identity();
  23735. };
  23736. /** @hidden */
  23737. Camera.prototype.setCameraRigParameter = function (name, value) {
  23738. if (!this._cameraRigParams) {
  23739. this._cameraRigParams = {};
  23740. }
  23741. this._cameraRigParams[name] = value;
  23742. //provisionnally:
  23743. if (name === "interaxialDistance") {
  23744. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  23745. }
  23746. };
  23747. /**
  23748. * needs to be overridden by children so sub has required properties to be copied
  23749. * @hidden
  23750. */
  23751. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  23752. return null;
  23753. };
  23754. /**
  23755. * May need to be overridden by children
  23756. * @hidden
  23757. */
  23758. Camera.prototype._updateRigCameras = function () {
  23759. for (var i = 0; i < this._rigCameras.length; i++) {
  23760. this._rigCameras[i].minZ = this.minZ;
  23761. this._rigCameras[i].maxZ = this.maxZ;
  23762. this._rigCameras[i].fov = this.fov;
  23763. }
  23764. // only update viewport when ANAGLYPH
  23765. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23766. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23767. }
  23768. };
  23769. /** @hidden */
  23770. Camera.prototype._setupInputs = function () {
  23771. };
  23772. /**
  23773. * Serialiaze the camera setup to a json represention
  23774. * @returns the JSON representation
  23775. */
  23776. Camera.prototype.serialize = function () {
  23777. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23778. // Type
  23779. serializationObject.type = this.getClassName();
  23780. // Parent
  23781. if (this.parent) {
  23782. serializationObject.parentId = this.parent.id;
  23783. }
  23784. if (this.inputs) {
  23785. this.inputs.serialize(serializationObject);
  23786. }
  23787. // Animations
  23788. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23789. serializationObject.ranges = this.serializeAnimationRanges();
  23790. return serializationObject;
  23791. };
  23792. /**
  23793. * Clones the current camera.
  23794. * @param name The cloned camera name
  23795. * @returns the cloned camera
  23796. */
  23797. Camera.prototype.clone = function (name) {
  23798. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23799. };
  23800. /**
  23801. * Gets the direction of the camera relative to a given local axis.
  23802. * @param localAxis Defines the reference axis to provide a relative direction.
  23803. * @return the direction
  23804. */
  23805. Camera.prototype.getDirection = function (localAxis) {
  23806. var result = BABYLON.Vector3.Zero();
  23807. this.getDirectionToRef(localAxis, result);
  23808. return result;
  23809. };
  23810. /**
  23811. * Gets the direction of the camera relative to a given local axis into a passed vector.
  23812. * @param localAxis Defines the reference axis to provide a relative direction.
  23813. * @param result Defines the vector to store the result in
  23814. */
  23815. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23816. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23817. };
  23818. /**
  23819. * Gets a camera constructor for a given camera type
  23820. * @param type The type of the camera to construct (should be equal to one of the camera class name)
  23821. * @param name The name of the camera the result will be able to instantiate
  23822. * @param scene The scene the result will construct the camera in
  23823. * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes
  23824. * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side
  23825. * @returns a factory method to construc the camera
  23826. */
  23827. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23828. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23829. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23830. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  23831. interaxial_distance: interaxial_distance,
  23832. isStereoscopicSideBySide: isStereoscopicSideBySide
  23833. });
  23834. if (constructorFunc) {
  23835. return constructorFunc;
  23836. }
  23837. // Default to universal camera
  23838. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23839. };
  23840. /**
  23841. * Compute the world matrix of the camera.
  23842. * @returns the camera workd matrix
  23843. */
  23844. Camera.prototype.computeWorldMatrix = function () {
  23845. return this.getWorldMatrix();
  23846. };
  23847. /**
  23848. * Parse a JSON and creates the camera from the parsed information
  23849. * @param parsedCamera The JSON to parse
  23850. * @param scene The scene to instantiate the camera in
  23851. * @returns the newly constructed camera
  23852. */
  23853. Camera.Parse = function (parsedCamera, scene) {
  23854. var type = parsedCamera.type;
  23855. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23856. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23857. // Parent
  23858. if (parsedCamera.parentId) {
  23859. camera._waitingParentId = parsedCamera.parentId;
  23860. }
  23861. //If camera has an input manager, let it parse inputs settings
  23862. if (camera.inputs) {
  23863. camera.inputs.parse(parsedCamera);
  23864. camera._setupInputs();
  23865. }
  23866. if (camera.setPosition) { // need to force position
  23867. camera.position.copyFromFloats(0, 0, 0);
  23868. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23869. }
  23870. // Target
  23871. if (parsedCamera.target) {
  23872. if (camera.setTarget) {
  23873. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23874. }
  23875. }
  23876. // Apply 3d rig, when found
  23877. if (parsedCamera.cameraRigMode) {
  23878. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23879. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23880. }
  23881. // Animations
  23882. if (parsedCamera.animations) {
  23883. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23884. var parsedAnimation = parsedCamera.animations[animationIndex];
  23885. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23886. }
  23887. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23888. }
  23889. if (parsedCamera.autoAnimate) {
  23890. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23891. }
  23892. return camera;
  23893. };
  23894. /**
  23895. * This is the default projection mode used by the cameras.
  23896. * It helps recreating a feeling of perspective and better appreciate depth.
  23897. * This is the best way to simulate real life cameras.
  23898. */
  23899. Camera.PERSPECTIVE_CAMERA = 0;
  23900. /**
  23901. * This helps creating camera with an orthographic mode.
  23902. * Orthographic is commonly used in engineering as a means to produce object specifications that communicate dimensions unambiguously, each line of 1 unit length (cm, meter..whatever) will appear to have the same length everywhere on the drawing. This allows the drafter to dimension only a subset of lines and let the reader know that other lines of that length on the drawing are also that length in reality. Every parallel line in the drawing is also parallel in the object.
  23903. */
  23904. Camera.ORTHOGRAPHIC_CAMERA = 1;
  23905. /**
  23906. * This is the default FOV mode for perspective cameras.
  23907. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  23908. */
  23909. Camera.FOVMODE_VERTICAL_FIXED = 0;
  23910. /**
  23911. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  23912. */
  23913. Camera.FOVMODE_HORIZONTAL_FIXED = 1;
  23914. /**
  23915. * This specifies ther is no need for a camera rig.
  23916. * Basically only one eye is rendered corresponding to the camera.
  23917. */
  23918. Camera.RIG_MODE_NONE = 0;
  23919. /**
  23920. * Simulates a camera Rig with one blue eye and one red eye.
  23921. * This can be use with 3d blue and red glasses.
  23922. */
  23923. Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23924. /**
  23925. * Defines that both eyes of the camera will be rendered side by side with a parallel target.
  23926. */
  23927. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23928. /**
  23929. * Defines that both eyes of the camera will be rendered side by side with a none parallel target.
  23930. */
  23931. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23932. /**
  23933. * Defines that both eyes of the camera will be rendered over under each other.
  23934. */
  23935. Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23936. /**
  23937. * Defines that both eyes of the camera should be renderered in a VR mode (carbox).
  23938. */
  23939. Camera.RIG_MODE_VR = 20;
  23940. /**
  23941. * Defines that both eyes of the camera should be renderered in a VR mode (webVR).
  23942. */
  23943. Camera.RIG_MODE_WEBVR = 21;
  23944. /**
  23945. * Defines if by default attaching controls should prevent the default javascript event to continue.
  23946. */
  23947. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23948. /**
  23949. * @hidden
  23950. * Might be removed once multiview will be a thing
  23951. */
  23952. Camera.UseAlternateWebVRRendering = false;
  23953. __decorate([
  23954. BABYLON.serializeAsVector3()
  23955. ], Camera.prototype, "position", void 0);
  23956. __decorate([
  23957. BABYLON.serializeAsVector3()
  23958. ], Camera.prototype, "upVector", void 0);
  23959. __decorate([
  23960. BABYLON.serialize()
  23961. ], Camera.prototype, "orthoLeft", void 0);
  23962. __decorate([
  23963. BABYLON.serialize()
  23964. ], Camera.prototype, "orthoRight", void 0);
  23965. __decorate([
  23966. BABYLON.serialize()
  23967. ], Camera.prototype, "orthoBottom", void 0);
  23968. __decorate([
  23969. BABYLON.serialize()
  23970. ], Camera.prototype, "orthoTop", void 0);
  23971. __decorate([
  23972. BABYLON.serialize()
  23973. ], Camera.prototype, "fov", void 0);
  23974. __decorate([
  23975. BABYLON.serialize()
  23976. ], Camera.prototype, "minZ", void 0);
  23977. __decorate([
  23978. BABYLON.serialize()
  23979. ], Camera.prototype, "maxZ", void 0);
  23980. __decorate([
  23981. BABYLON.serialize()
  23982. ], Camera.prototype, "inertia", void 0);
  23983. __decorate([
  23984. BABYLON.serialize()
  23985. ], Camera.prototype, "mode", void 0);
  23986. __decorate([
  23987. BABYLON.serialize()
  23988. ], Camera.prototype, "layerMask", void 0);
  23989. __decorate([
  23990. BABYLON.serialize()
  23991. ], Camera.prototype, "fovMode", void 0);
  23992. __decorate([
  23993. BABYLON.serialize()
  23994. ], Camera.prototype, "cameraRigMode", void 0);
  23995. __decorate([
  23996. BABYLON.serialize()
  23997. ], Camera.prototype, "interaxialDistance", void 0);
  23998. __decorate([
  23999. BABYLON.serialize()
  24000. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  24001. return Camera;
  24002. }(BABYLON.Node));
  24003. BABYLON.Camera = Camera;
  24004. })(BABYLON || (BABYLON = {}));
  24005. //# sourceMappingURL=babylon.camera.js.map
  24006. var BABYLON;
  24007. (function (BABYLON) {
  24008. /**
  24009. * This is the manager responsible of all the rendering for meshes sprites and particles.
  24010. * It is enable to manage the different groups as well as the different necessary sort functions.
  24011. * This should not be used directly aside of the few static configurations
  24012. */
  24013. var RenderingManager = /** @class */ (function () {
  24014. /**
  24015. * Instantiates a new rendering group for a particular scene
  24016. * @param scene Defines the scene the groups belongs to
  24017. */
  24018. function RenderingManager(scene) {
  24019. /**
  24020. * @hidden
  24021. */
  24022. this._useSceneAutoClearSetup = false;
  24023. this._renderingGroups = new Array();
  24024. this._autoClearDepthStencil = {};
  24025. this._customOpaqueSortCompareFn = {};
  24026. this._customAlphaTestSortCompareFn = {};
  24027. this._customTransparentSortCompareFn = {};
  24028. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  24029. this._scene = scene;
  24030. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  24031. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  24032. }
  24033. }
  24034. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  24035. if (depth === void 0) { depth = true; }
  24036. if (stencil === void 0) { stencil = true; }
  24037. if (this._depthStencilBufferAlreadyCleaned) {
  24038. return;
  24039. }
  24040. this._scene.getEngine().clear(null, false, depth, stencil);
  24041. this._depthStencilBufferAlreadyCleaned = true;
  24042. };
  24043. /**
  24044. * Renders the entire managed groups. This is used by the scene or the different rennder targets.
  24045. * @hidden
  24046. */
  24047. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  24048. // Update the observable context (not null as it only goes away on dispose)
  24049. var info = this._renderingGroupInfo;
  24050. info.scene = this._scene;
  24051. info.camera = this._scene.activeCamera;
  24052. // Dispatch sprites
  24053. if (this._scene.spriteManagers && renderSprites) {
  24054. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  24055. var manager = this._scene.spriteManagers[index];
  24056. this.dispatchSprites(manager);
  24057. }
  24058. }
  24059. // Render
  24060. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24061. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  24062. var renderingGroup = this._renderingGroups[index];
  24063. if (!renderingGroup)
  24064. continue;
  24065. var renderingGroupMask = Math.pow(2, index);
  24066. info.renderingGroupId = index;
  24067. // Before Observable
  24068. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24069. // Clear depth/stencil if needed
  24070. if (RenderingManager.AUTOCLEAR) {
  24071. var autoClear = this._useSceneAutoClearSetup ?
  24072. this._scene.getAutoClearDepthStencilSetup(index) :
  24073. this._autoClearDepthStencil[index];
  24074. if (autoClear && autoClear.autoClear) {
  24075. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  24076. }
  24077. }
  24078. // Render
  24079. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  24080. var step = _a[_i];
  24081. step.action(index);
  24082. }
  24083. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  24084. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  24085. var step = _c[_b];
  24086. step.action(index);
  24087. }
  24088. // After Observable
  24089. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24090. }
  24091. };
  24092. /**
  24093. * Resets the different information of the group to prepare a new frame
  24094. * @hidden
  24095. */
  24096. RenderingManager.prototype.reset = function () {
  24097. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24098. var renderingGroup = this._renderingGroups[index];
  24099. if (renderingGroup) {
  24100. renderingGroup.prepare();
  24101. }
  24102. }
  24103. };
  24104. /**
  24105. * Dispose and release the group and its associated resources.
  24106. * @hidden
  24107. */
  24108. RenderingManager.prototype.dispose = function () {
  24109. this.freeRenderingGroups();
  24110. this._renderingGroups.length = 0;
  24111. this._renderingGroupInfo = null;
  24112. };
  24113. /**
  24114. * Clear the info related to rendering groups preventing retention points during dispose.
  24115. */
  24116. RenderingManager.prototype.freeRenderingGroups = function () {
  24117. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24118. var renderingGroup = this._renderingGroups[index];
  24119. if (renderingGroup) {
  24120. renderingGroup.dispose();
  24121. }
  24122. }
  24123. };
  24124. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  24125. if (this._renderingGroups[renderingGroupId] === undefined) {
  24126. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  24127. }
  24128. };
  24129. /**
  24130. * Add a sprite manager to the rendering manager in order to render it this frame.
  24131. * @param spriteManager Define the sprite manager to render
  24132. */
  24133. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  24134. var renderingGroupId = spriteManager.renderingGroupId || 0;
  24135. this._prepareRenderingGroup(renderingGroupId);
  24136. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  24137. };
  24138. /**
  24139. * Add a particle system to the rendering manager in order to render it this frame.
  24140. * @param particleSystem Define the particle system to render
  24141. */
  24142. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  24143. var renderingGroupId = particleSystem.renderingGroupId || 0;
  24144. this._prepareRenderingGroup(renderingGroupId);
  24145. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  24146. };
  24147. /**
  24148. * Add a submesh to the manager in order to render it this frame
  24149. * @param subMesh The submesh to dispatch
  24150. * @param mesh Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24151. * @param material Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24152. */
  24153. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  24154. if (mesh === undefined) {
  24155. mesh = subMesh.getMesh();
  24156. }
  24157. var renderingGroupId = mesh.renderingGroupId || 0;
  24158. this._prepareRenderingGroup(renderingGroupId);
  24159. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  24160. };
  24161. /**
  24162. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24163. * This allowed control for front to back rendering or reversly depending of the special needs.
  24164. *
  24165. * @param renderingGroupId The rendering group id corresponding to its index
  24166. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24167. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24168. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24169. */
  24170. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24171. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24172. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24173. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24174. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  24175. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  24176. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  24177. if (this._renderingGroups[renderingGroupId]) {
  24178. var group = this._renderingGroups[renderingGroupId];
  24179. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  24180. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  24181. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  24182. }
  24183. };
  24184. /**
  24185. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24186. *
  24187. * @param renderingGroupId The rendering group id corresponding to its index
  24188. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24189. * @param depth Automatically clears depth between groups if true and autoClear is true.
  24190. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24191. */
  24192. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24193. if (depth === void 0) { depth = true; }
  24194. if (stencil === void 0) { stencil = true; }
  24195. this._autoClearDepthStencil[renderingGroupId] = {
  24196. autoClear: autoClearDepthStencil,
  24197. depth: depth,
  24198. stencil: stencil
  24199. };
  24200. };
  24201. /**
  24202. * Gets the current auto clear configuration for one rendering group of the rendering
  24203. * manager.
  24204. * @param index the rendering group index to get the information for
  24205. * @returns The auto clear setup for the requested rendering group
  24206. */
  24207. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  24208. return this._autoClearDepthStencil[index];
  24209. };
  24210. /**
  24211. * The max id used for rendering groups (not included)
  24212. */
  24213. RenderingManager.MAX_RENDERINGGROUPS = 4;
  24214. /**
  24215. * The min id used for rendering groups (included)
  24216. */
  24217. RenderingManager.MIN_RENDERINGGROUPS = 0;
  24218. /**
  24219. * Used to globally prevent autoclearing scenes.
  24220. */
  24221. RenderingManager.AUTOCLEAR = true;
  24222. return RenderingManager;
  24223. }());
  24224. BABYLON.RenderingManager = RenderingManager;
  24225. })(BABYLON || (BABYLON = {}));
  24226. //# sourceMappingURL=babylon.renderingManager.js.map
  24227. var BABYLON;
  24228. (function (BABYLON) {
  24229. /**
  24230. * This represents the object necessary to create a rendering group.
  24231. * This is exclusively used and created by the rendering manager.
  24232. * To modify the behavior, you use the available helpers in your scene or meshes.
  24233. * @hidden
  24234. */
  24235. var RenderingGroup = /** @class */ (function () {
  24236. /**
  24237. * Creates a new rendering group.
  24238. * @param index The rendering group index
  24239. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  24240. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  24241. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  24242. */
  24243. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24244. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24245. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24246. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24247. this.index = index;
  24248. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  24249. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  24250. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  24251. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  24252. this._particleSystems = new BABYLON.SmartArray(256);
  24253. this._spriteManagers = new BABYLON.SmartArray(256);
  24254. this._edgesRenderers = new BABYLON.SmartArray(16);
  24255. this._scene = scene;
  24256. this.opaqueSortCompareFn = opaqueSortCompareFn;
  24257. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  24258. this.transparentSortCompareFn = transparentSortCompareFn;
  24259. }
  24260. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  24261. /**
  24262. * Set the opaque sort comparison function.
  24263. * If null the sub meshes will be render in the order they were created
  24264. */
  24265. set: function (value) {
  24266. this._opaqueSortCompareFn = value;
  24267. if (value) {
  24268. this._renderOpaque = this.renderOpaqueSorted;
  24269. }
  24270. else {
  24271. this._renderOpaque = RenderingGroup.renderUnsorted;
  24272. }
  24273. },
  24274. enumerable: true,
  24275. configurable: true
  24276. });
  24277. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  24278. /**
  24279. * Set the alpha test sort comparison function.
  24280. * If null the sub meshes will be render in the order they were created
  24281. */
  24282. set: function (value) {
  24283. this._alphaTestSortCompareFn = value;
  24284. if (value) {
  24285. this._renderAlphaTest = this.renderAlphaTestSorted;
  24286. }
  24287. else {
  24288. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  24289. }
  24290. },
  24291. enumerable: true,
  24292. configurable: true
  24293. });
  24294. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  24295. /**
  24296. * Set the transparent sort comparison function.
  24297. * If null the sub meshes will be render in the order they were created
  24298. */
  24299. set: function (value) {
  24300. if (value) {
  24301. this._transparentSortCompareFn = value;
  24302. }
  24303. else {
  24304. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  24305. }
  24306. this._renderTransparent = this.renderTransparentSorted;
  24307. },
  24308. enumerable: true,
  24309. configurable: true
  24310. });
  24311. /**
  24312. * Render all the sub meshes contained in the group.
  24313. * @param customRenderFunction Used to override the default render behaviour of the group.
  24314. * @returns true if rendered some submeshes.
  24315. */
  24316. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  24317. if (customRenderFunction) {
  24318. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  24319. return;
  24320. }
  24321. var engine = this._scene.getEngine();
  24322. // Depth only
  24323. if (this._depthOnlySubMeshes.length !== 0) {
  24324. engine.setColorWrite(false);
  24325. this._renderAlphaTest(this._depthOnlySubMeshes);
  24326. engine.setColorWrite(true);
  24327. }
  24328. // Opaque
  24329. if (this._opaqueSubMeshes.length !== 0) {
  24330. this._renderOpaque(this._opaqueSubMeshes);
  24331. }
  24332. // Alpha test
  24333. if (this._alphaTestSubMeshes.length !== 0) {
  24334. this._renderAlphaTest(this._alphaTestSubMeshes);
  24335. }
  24336. var stencilState = engine.getStencilBuffer();
  24337. engine.setStencilBuffer(false);
  24338. // Sprites
  24339. if (renderSprites) {
  24340. this._renderSprites();
  24341. }
  24342. // Particles
  24343. if (renderParticles) {
  24344. this._renderParticles(activeMeshes);
  24345. }
  24346. if (this.onBeforeTransparentRendering) {
  24347. this.onBeforeTransparentRendering();
  24348. }
  24349. // Transparent
  24350. if (this._transparentSubMeshes.length !== 0) {
  24351. this._renderTransparent(this._transparentSubMeshes);
  24352. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24353. }
  24354. // Set back stencil to false in case it changes before the edge renderer.
  24355. engine.setStencilBuffer(false);
  24356. // Edges
  24357. if (this._edgesRenderers.length) {
  24358. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  24359. this._edgesRenderers.data[edgesRendererIndex].render();
  24360. }
  24361. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24362. }
  24363. // Restore Stencil state.
  24364. engine.setStencilBuffer(stencilState);
  24365. };
  24366. /**
  24367. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  24368. * @param subMeshes The submeshes to render
  24369. */
  24370. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  24371. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  24372. };
  24373. /**
  24374. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  24375. * @param subMeshes The submeshes to render
  24376. */
  24377. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  24378. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  24379. };
  24380. /**
  24381. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  24382. * @param subMeshes The submeshes to render
  24383. */
  24384. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  24385. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  24386. };
  24387. /**
  24388. * Renders the submeshes in a specified order.
  24389. * @param subMeshes The submeshes to sort before render
  24390. * @param sortCompareFn The comparison function use to sort
  24391. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  24392. * @param transparent Specifies to activate blending if true
  24393. */
  24394. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  24395. var subIndex = 0;
  24396. var subMesh;
  24397. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  24398. for (; subIndex < subMeshes.length; subIndex++) {
  24399. subMesh = subMeshes.data[subIndex];
  24400. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  24401. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  24402. }
  24403. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  24404. if (sortCompareFn) {
  24405. sortedArray.sort(sortCompareFn);
  24406. }
  24407. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  24408. subMesh = sortedArray[subIndex];
  24409. if (transparent) {
  24410. var material = subMesh.getMaterial();
  24411. if (material && material.needDepthPrePass) {
  24412. var engine = material.getScene().getEngine();
  24413. engine.setColorWrite(false);
  24414. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24415. subMesh.render(false);
  24416. engine.setColorWrite(true);
  24417. }
  24418. }
  24419. subMesh.render(transparent);
  24420. }
  24421. };
  24422. /**
  24423. * Renders the submeshes in the order they were dispatched (no sort applied).
  24424. * @param subMeshes The submeshes to render
  24425. */
  24426. RenderingGroup.renderUnsorted = function (subMeshes) {
  24427. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  24428. var submesh = subMeshes.data[subIndex];
  24429. submesh.render(false);
  24430. }
  24431. };
  24432. /**
  24433. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24434. * are rendered back to front if in the same alpha index.
  24435. *
  24436. * @param a The first submesh
  24437. * @param b The second submesh
  24438. * @returns The result of the comparison
  24439. */
  24440. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  24441. // Alpha index first
  24442. if (a._alphaIndex > b._alphaIndex) {
  24443. return 1;
  24444. }
  24445. if (a._alphaIndex < b._alphaIndex) {
  24446. return -1;
  24447. }
  24448. // Then distance to camera
  24449. return RenderingGroup.backToFrontSortCompare(a, b);
  24450. };
  24451. /**
  24452. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24453. * are rendered back to front.
  24454. *
  24455. * @param a The first submesh
  24456. * @param b The second submesh
  24457. * @returns The result of the comparison
  24458. */
  24459. RenderingGroup.backToFrontSortCompare = function (a, b) {
  24460. // Then distance to camera
  24461. if (a._distanceToCamera < b._distanceToCamera) {
  24462. return 1;
  24463. }
  24464. if (a._distanceToCamera > b._distanceToCamera) {
  24465. return -1;
  24466. }
  24467. return 0;
  24468. };
  24469. /**
  24470. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24471. * are rendered front to back (prevent overdraw).
  24472. *
  24473. * @param a The first submesh
  24474. * @param b The second submesh
  24475. * @returns The result of the comparison
  24476. */
  24477. RenderingGroup.frontToBackSortCompare = function (a, b) {
  24478. // Then distance to camera
  24479. if (a._distanceToCamera < b._distanceToCamera) {
  24480. return -1;
  24481. }
  24482. if (a._distanceToCamera > b._distanceToCamera) {
  24483. return 1;
  24484. }
  24485. return 0;
  24486. };
  24487. /**
  24488. * Resets the different lists of submeshes to prepare a new frame.
  24489. */
  24490. RenderingGroup.prototype.prepare = function () {
  24491. this._opaqueSubMeshes.reset();
  24492. this._transparentSubMeshes.reset();
  24493. this._alphaTestSubMeshes.reset();
  24494. this._depthOnlySubMeshes.reset();
  24495. this._particleSystems.reset();
  24496. this._spriteManagers.reset();
  24497. this._edgesRenderers.reset();
  24498. };
  24499. RenderingGroup.prototype.dispose = function () {
  24500. this._opaqueSubMeshes.dispose();
  24501. this._transparentSubMeshes.dispose();
  24502. this._alphaTestSubMeshes.dispose();
  24503. this._depthOnlySubMeshes.dispose();
  24504. this._particleSystems.dispose();
  24505. this._spriteManagers.dispose();
  24506. this._edgesRenderers.dispose();
  24507. };
  24508. /**
  24509. * Inserts the submesh in its correct queue depending on its material.
  24510. * @param subMesh The submesh to dispatch
  24511. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24512. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24513. */
  24514. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  24515. // Get mesh and materials if not provided
  24516. if (mesh === undefined) {
  24517. mesh = subMesh.getMesh();
  24518. }
  24519. if (material === undefined) {
  24520. material = subMesh.getMaterial();
  24521. }
  24522. if (material === null || material === undefined) {
  24523. return;
  24524. }
  24525. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  24526. this._transparentSubMeshes.push(subMesh);
  24527. }
  24528. else if (material.needAlphaTesting()) { // Alpha test
  24529. if (material.needDepthPrePass) {
  24530. this._depthOnlySubMeshes.push(subMesh);
  24531. }
  24532. this._alphaTestSubMeshes.push(subMesh);
  24533. }
  24534. else {
  24535. if (material.needDepthPrePass) {
  24536. this._depthOnlySubMeshes.push(subMesh);
  24537. }
  24538. this._opaqueSubMeshes.push(subMesh); // Opaque
  24539. }
  24540. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  24541. this._edgesRenderers.push(mesh._edgesRenderer);
  24542. }
  24543. };
  24544. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  24545. this._spriteManagers.push(spriteManager);
  24546. };
  24547. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  24548. this._particleSystems.push(particleSystem);
  24549. };
  24550. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  24551. if (this._particleSystems.length === 0) {
  24552. return;
  24553. }
  24554. // Particles
  24555. var activeCamera = this._scene.activeCamera;
  24556. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  24557. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  24558. var particleSystem = this._particleSystems.data[particleIndex];
  24559. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  24560. continue;
  24561. }
  24562. var emitter = particleSystem.emitter;
  24563. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  24564. this._scene._activeParticles.addCount(particleSystem.render(), false);
  24565. }
  24566. }
  24567. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  24568. };
  24569. RenderingGroup.prototype._renderSprites = function () {
  24570. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  24571. return;
  24572. }
  24573. // Sprites
  24574. var activeCamera = this._scene.activeCamera;
  24575. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  24576. for (var id = 0; id < this._spriteManagers.length; id++) {
  24577. var spriteManager = this._spriteManagers.data[id];
  24578. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  24579. spriteManager.render();
  24580. }
  24581. }
  24582. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  24583. };
  24584. return RenderingGroup;
  24585. }());
  24586. BABYLON.RenderingGroup = RenderingGroup;
  24587. })(BABYLON || (BABYLON = {}));
  24588. //# sourceMappingURL=babylon.renderingGroup.js.map
  24589. var BABYLON;
  24590. (function (BABYLON) {
  24591. /**
  24592. * Groups all the scene component constants in one place to ease maintenance.
  24593. * @hidden
  24594. */
  24595. var SceneComponentConstants = /** @class */ (function () {
  24596. function SceneComponentConstants() {
  24597. }
  24598. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  24599. SceneComponentConstants.NAME_LAYER = "Layer";
  24600. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  24601. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  24602. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  24603. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  24604. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  24605. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  24606. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  24607. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  24608. SceneComponentConstants.NAME_SPRITE = "Sprite";
  24609. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  24610. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  24611. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  24612. SceneComponentConstants.NAME_OCTREE = "Octree";
  24613. SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
  24614. SceneComponentConstants.NAME_AUDIO = "Audio";
  24615. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  24616. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24617. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  24618. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24619. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  24620. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  24621. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  24622. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  24623. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  24624. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  24625. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
  24626. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  24627. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  24628. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  24629. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  24630. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  24631. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  24632. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  24633. SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
  24634. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  24635. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  24636. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  24637. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  24638. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  24639. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  24640. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  24641. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  24642. return SceneComponentConstants;
  24643. }());
  24644. BABYLON.SceneComponentConstants = SceneComponentConstants;
  24645. /**
  24646. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  24647. * @hidden
  24648. */
  24649. var Stage = /** @class */ (function (_super) {
  24650. __extends(Stage, _super);
  24651. /**
  24652. * Hide ctor from the rest of the world.
  24653. * @param items The items to add.
  24654. */
  24655. function Stage(items) {
  24656. return _super.apply(this, items) || this;
  24657. }
  24658. /**
  24659. * Creates a new Stage.
  24660. * @returns A new instance of a Stage
  24661. */
  24662. Stage.Create = function () {
  24663. return Object.create(Stage.prototype);
  24664. };
  24665. /**
  24666. * Registers a step in an ordered way in the targeted stage.
  24667. * @param index Defines the position to register the step in
  24668. * @param component Defines the component attached to the step
  24669. * @param action Defines the action to launch during the step
  24670. */
  24671. Stage.prototype.registerStep = function (index, component, action) {
  24672. var i = 0;
  24673. var maxIndex = Number.MAX_VALUE;
  24674. for (; i < this.length && i < maxIndex; i++) {
  24675. var step = this[i];
  24676. maxIndex = step.index;
  24677. }
  24678. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  24679. };
  24680. /**
  24681. * Clears all the steps from the stage.
  24682. */
  24683. Stage.prototype.clear = function () {
  24684. this.length = 0;
  24685. };
  24686. return Stage;
  24687. }(Array));
  24688. BABYLON.Stage = Stage;
  24689. })(BABYLON || (BABYLON = {}));
  24690. //# sourceMappingURL=babylon.sceneComponent.js.map
  24691. var BABYLON;
  24692. (function (BABYLON) {
  24693. /**
  24694. * Base class of the scene acting as a container for the different elements composing a scene.
  24695. * This class is dynamically extended by the different components of the scene increasing
  24696. * flexibility and reducing coupling
  24697. */
  24698. var AbstractScene = /** @class */ (function () {
  24699. function AbstractScene() {
  24700. /**
  24701. * Gets the list of root nodes (ie. nodes with no parent)
  24702. */
  24703. this.rootNodes = new Array();
  24704. /** All of the cameras added to this scene
  24705. * @see http://doc.babylonjs.com/babylon101/cameras
  24706. */
  24707. this.cameras = new Array();
  24708. /**
  24709. * All of the lights added to this scene
  24710. * @see http://doc.babylonjs.com/babylon101/lights
  24711. */
  24712. this.lights = new Array();
  24713. /**
  24714. * All of the (abstract) meshes added to this scene
  24715. */
  24716. this.meshes = new Array();
  24717. /**
  24718. * The list of skeletons added to the scene
  24719. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24720. */
  24721. this.skeletons = new Array();
  24722. /**
  24723. * All of the particle systems added to this scene
  24724. * @see http://doc.babylonjs.com/babylon101/particles
  24725. */
  24726. this.particleSystems = new Array();
  24727. /**
  24728. * Gets a list of Animations associated with the scene
  24729. */
  24730. this.animations = [];
  24731. /**
  24732. * All of the animation groups added to this scene
  24733. * @see http://doc.babylonjs.com/how_to/group
  24734. */
  24735. this.animationGroups = new Array();
  24736. /**
  24737. * All of the multi-materials added to this scene
  24738. * @see http://doc.babylonjs.com/how_to/multi_materials
  24739. */
  24740. this.multiMaterials = new Array();
  24741. /**
  24742. * All of the materials added to this scene
  24743. * @see http://doc.babylonjs.com/babylon101/materials
  24744. */
  24745. this.materials = new Array();
  24746. /**
  24747. * The list of morph target managers added to the scene
  24748. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24749. */
  24750. this.morphTargetManagers = new Array();
  24751. /**
  24752. * The list of geometries used in the scene.
  24753. */
  24754. this.geometries = new Array();
  24755. /**
  24756. * All of the tranform nodes added to this scene
  24757. * @see http://doc.babylonjs.com/how_to/transformnode
  24758. */
  24759. this.transformNodes = new Array();
  24760. /**
  24761. * ActionManagers available on the scene.
  24762. */
  24763. this.actionManagers = new Array();
  24764. /**
  24765. * Textures to keep.
  24766. */
  24767. this.textures = new Array();
  24768. }
  24769. /**
  24770. * Adds a parser in the list of available ones
  24771. * @param name Defines the name of the parser
  24772. * @param parser Defines the parser to add
  24773. */
  24774. AbstractScene.AddParser = function (name, parser) {
  24775. this._BabylonFileParsers[name] = parser;
  24776. };
  24777. /**
  24778. * Gets a general parser from the list of avaialble ones
  24779. * @param name Defines the name of the parser
  24780. * @returns the requested parser or null
  24781. */
  24782. AbstractScene.GetParser = function (name) {
  24783. if (this._BabylonFileParsers[name]) {
  24784. return this._BabylonFileParsers[name];
  24785. }
  24786. return null;
  24787. };
  24788. /**
  24789. * Adds n individual parser in the list of available ones
  24790. * @param name Defines the name of the parser
  24791. * @param parser Defines the parser to add
  24792. */
  24793. AbstractScene.AddIndividualParser = function (name, parser) {
  24794. this._IndividualBabylonFileParsers[name] = parser;
  24795. };
  24796. /**
  24797. * Gets an individual parser from the list of avaialble ones
  24798. * @param name Defines the name of the parser
  24799. * @returns the requested parser or null
  24800. */
  24801. AbstractScene.GetIndividualParser = function (name) {
  24802. if (this._IndividualBabylonFileParsers[name]) {
  24803. return this._IndividualBabylonFileParsers[name];
  24804. }
  24805. return null;
  24806. };
  24807. /**
  24808. * Parser json data and populate both a scene and its associated container object
  24809. * @param jsonData Defines the data to parse
  24810. * @param scene Defines the scene to parse the data for
  24811. * @param container Defines the container attached to the parsing sequence
  24812. * @param rootUrl Defines the root url of the data
  24813. */
  24814. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  24815. for (var parserName in this._BabylonFileParsers) {
  24816. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  24817. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  24818. }
  24819. }
  24820. };
  24821. /**
  24822. * Stores the list of available parsers in the application.
  24823. */
  24824. AbstractScene._BabylonFileParsers = {};
  24825. /**
  24826. * Stores the list of available individual parsers in the application.
  24827. */
  24828. AbstractScene._IndividualBabylonFileParsers = {};
  24829. return AbstractScene;
  24830. }());
  24831. BABYLON.AbstractScene = AbstractScene;
  24832. })(BABYLON || (BABYLON = {}));
  24833. //# sourceMappingURL=babylon.abstractScene.js.map
  24834. var BABYLON;
  24835. (function (BABYLON) {
  24836. /** @hidden */
  24837. var ClickInfo = /** @class */ (function () {
  24838. function ClickInfo() {
  24839. this._singleClick = false;
  24840. this._doubleClick = false;
  24841. this._hasSwiped = false;
  24842. this._ignore = false;
  24843. }
  24844. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  24845. get: function () {
  24846. return this._singleClick;
  24847. },
  24848. set: function (b) {
  24849. this._singleClick = b;
  24850. },
  24851. enumerable: true,
  24852. configurable: true
  24853. });
  24854. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  24855. get: function () {
  24856. return this._doubleClick;
  24857. },
  24858. set: function (b) {
  24859. this._doubleClick = b;
  24860. },
  24861. enumerable: true,
  24862. configurable: true
  24863. });
  24864. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  24865. get: function () {
  24866. return this._hasSwiped;
  24867. },
  24868. set: function (b) {
  24869. this._hasSwiped = b;
  24870. },
  24871. enumerable: true,
  24872. configurable: true
  24873. });
  24874. Object.defineProperty(ClickInfo.prototype, "ignore", {
  24875. get: function () {
  24876. return this._ignore;
  24877. },
  24878. set: function (b) {
  24879. this._ignore = b;
  24880. },
  24881. enumerable: true,
  24882. configurable: true
  24883. });
  24884. return ClickInfo;
  24885. }());
  24886. /**
  24887. * This class is used by the onRenderingGroupObservable
  24888. */
  24889. var RenderingGroupInfo = /** @class */ (function () {
  24890. function RenderingGroupInfo() {
  24891. }
  24892. return RenderingGroupInfo;
  24893. }());
  24894. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  24895. /**
  24896. * Represents a scene to be rendered by the engine.
  24897. * @see http://doc.babylonjs.com/features/scene
  24898. */
  24899. var Scene = /** @class */ (function (_super) {
  24900. __extends(Scene, _super);
  24901. /**
  24902. * Creates a new Scene
  24903. * @param engine defines the engine to use to render this scene
  24904. */
  24905. function Scene(engine) {
  24906. var _this = _super.call(this) || this;
  24907. // Members
  24908. /**
  24909. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  24910. */
  24911. _this.autoClear = true;
  24912. /**
  24913. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  24914. */
  24915. _this.autoClearDepthAndStencil = true;
  24916. /**
  24917. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  24918. */
  24919. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  24920. /**
  24921. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  24922. */
  24923. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  24924. _this._forceWireframe = false;
  24925. _this._forcePointsCloud = false;
  24926. /**
  24927. * Gets or sets a boolean indicating if animations are enabled
  24928. */
  24929. _this.animationsEnabled = true;
  24930. _this._animationPropertiesOverride = null;
  24931. /**
  24932. * Gets or sets a boolean indicating if a constant deltatime has to be used
  24933. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  24934. */
  24935. _this.useConstantAnimationDeltaTime = false;
  24936. /**
  24937. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  24938. * Please note that it requires to run a ray cast through the scene on every frame
  24939. */
  24940. _this.constantlyUpdateMeshUnderPointer = false;
  24941. /**
  24942. * Defines the HTML cursor to use when hovering over interactive elements
  24943. */
  24944. _this.hoverCursor = "pointer";
  24945. /**
  24946. * Defines the HTML default cursor to use (empty by default)
  24947. */
  24948. _this.defaultCursor = "";
  24949. /**
  24950. * This is used to call preventDefault() on pointer down
  24951. * in order to block unwanted artifacts like system double clicks
  24952. */
  24953. _this.preventDefaultOnPointerDown = true;
  24954. // Metadata
  24955. /**
  24956. * Gets or sets user defined metadata
  24957. */
  24958. _this.metadata = null;
  24959. /**
  24960. * Use this array to add regular expressions used to disable offline support for specific urls
  24961. */
  24962. _this.disableOfflineSupportExceptionRules = new Array();
  24963. /**
  24964. * An event triggered when the scene is disposed.
  24965. */
  24966. _this.onDisposeObservable = new BABYLON.Observable();
  24967. _this._onDisposeObserver = null;
  24968. /**
  24969. * An event triggered before rendering the scene (right after animations and physics)
  24970. */
  24971. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24972. _this._onBeforeRenderObserver = null;
  24973. /**
  24974. * An event triggered after rendering the scene
  24975. */
  24976. _this.onAfterRenderObservable = new BABYLON.Observable();
  24977. _this._onAfterRenderObserver = null;
  24978. /**
  24979. * An event triggered before animating the scene
  24980. */
  24981. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  24982. /**
  24983. * An event triggered after animations processing
  24984. */
  24985. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  24986. /**
  24987. * An event triggered before draw calls are ready to be sent
  24988. */
  24989. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  24990. /**
  24991. * An event triggered after draw calls have been sent
  24992. */
  24993. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  24994. /**
  24995. * An event triggered when the scene is ready
  24996. */
  24997. _this.onReadyObservable = new BABYLON.Observable();
  24998. /**
  24999. * An event triggered before rendering a camera
  25000. */
  25001. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  25002. _this._onBeforeCameraRenderObserver = null;
  25003. /**
  25004. * An event triggered after rendering a camera
  25005. */
  25006. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  25007. _this._onAfterCameraRenderObserver = null;
  25008. /**
  25009. * An event triggered when active meshes evaluation is about to start
  25010. */
  25011. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  25012. /**
  25013. * An event triggered when active meshes evaluation is done
  25014. */
  25015. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  25016. /**
  25017. * An event triggered when particles rendering is about to start
  25018. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  25019. */
  25020. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  25021. /**
  25022. * An event triggered when particles rendering is done
  25023. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  25024. */
  25025. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  25026. /**
  25027. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  25028. */
  25029. _this.onDataLoadedObservable = new BABYLON.Observable();
  25030. /**
  25031. * An event triggered when a camera is created
  25032. */
  25033. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  25034. /**
  25035. * An event triggered when a camera is removed
  25036. */
  25037. _this.onCameraRemovedObservable = new BABYLON.Observable();
  25038. /**
  25039. * An event triggered when a light is created
  25040. */
  25041. _this.onNewLightAddedObservable = new BABYLON.Observable();
  25042. /**
  25043. * An event triggered when a light is removed
  25044. */
  25045. _this.onLightRemovedObservable = new BABYLON.Observable();
  25046. /**
  25047. * An event triggered when a geometry is created
  25048. */
  25049. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  25050. /**
  25051. * An event triggered when a geometry is removed
  25052. */
  25053. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  25054. /**
  25055. * An event triggered when a transform node is created
  25056. */
  25057. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  25058. /**
  25059. * An event triggered when a transform node is removed
  25060. */
  25061. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  25062. /**
  25063. * An event triggered when a mesh is created
  25064. */
  25065. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  25066. /**
  25067. * An event triggered when a mesh is removed
  25068. */
  25069. _this.onMeshRemovedObservable = new BABYLON.Observable();
  25070. /**
  25071. * An event triggered when a material is created
  25072. */
  25073. _this.onNewMaterialAddedObservable = new BABYLON.Observable();
  25074. /**
  25075. * An event triggered when a material is removed
  25076. */
  25077. _this.onMaterialRemovedObservable = new BABYLON.Observable();
  25078. /**
  25079. * An event triggered when a texture is created
  25080. */
  25081. _this.onNewTextureAddedObservable = new BABYLON.Observable();
  25082. /**
  25083. * An event triggered when a texture is removed
  25084. */
  25085. _this.onTextureRemovedObservable = new BABYLON.Observable();
  25086. /**
  25087. * An event triggered when render targets are about to be rendered
  25088. * Can happen multiple times per frame.
  25089. */
  25090. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  25091. /**
  25092. * An event triggered when render targets were rendered.
  25093. * Can happen multiple times per frame.
  25094. */
  25095. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  25096. /**
  25097. * An event triggered before calculating deterministic simulation step
  25098. */
  25099. _this.onBeforeStepObservable = new BABYLON.Observable();
  25100. /**
  25101. * An event triggered after calculating deterministic simulation step
  25102. */
  25103. _this.onAfterStepObservable = new BABYLON.Observable();
  25104. /**
  25105. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  25106. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25107. * 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)
  25108. */
  25109. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  25110. /**
  25111. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  25112. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25113. * 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)
  25114. */
  25115. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  25116. /**
  25117. * This Observable will when a mesh has been imported into the scene.
  25118. */
  25119. _this.onMeshImportedObservable = new BABYLON.Observable();
  25120. // Animations
  25121. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  25122. /**
  25123. * 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).
  25124. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  25125. */
  25126. _this.onPrePointerObservable = new BABYLON.Observable();
  25127. /**
  25128. * Observable event triggered each time an input event is received from the rendering canvas
  25129. */
  25130. _this.onPointerObservable = new BABYLON.Observable();
  25131. _this._meshPickProceed = false;
  25132. _this._currentPickResult = null;
  25133. _this._previousPickResult = null;
  25134. _this._totalPointersPressed = 0;
  25135. _this._doubleClickOccured = false;
  25136. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  25137. _this.cameraToUseForPointers = null;
  25138. _this._pointerX = 0;
  25139. _this._pointerY = 0;
  25140. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  25141. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  25142. _this._startingPointerTime = 0;
  25143. _this._previousStartingPointerTime = 0;
  25144. _this._pointerCaptures = {};
  25145. // Deterministic lockstep
  25146. _this._timeAccumulator = 0;
  25147. _this._currentStepId = 0;
  25148. _this._currentInternalStep = 0;
  25149. // Keyboard
  25150. /**
  25151. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  25152. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  25153. */
  25154. _this.onPreKeyboardObservable = new BABYLON.Observable();
  25155. /**
  25156. * Observable event triggered each time an keyboard event is received from the hosting window
  25157. */
  25158. _this.onKeyboardObservable = new BABYLON.Observable();
  25159. // Coordinates system
  25160. _this._useRightHandedSystem = false;
  25161. // Fog
  25162. _this._fogEnabled = true;
  25163. _this._fogMode = Scene.FOGMODE_NONE;
  25164. /**
  25165. * Gets or sets the fog color to use
  25166. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25167. * (Default is Color3(0.2, 0.2, 0.3))
  25168. */
  25169. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  25170. /**
  25171. * Gets or sets the fog density to use
  25172. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25173. * (Default is 0.1)
  25174. */
  25175. _this.fogDensity = 0.1;
  25176. /**
  25177. * Gets or sets the fog start distance to use
  25178. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25179. * (Default is 0)
  25180. */
  25181. _this.fogStart = 0;
  25182. /**
  25183. * Gets or sets the fog end distance to use
  25184. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25185. * (Default is 1000)
  25186. */
  25187. _this.fogEnd = 1000.0;
  25188. // Lights
  25189. _this._shadowsEnabled = true;
  25190. _this._lightsEnabled = true;
  25191. /** All of the active cameras added to this scene. */
  25192. _this.activeCameras = new Array();
  25193. // Textures
  25194. _this._texturesEnabled = true;
  25195. // Particles
  25196. /**
  25197. * Gets or sets a boolean indicating if particles are enabled on this scene
  25198. */
  25199. _this.particlesEnabled = true;
  25200. // Sprites
  25201. /**
  25202. * Gets or sets a boolean indicating if sprites are enabled on this scene
  25203. */
  25204. _this.spritesEnabled = true;
  25205. // Skeletons
  25206. _this._skeletonsEnabled = true;
  25207. // Lens flares
  25208. /**
  25209. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  25210. */
  25211. _this.lensFlaresEnabled = true;
  25212. // Collisions
  25213. /**
  25214. * Gets or sets a boolean indicating if collisions are enabled on this scene
  25215. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25216. */
  25217. _this.collisionsEnabled = true;
  25218. /**
  25219. * Defines the gravity applied to this scene (used only for collisions)
  25220. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25221. */
  25222. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  25223. // Postprocesses
  25224. /**
  25225. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  25226. */
  25227. _this.postProcessesEnabled = true;
  25228. /**
  25229. * The list of postprocesses added to the scene
  25230. */
  25231. _this.postProcesses = new Array();
  25232. // Customs render targets
  25233. /**
  25234. * Gets or sets a boolean indicating if render targets are enabled on this scene
  25235. */
  25236. _this.renderTargetsEnabled = true;
  25237. /**
  25238. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  25239. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  25240. */
  25241. _this.dumpNextRenderTargets = false;
  25242. /**
  25243. * The list of user defined render targets added to the scene
  25244. */
  25245. _this.customRenderTargets = new Array();
  25246. /**
  25247. * Gets the list of meshes imported to the scene through SceneLoader
  25248. */
  25249. _this.importedMeshesFiles = new Array();
  25250. // Probes
  25251. /**
  25252. * Gets or sets a boolean indicating if probes are enabled on this scene
  25253. */
  25254. _this.probesEnabled = true;
  25255. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  25256. // Procedural textures
  25257. /**
  25258. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  25259. */
  25260. _this.proceduralTexturesEnabled = true;
  25261. // Performance counters
  25262. _this._totalVertices = new BABYLON.PerfCounter();
  25263. /** @hidden */
  25264. _this._activeIndices = new BABYLON.PerfCounter();
  25265. /** @hidden */
  25266. _this._activeParticles = new BABYLON.PerfCounter();
  25267. /** @hidden */
  25268. _this._activeBones = new BABYLON.PerfCounter();
  25269. _this._animationTime = 0;
  25270. /**
  25271. * Gets or sets a general scale for animation speed
  25272. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  25273. */
  25274. _this.animationTimeScale = 1;
  25275. _this._renderId = 0;
  25276. _this._frameId = 0;
  25277. _this._executeWhenReadyTimeoutId = -1;
  25278. _this._intermediateRendering = false;
  25279. _this._viewUpdateFlag = -1;
  25280. _this._projectionUpdateFlag = -1;
  25281. _this._alternateViewUpdateFlag = -1;
  25282. _this._alternateProjectionUpdateFlag = -1;
  25283. /** @hidden */
  25284. _this._toBeDisposed = new Array(256);
  25285. _this._activeRequests = new Array();
  25286. _this._pendingData = new Array();
  25287. _this._isDisposed = false;
  25288. /**
  25289. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  25290. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  25291. */
  25292. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  25293. _this._activeMeshes = new BABYLON.SmartArray(256);
  25294. _this._processedMaterials = new BABYLON.SmartArray(256);
  25295. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  25296. /** @hidden */
  25297. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  25298. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  25299. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  25300. /** @hidden */
  25301. _this._activeAnimatables = new Array();
  25302. _this._transformMatrix = BABYLON.Matrix.Zero();
  25303. _this._useAlternateCameraConfiguration = false;
  25304. _this._alternateRendering = false;
  25305. /**
  25306. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  25307. * This is useful if there are more lights that the maximum simulteanous authorized
  25308. */
  25309. _this.requireLightSorting = false;
  25310. /**
  25311. * @hidden
  25312. * Backing store of defined scene components.
  25313. */
  25314. _this._components = [];
  25315. /**
  25316. * @hidden
  25317. * Backing store of defined scene components.
  25318. */
  25319. _this._serializableComponents = [];
  25320. /**
  25321. * List of components to register on the next registration step.
  25322. */
  25323. _this._transientComponents = [];
  25324. /**
  25325. * @hidden
  25326. * Defines the actions happening before camera updates.
  25327. */
  25328. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  25329. /**
  25330. * @hidden
  25331. * Defines the actions happening before clear the canvas.
  25332. */
  25333. _this._beforeClearStage = BABYLON.Stage.Create();
  25334. /**
  25335. * @hidden
  25336. * Defines the actions when collecting render targets for the frame.
  25337. */
  25338. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  25339. /**
  25340. * @hidden
  25341. * Defines the actions happening for one camera in the frame.
  25342. */
  25343. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  25344. /**
  25345. * @hidden
  25346. * Defines the actions happening during the per mesh ready checks.
  25347. */
  25348. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  25349. /**
  25350. * @hidden
  25351. * Defines the actions happening before evaluate active mesh checks.
  25352. */
  25353. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  25354. /**
  25355. * @hidden
  25356. * Defines the actions happening during the evaluate sub mesh checks.
  25357. */
  25358. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  25359. /**
  25360. * @hidden
  25361. * Defines the actions happening during the active mesh stage.
  25362. */
  25363. _this._activeMeshStage = BABYLON.Stage.Create();
  25364. /**
  25365. * @hidden
  25366. * Defines the actions happening during the per camera render target step.
  25367. */
  25368. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  25369. /**
  25370. * @hidden
  25371. * Defines the actions happening just before the active camera is drawing.
  25372. */
  25373. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  25374. /**
  25375. * @hidden
  25376. * Defines the actions happening just before a rendering group is drawing.
  25377. */
  25378. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  25379. /**
  25380. * @hidden
  25381. * Defines the actions happening just before a mesh is drawing.
  25382. */
  25383. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  25384. /**
  25385. * @hidden
  25386. * Defines the actions happening just after a mesh has been drawn.
  25387. */
  25388. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  25389. /**
  25390. * @hidden
  25391. * Defines the actions happening just after a rendering group has been drawn.
  25392. */
  25393. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  25394. /**
  25395. * @hidden
  25396. * Defines the actions happening just after the active camera has been drawn.
  25397. */
  25398. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  25399. /**
  25400. * @hidden
  25401. * Defines the actions happening just after rendering all cameras and computing intersections.
  25402. */
  25403. _this._afterRenderStage = BABYLON.Stage.Create();
  25404. /**
  25405. * @hidden
  25406. * Defines the actions happening when a pointer move event happens.
  25407. */
  25408. _this._pointerMoveStage = BABYLON.Stage.Create();
  25409. /**
  25410. * @hidden
  25411. * Defines the actions happening when a pointer down event happens.
  25412. */
  25413. _this._pointerDownStage = BABYLON.Stage.Create();
  25414. /**
  25415. * @hidden
  25416. * Defines the actions happening when a pointer up event happens.
  25417. */
  25418. _this._pointerUpStage = BABYLON.Stage.Create();
  25419. _this._defaultMeshCandidates = {
  25420. data: [],
  25421. length: 0
  25422. };
  25423. _this._defaultSubMeshCandidates = {
  25424. data: [],
  25425. length: 0
  25426. };
  25427. _this._activeMeshesFrozen = false;
  25428. /** @hidden */
  25429. _this._allowPostProcessClearColor = true;
  25430. /**
  25431. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  25432. */
  25433. _this.getDeterministicFrameTime = function () {
  25434. return 1000.0 / 60.0; // frame time in ms
  25435. };
  25436. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  25437. _this._blockMaterialDirtyMechanism = false;
  25438. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  25439. _this._engine.scenes.push(_this);
  25440. _this._uid = null;
  25441. _this._renderingManager = new BABYLON.RenderingManager(_this);
  25442. if (BABYLON.PostProcessManager) {
  25443. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  25444. }
  25445. if (BABYLON.Tools.IsWindowObjectExist()) {
  25446. _this.attachControl();
  25447. }
  25448. //collision coordinator initialization. For now legacy per default.
  25449. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  25450. // Uniform Buffer
  25451. _this._createUbo();
  25452. // Default Image processing definition
  25453. if (BABYLON.ImageProcessingConfiguration) {
  25454. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  25455. }
  25456. _this.setDefaultCandidateProviders();
  25457. return _this;
  25458. }
  25459. Object.defineProperty(Scene.prototype, "environmentTexture", {
  25460. /**
  25461. * Texture used in all pbr material as the reflection texture.
  25462. * As in the majority of the scene they are the same (exception for multi room and so on),
  25463. * this is easier to reference from here than from all the materials.
  25464. */
  25465. get: function () {
  25466. return this._environmentTexture;
  25467. },
  25468. /**
  25469. * Texture used in all pbr material as the reflection texture.
  25470. * As in the majority of the scene they are the same (exception for multi room and so on),
  25471. * this is easier to set here than in all the materials.
  25472. */
  25473. set: function (value) {
  25474. if (this._environmentTexture === value) {
  25475. return;
  25476. }
  25477. this._environmentTexture = value;
  25478. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25479. },
  25480. enumerable: true,
  25481. configurable: true
  25482. });
  25483. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  25484. /**
  25485. * Default image processing configuration used either in the rendering
  25486. * Forward main pass or through the imageProcessingPostProcess if present.
  25487. * As in the majority of the scene they are the same (exception for multi camera),
  25488. * this is easier to reference from here than from all the materials and post process.
  25489. *
  25490. * No setter as we it is a shared configuration, you can set the values instead.
  25491. */
  25492. get: function () {
  25493. return this._imageProcessingConfiguration;
  25494. },
  25495. enumerable: true,
  25496. configurable: true
  25497. });
  25498. Object.defineProperty(Scene.prototype, "forceWireframe", {
  25499. get: function () {
  25500. return this._forceWireframe;
  25501. },
  25502. /**
  25503. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  25504. */
  25505. set: function (value) {
  25506. if (this._forceWireframe === value) {
  25507. return;
  25508. }
  25509. this._forceWireframe = value;
  25510. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25511. },
  25512. enumerable: true,
  25513. configurable: true
  25514. });
  25515. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  25516. get: function () {
  25517. return this._forcePointsCloud;
  25518. },
  25519. /**
  25520. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  25521. */
  25522. set: function (value) {
  25523. if (this._forcePointsCloud === value) {
  25524. return;
  25525. }
  25526. this._forcePointsCloud = value;
  25527. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25528. },
  25529. enumerable: true,
  25530. configurable: true
  25531. });
  25532. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  25533. /**
  25534. * Gets or sets the animation properties override
  25535. */
  25536. get: function () {
  25537. return this._animationPropertiesOverride;
  25538. },
  25539. set: function (value) {
  25540. this._animationPropertiesOverride = value;
  25541. },
  25542. enumerable: true,
  25543. configurable: true
  25544. });
  25545. Object.defineProperty(Scene.prototype, "onDispose", {
  25546. /** Sets a function to be executed when this scene is disposed. */
  25547. set: function (callback) {
  25548. if (this._onDisposeObserver) {
  25549. this.onDisposeObservable.remove(this._onDisposeObserver);
  25550. }
  25551. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25552. },
  25553. enumerable: true,
  25554. configurable: true
  25555. });
  25556. Object.defineProperty(Scene.prototype, "beforeRender", {
  25557. /** Sets a function to be executed before rendering this scene */
  25558. set: function (callback) {
  25559. if (this._onBeforeRenderObserver) {
  25560. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  25561. }
  25562. if (callback) {
  25563. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  25564. }
  25565. },
  25566. enumerable: true,
  25567. configurable: true
  25568. });
  25569. Object.defineProperty(Scene.prototype, "afterRender", {
  25570. /** Sets a function to be executed after rendering this scene */
  25571. set: function (callback) {
  25572. if (this._onAfterRenderObserver) {
  25573. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  25574. }
  25575. if (callback) {
  25576. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  25577. }
  25578. },
  25579. enumerable: true,
  25580. configurable: true
  25581. });
  25582. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  25583. /** Sets a function to be executed before rendering a camera*/
  25584. set: function (callback) {
  25585. if (this._onBeforeCameraRenderObserver) {
  25586. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  25587. }
  25588. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  25589. },
  25590. enumerable: true,
  25591. configurable: true
  25592. });
  25593. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  25594. /** Sets a function to be executed after rendering a camera*/
  25595. set: function (callback) {
  25596. if (this._onAfterCameraRenderObserver) {
  25597. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  25598. }
  25599. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  25600. },
  25601. enumerable: true,
  25602. configurable: true
  25603. });
  25604. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  25605. /**
  25606. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  25607. */
  25608. get: function () {
  25609. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  25610. },
  25611. enumerable: true,
  25612. configurable: true
  25613. });
  25614. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  25615. get: function () {
  25616. return this._useRightHandedSystem;
  25617. },
  25618. /**
  25619. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  25620. */
  25621. set: function (value) {
  25622. if (this._useRightHandedSystem === value) {
  25623. return;
  25624. }
  25625. this._useRightHandedSystem = value;
  25626. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25627. },
  25628. enumerable: true,
  25629. configurable: true
  25630. });
  25631. /**
  25632. * Sets the step Id used by deterministic lock step
  25633. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25634. * @param newStepId defines the step Id
  25635. */
  25636. Scene.prototype.setStepId = function (newStepId) {
  25637. this._currentStepId = newStepId;
  25638. };
  25639. ;
  25640. /**
  25641. * Gets the step Id used by deterministic lock step
  25642. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25643. * @returns the step Id
  25644. */
  25645. Scene.prototype.getStepId = function () {
  25646. return this._currentStepId;
  25647. };
  25648. ;
  25649. /**
  25650. * Gets the internal step used by deterministic lock step
  25651. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25652. * @returns the internal step
  25653. */
  25654. Scene.prototype.getInternalStep = function () {
  25655. return this._currentInternalStep;
  25656. };
  25657. ;
  25658. Object.defineProperty(Scene.prototype, "fogEnabled", {
  25659. get: function () {
  25660. return this._fogEnabled;
  25661. },
  25662. /**
  25663. * Gets or sets a boolean indicating if fog is enabled on this scene
  25664. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25665. * (Default is true)
  25666. */
  25667. set: function (value) {
  25668. if (this._fogEnabled === value) {
  25669. return;
  25670. }
  25671. this._fogEnabled = value;
  25672. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25673. },
  25674. enumerable: true,
  25675. configurable: true
  25676. });
  25677. Object.defineProperty(Scene.prototype, "fogMode", {
  25678. get: function () {
  25679. return this._fogMode;
  25680. },
  25681. /**
  25682. * Gets or sets the fog mode to use
  25683. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25684. * | mode | value |
  25685. * | --- | --- |
  25686. * | FOGMODE_NONE | 0 |
  25687. * | FOGMODE_EXP | 1 |
  25688. * | FOGMODE_EXP2 | 2 |
  25689. * | FOGMODE_LINEAR | 3 |
  25690. */
  25691. set: function (value) {
  25692. if (this._fogMode === value) {
  25693. return;
  25694. }
  25695. this._fogMode = value;
  25696. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25697. },
  25698. enumerable: true,
  25699. configurable: true
  25700. });
  25701. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  25702. get: function () {
  25703. return this._shadowsEnabled;
  25704. },
  25705. /**
  25706. * Gets or sets a boolean indicating if shadows are enabled on this scene
  25707. */
  25708. set: function (value) {
  25709. if (this._shadowsEnabled === value) {
  25710. return;
  25711. }
  25712. this._shadowsEnabled = value;
  25713. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25714. },
  25715. enumerable: true,
  25716. configurable: true
  25717. });
  25718. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  25719. get: function () {
  25720. return this._lightsEnabled;
  25721. },
  25722. /**
  25723. * Gets or sets a boolean indicating if lights are enabled on this scene
  25724. */
  25725. set: function (value) {
  25726. if (this._lightsEnabled === value) {
  25727. return;
  25728. }
  25729. this._lightsEnabled = value;
  25730. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25731. },
  25732. enumerable: true,
  25733. configurable: true
  25734. });
  25735. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  25736. /** The default material used on meshes when no material is affected */
  25737. get: function () {
  25738. if (!this._defaultMaterial) {
  25739. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  25740. }
  25741. return this._defaultMaterial;
  25742. },
  25743. /** The default material used on meshes when no material is affected */
  25744. set: function (value) {
  25745. this._defaultMaterial = value;
  25746. },
  25747. enumerable: true,
  25748. configurable: true
  25749. });
  25750. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  25751. get: function () {
  25752. return this._texturesEnabled;
  25753. },
  25754. /**
  25755. * Gets or sets a boolean indicating if textures are enabled on this scene
  25756. */
  25757. set: function (value) {
  25758. if (this._texturesEnabled === value) {
  25759. return;
  25760. }
  25761. this._texturesEnabled = value;
  25762. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25763. },
  25764. enumerable: true,
  25765. configurable: true
  25766. });
  25767. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  25768. get: function () {
  25769. return this._skeletonsEnabled;
  25770. },
  25771. /**
  25772. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  25773. */
  25774. set: function (value) {
  25775. if (this._skeletonsEnabled === value) {
  25776. return;
  25777. }
  25778. this._skeletonsEnabled = value;
  25779. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  25780. },
  25781. enumerable: true,
  25782. configurable: true
  25783. });
  25784. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  25785. /** @hidden */
  25786. get: function () {
  25787. return this._alternateRendering;
  25788. },
  25789. enumerable: true,
  25790. configurable: true
  25791. });
  25792. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  25793. /**
  25794. * Gets the list of frustum planes (built from the active camera)
  25795. */
  25796. get: function () {
  25797. return this._frustumPlanes;
  25798. },
  25799. enumerable: true,
  25800. configurable: true
  25801. });
  25802. /**
  25803. * Registers the transient components if needed.
  25804. */
  25805. Scene.prototype._registerTransientComponents = function () {
  25806. // Register components that have been associated lately to the scene.
  25807. if (this._transientComponents.length > 0) {
  25808. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  25809. var component = _a[_i];
  25810. component.register();
  25811. }
  25812. this._transientComponents = [];
  25813. }
  25814. };
  25815. /**
  25816. * @hidden
  25817. * Add a component to the scene.
  25818. * Note that the ccomponent could be registered on th next frame if this is called after
  25819. * the register component stage.
  25820. * @param component Defines the component to add to the scene
  25821. */
  25822. Scene.prototype._addComponent = function (component) {
  25823. this._components.push(component);
  25824. this._transientComponents.push(component);
  25825. var serializableComponent = component;
  25826. if (serializableComponent.addFromContainer) {
  25827. this._serializableComponents.push(serializableComponent);
  25828. }
  25829. };
  25830. /**
  25831. * @hidden
  25832. * Gets a component from the scene.
  25833. * @param name defines the name of the component to retrieve
  25834. * @returns the component or null if not present
  25835. */
  25836. Scene.prototype._getComponent = function (name) {
  25837. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  25838. var component = _a[_i];
  25839. if (component.name === name) {
  25840. return component;
  25841. }
  25842. }
  25843. return null;
  25844. };
  25845. /**
  25846. * @hidden
  25847. */
  25848. Scene.prototype._getDefaultMeshCandidates = function () {
  25849. this._defaultMeshCandidates.data = this.meshes;
  25850. this._defaultMeshCandidates.length = this.meshes.length;
  25851. return this._defaultMeshCandidates;
  25852. };
  25853. /**
  25854. * @hidden
  25855. */
  25856. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  25857. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  25858. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  25859. return this._defaultSubMeshCandidates;
  25860. };
  25861. /**
  25862. * Sets the default candidate providers for the scene.
  25863. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  25864. * and getCollidingSubMeshCandidates to their default function
  25865. */
  25866. Scene.prototype.setDefaultCandidateProviders = function () {
  25867. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  25868. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25869. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25870. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25871. };
  25872. Object.defineProperty(Scene.prototype, "workerCollisions", {
  25873. /**
  25874. * Gets a boolean indicating if collisions are processed on a web worker
  25875. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  25876. */
  25877. get: function () {
  25878. return this._workerCollisions;
  25879. },
  25880. set: function (enabled) {
  25881. if (!BABYLON.CollisionCoordinatorLegacy) {
  25882. return;
  25883. }
  25884. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  25885. this._workerCollisions = enabled;
  25886. if (this.collisionCoordinator) {
  25887. this.collisionCoordinator.destroy();
  25888. }
  25889. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  25890. this.collisionCoordinator.init(this);
  25891. },
  25892. enumerable: true,
  25893. configurable: true
  25894. });
  25895. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  25896. /**
  25897. * Gets the mesh that is currently under the pointer
  25898. */
  25899. get: function () {
  25900. return this._pointerOverMesh;
  25901. },
  25902. enumerable: true,
  25903. configurable: true
  25904. });
  25905. Object.defineProperty(Scene.prototype, "pointerX", {
  25906. /**
  25907. * Gets the current on-screen X position of the pointer
  25908. */
  25909. get: function () {
  25910. return this._pointerX;
  25911. },
  25912. enumerable: true,
  25913. configurable: true
  25914. });
  25915. Object.defineProperty(Scene.prototype, "pointerY", {
  25916. /**
  25917. * Gets the current on-screen Y position of the pointer
  25918. */
  25919. get: function () {
  25920. return this._pointerY;
  25921. },
  25922. enumerable: true,
  25923. configurable: true
  25924. });
  25925. /**
  25926. * Gets the cached material (ie. the latest rendered one)
  25927. * @returns the cached material
  25928. */
  25929. Scene.prototype.getCachedMaterial = function () {
  25930. return this._cachedMaterial;
  25931. };
  25932. /**
  25933. * Gets the cached effect (ie. the latest rendered one)
  25934. * @returns the cached effect
  25935. */
  25936. Scene.prototype.getCachedEffect = function () {
  25937. return this._cachedEffect;
  25938. };
  25939. /**
  25940. * Gets the cached visibility state (ie. the latest rendered one)
  25941. * @returns the cached visibility state
  25942. */
  25943. Scene.prototype.getCachedVisibility = function () {
  25944. return this._cachedVisibility;
  25945. };
  25946. /**
  25947. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  25948. * @param material defines the current material
  25949. * @param effect defines the current effect
  25950. * @param visibility defines the current visibility state
  25951. * @returns true if one parameter is not cached
  25952. */
  25953. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  25954. if (visibility === void 0) { visibility = 1; }
  25955. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  25956. };
  25957. /**
  25958. * Gets the engine associated with the scene
  25959. * @returns an Engine
  25960. */
  25961. Scene.prototype.getEngine = function () {
  25962. return this._engine;
  25963. };
  25964. /**
  25965. * Gets the total number of vertices rendered per frame
  25966. * @returns the total number of vertices rendered per frame
  25967. */
  25968. Scene.prototype.getTotalVertices = function () {
  25969. return this._totalVertices.current;
  25970. };
  25971. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  25972. /**
  25973. * Gets the performance counter for total vertices
  25974. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25975. */
  25976. get: function () {
  25977. return this._totalVertices;
  25978. },
  25979. enumerable: true,
  25980. configurable: true
  25981. });
  25982. /**
  25983. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  25984. * @returns the total number of active indices rendered per frame
  25985. */
  25986. Scene.prototype.getActiveIndices = function () {
  25987. return this._activeIndices.current;
  25988. };
  25989. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  25990. /**
  25991. * Gets the performance counter for active indices
  25992. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25993. */
  25994. get: function () {
  25995. return this._activeIndices;
  25996. },
  25997. enumerable: true,
  25998. configurable: true
  25999. });
  26000. /**
  26001. * Gets the total number of active particles rendered per frame
  26002. * @returns the total number of active particles rendered per frame
  26003. */
  26004. Scene.prototype.getActiveParticles = function () {
  26005. return this._activeParticles.current;
  26006. };
  26007. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  26008. /**
  26009. * Gets the performance counter for active particles
  26010. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26011. */
  26012. get: function () {
  26013. return this._activeParticles;
  26014. },
  26015. enumerable: true,
  26016. configurable: true
  26017. });
  26018. /**
  26019. * Gets the total number of active bones rendered per frame
  26020. * @returns the total number of active bones rendered per frame
  26021. */
  26022. Scene.prototype.getActiveBones = function () {
  26023. return this._activeBones.current;
  26024. };
  26025. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  26026. /**
  26027. * Gets the performance counter for active bones
  26028. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26029. */
  26030. get: function () {
  26031. return this._activeBones;
  26032. },
  26033. enumerable: true,
  26034. configurable: true
  26035. });
  26036. /** @hidden */
  26037. Scene.prototype.getInterFramePerfCounter = function () {
  26038. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  26039. return 0;
  26040. };
  26041. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  26042. /** @hidden */
  26043. get: function () {
  26044. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  26045. return null;
  26046. },
  26047. enumerable: true,
  26048. configurable: true
  26049. });
  26050. /** @hidden */
  26051. Scene.prototype.getLastFrameDuration = function () {
  26052. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  26053. return 0;
  26054. };
  26055. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  26056. /** @hidden */
  26057. get: function () {
  26058. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  26059. return null;
  26060. },
  26061. enumerable: true,
  26062. configurable: true
  26063. });
  26064. /** @hidden */
  26065. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  26066. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  26067. return 0;
  26068. };
  26069. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  26070. /** @hidden */
  26071. get: function () {
  26072. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26073. return null;
  26074. },
  26075. enumerable: true,
  26076. configurable: true
  26077. });
  26078. /**
  26079. * Gets the array of active meshes
  26080. * @returns an array of AbstractMesh
  26081. */
  26082. Scene.prototype.getActiveMeshes = function () {
  26083. return this._activeMeshes;
  26084. };
  26085. /** @hidden */
  26086. Scene.prototype.getRenderTargetsDuration = function () {
  26087. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  26088. return 0;
  26089. };
  26090. /** @hidden */
  26091. Scene.prototype.getRenderDuration = function () {
  26092. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  26093. return 0;
  26094. };
  26095. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  26096. /** @hidden */
  26097. get: function () {
  26098. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26099. return null;
  26100. },
  26101. enumerable: true,
  26102. configurable: true
  26103. });
  26104. /** @hidden */
  26105. Scene.prototype.getParticlesDuration = function () {
  26106. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  26107. return 0;
  26108. };
  26109. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  26110. /** @hidden */
  26111. get: function () {
  26112. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26113. return null;
  26114. },
  26115. enumerable: true,
  26116. configurable: true
  26117. });
  26118. /** @hidden */
  26119. Scene.prototype.getSpritesDuration = function () {
  26120. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  26121. return 0;
  26122. };
  26123. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  26124. /** @hidden */
  26125. get: function () {
  26126. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  26127. return null;
  26128. },
  26129. enumerable: true,
  26130. configurable: true
  26131. });
  26132. /**
  26133. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  26134. * @returns a number
  26135. */
  26136. Scene.prototype.getAnimationRatio = function () {
  26137. return this._animationRatio !== undefined ? this._animationRatio : 1;
  26138. };
  26139. /**
  26140. * Gets an unique Id for the current render phase
  26141. * @returns a number
  26142. */
  26143. Scene.prototype.getRenderId = function () {
  26144. return this._renderId;
  26145. };
  26146. /**
  26147. * Gets an unique Id for the current frame
  26148. * @returns a number
  26149. */
  26150. Scene.prototype.getFrameId = function () {
  26151. return this._frameId;
  26152. };
  26153. /** Call this function if you want to manually increment the render Id*/
  26154. Scene.prototype.incrementRenderId = function () {
  26155. this._renderId++;
  26156. };
  26157. Scene.prototype._updatePointerPosition = function (evt) {
  26158. var canvasRect = this._engine.getRenderingCanvasClientRect();
  26159. if (!canvasRect) {
  26160. return;
  26161. }
  26162. this._pointerX = evt.clientX - canvasRect.left;
  26163. this._pointerY = evt.clientY - canvasRect.top;
  26164. this._unTranslatedPointerX = this._pointerX;
  26165. this._unTranslatedPointerY = this._pointerY;
  26166. };
  26167. Scene.prototype._createUbo = function () {
  26168. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26169. this._sceneUbo.addUniform("viewProjection", 16);
  26170. this._sceneUbo.addUniform("view", 16);
  26171. };
  26172. Scene.prototype._createAlternateUbo = function () {
  26173. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26174. this._alternateSceneUbo.addUniform("viewProjection", 16);
  26175. this._alternateSceneUbo.addUniform("view", 16);
  26176. };
  26177. // Pointers handling
  26178. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  26179. if (pointerInfo.pickInfo) {
  26180. if (!pointerInfo.pickInfo.ray) {
  26181. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  26182. }
  26183. }
  26184. };
  26185. /**
  26186. * Use this method to simulate a pointer move on a mesh
  26187. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26188. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26189. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26190. * @returns the current scene
  26191. */
  26192. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  26193. var evt = new PointerEvent("pointermove", pointerEventInit);
  26194. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  26195. return this;
  26196. }
  26197. return this._processPointerMove(pickResult, evt);
  26198. };
  26199. Scene.prototype._processPointerMove = function (pickResult, evt) {
  26200. var canvas = this._engine.getRenderingCanvas();
  26201. if (!canvas) {
  26202. return this;
  26203. }
  26204. // Restore pointer
  26205. canvas.style.cursor = this.defaultCursor;
  26206. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  26207. if (isMeshPicked) {
  26208. this.setPointerOverMesh(pickResult.pickedMesh);
  26209. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  26210. if (this._pointerOverMesh.actionManager.hoverCursor) {
  26211. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  26212. }
  26213. else {
  26214. canvas.style.cursor = this.hoverCursor;
  26215. }
  26216. }
  26217. }
  26218. else {
  26219. this.setPointerOverMesh(null);
  26220. }
  26221. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  26222. var step = _a[_i];
  26223. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  26224. }
  26225. if (pickResult) {
  26226. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  26227. if (this.onPointerMove) {
  26228. this.onPointerMove(evt, pickResult, type);
  26229. }
  26230. if (this.onPointerObservable.hasObservers()) {
  26231. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26232. this._setRayOnPointerInfo(pi);
  26233. this.onPointerObservable.notifyObservers(pi, type);
  26234. }
  26235. }
  26236. return this;
  26237. };
  26238. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  26239. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  26240. if (pickResult) {
  26241. pi.ray = pickResult.ray;
  26242. }
  26243. this.onPrePointerObservable.notifyObservers(pi, type);
  26244. if (pi.skipOnPointerObservable) {
  26245. return true;
  26246. }
  26247. else {
  26248. return false;
  26249. }
  26250. };
  26251. /**
  26252. * Use this method to simulate a pointer down on a mesh
  26253. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26254. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26255. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26256. * @returns the current scene
  26257. */
  26258. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  26259. var evt = new PointerEvent("pointerdown", pointerEventInit);
  26260. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26261. return this;
  26262. }
  26263. return this._processPointerDown(pickResult, evt);
  26264. };
  26265. Scene.prototype._processPointerDown = function (pickResult, evt) {
  26266. var _this = this;
  26267. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  26268. this._pickedDownMesh = pickResult.pickedMesh;
  26269. var actionManager = pickResult.pickedMesh.actionManager;
  26270. if (actionManager) {
  26271. if (actionManager.hasPickTriggers) {
  26272. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26273. switch (evt.button) {
  26274. case 0:
  26275. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26276. break;
  26277. case 1:
  26278. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26279. break;
  26280. case 2:
  26281. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26282. break;
  26283. }
  26284. }
  26285. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  26286. window.setTimeout(function () {
  26287. 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);
  26288. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  26289. if (_this._totalPointersPressed !== 0 &&
  26290. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  26291. !_this._isPointerSwiping()) {
  26292. _this._startingPointerTime = 0;
  26293. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26294. }
  26295. }
  26296. }, Scene.LongPressDelay);
  26297. }
  26298. }
  26299. }
  26300. else {
  26301. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  26302. var step = _a[_i];
  26303. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26304. }
  26305. }
  26306. if (pickResult) {
  26307. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  26308. if (this.onPointerDown) {
  26309. this.onPointerDown(evt, pickResult, type);
  26310. }
  26311. if (this.onPointerObservable.hasObservers()) {
  26312. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26313. this._setRayOnPointerInfo(pi);
  26314. this.onPointerObservable.notifyObservers(pi, type);
  26315. }
  26316. }
  26317. return this;
  26318. };
  26319. /**
  26320. * Use this method to simulate a pointer up on a mesh
  26321. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26322. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26323. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26324. * @returns the current scene
  26325. */
  26326. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  26327. var evt = new PointerEvent("pointerup", pointerEventInit);
  26328. var clickInfo = new ClickInfo();
  26329. clickInfo.singleClick = true;
  26330. clickInfo.ignore = true;
  26331. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26332. return this;
  26333. }
  26334. return this._processPointerUp(pickResult, evt, clickInfo);
  26335. };
  26336. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  26337. if (pickResult && pickResult && pickResult.pickedMesh) {
  26338. this._pickedUpMesh = pickResult.pickedMesh;
  26339. if (this._pickedDownMesh === this._pickedUpMesh) {
  26340. if (this.onPointerPick) {
  26341. this.onPointerPick(evt, pickResult);
  26342. }
  26343. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  26344. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  26345. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  26346. this._setRayOnPointerInfo(pi);
  26347. this.onPointerObservable.notifyObservers(pi, type_1);
  26348. }
  26349. }
  26350. if (pickResult.pickedMesh.actionManager) {
  26351. if (clickInfo.ignore) {
  26352. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26353. }
  26354. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  26355. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26356. }
  26357. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26358. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26359. }
  26360. }
  26361. }
  26362. else {
  26363. if (!clickInfo.ignore) {
  26364. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  26365. var step = _a[_i];
  26366. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26367. }
  26368. }
  26369. }
  26370. if (this._pickedDownMesh &&
  26371. this._pickedDownMesh.actionManager &&
  26372. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  26373. this._pickedDownMesh !== this._pickedUpMesh) {
  26374. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  26375. }
  26376. var type = BABYLON.PointerEventTypes.POINTERUP;
  26377. if (this.onPointerObservable.hasObservers()) {
  26378. if (!clickInfo.ignore) {
  26379. if (!clickInfo.hasSwiped) {
  26380. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26381. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  26382. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  26383. this._setRayOnPointerInfo(pi);
  26384. this.onPointerObservable.notifyObservers(pi, type_2);
  26385. }
  26386. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26387. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  26388. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  26389. this._setRayOnPointerInfo(pi);
  26390. this.onPointerObservable.notifyObservers(pi, type_3);
  26391. }
  26392. }
  26393. }
  26394. else {
  26395. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26396. this._setRayOnPointerInfo(pi);
  26397. this.onPointerObservable.notifyObservers(pi, type);
  26398. }
  26399. }
  26400. if (this.onPointerUp) {
  26401. this.onPointerUp(evt, pickResult, type);
  26402. }
  26403. return this;
  26404. };
  26405. /**
  26406. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  26407. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  26408. * @returns true if the pointer was captured
  26409. */
  26410. Scene.prototype.isPointerCaptured = function (pointerId) {
  26411. if (pointerId === void 0) { pointerId = 0; }
  26412. return this._pointerCaptures[pointerId];
  26413. };
  26414. /** @hidden */
  26415. Scene.prototype._isPointerSwiping = function () {
  26416. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  26417. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  26418. };
  26419. /**
  26420. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  26421. * @param attachUp defines if you want to attach events to pointerup
  26422. * @param attachDown defines if you want to attach events to pointerdown
  26423. * @param attachMove defines if you want to attach events to pointermove
  26424. */
  26425. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  26426. var _this = this;
  26427. if (attachUp === void 0) { attachUp = true; }
  26428. if (attachDown === void 0) { attachDown = true; }
  26429. if (attachMove === void 0) { attachMove = true; }
  26430. this._initActionManager = function (act, clickInfo) {
  26431. if (!_this._meshPickProceed) {
  26432. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26433. _this._currentPickResult = pickResult;
  26434. if (pickResult) {
  26435. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  26436. }
  26437. _this._meshPickProceed = true;
  26438. }
  26439. return act;
  26440. };
  26441. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  26442. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  26443. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  26444. btn !== _this._previousButtonPressed) {
  26445. _this._doubleClickOccured = false;
  26446. clickInfo.singleClick = true;
  26447. clickInfo.ignore = false;
  26448. cb(clickInfo, _this._currentPickResult);
  26449. }
  26450. };
  26451. this._initClickEvent = function (obs1, obs2, evt, cb) {
  26452. var clickInfo = new ClickInfo();
  26453. _this._currentPickResult = null;
  26454. var act = null;
  26455. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  26456. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  26457. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26458. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  26459. act = _this._initActionManager(act, clickInfo);
  26460. if (act)
  26461. checkPicking = act.hasPickTriggers;
  26462. }
  26463. if (checkPicking) {
  26464. var btn = evt.button;
  26465. clickInfo.hasSwiped = _this._isPointerSwiping();
  26466. if (!clickInfo.hasSwiped) {
  26467. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  26468. if (!checkSingleClickImmediately) {
  26469. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  26470. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26471. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26472. act = _this._initActionManager(act, clickInfo);
  26473. if (act)
  26474. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26475. }
  26476. }
  26477. if (checkSingleClickImmediately) {
  26478. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  26479. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  26480. btn !== _this._previousButtonPressed) {
  26481. clickInfo.singleClick = true;
  26482. cb(clickInfo, _this._currentPickResult);
  26483. }
  26484. }
  26485. // at least one double click is required to be check and exclusive double click is enabled
  26486. else {
  26487. // wait that no double click has been raised during the double click delay
  26488. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26489. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  26490. }
  26491. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  26492. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26493. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26494. act = _this._initActionManager(act, clickInfo);
  26495. if (act)
  26496. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26497. }
  26498. if (checkDoubleClick) {
  26499. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  26500. if (btn === _this._previousButtonPressed &&
  26501. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  26502. !_this._doubleClickOccured) {
  26503. // pointer has not moved for 2 clicks, it's a double click
  26504. if (!clickInfo.hasSwiped &&
  26505. !_this._isPointerSwiping()) {
  26506. _this._previousStartingPointerTime = 0;
  26507. _this._doubleClickOccured = true;
  26508. clickInfo.doubleClick = true;
  26509. clickInfo.ignore = false;
  26510. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  26511. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26512. }
  26513. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26514. cb(clickInfo, _this._currentPickResult);
  26515. }
  26516. // if the two successive clicks are too far, it's just two simple clicks
  26517. else {
  26518. _this._doubleClickOccured = false;
  26519. _this._previousStartingPointerTime = _this._startingPointerTime;
  26520. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26521. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26522. _this._previousButtonPressed = btn;
  26523. if (Scene.ExclusiveDoubleClickMode) {
  26524. if (_this._previousDelayedSimpleClickTimeout) {
  26525. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26526. }
  26527. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26528. cb(clickInfo, _this._previousPickResult);
  26529. }
  26530. else {
  26531. cb(clickInfo, _this._currentPickResult);
  26532. }
  26533. }
  26534. }
  26535. // just the first click of the double has been raised
  26536. else {
  26537. _this._doubleClickOccured = false;
  26538. _this._previousStartingPointerTime = _this._startingPointerTime;
  26539. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26540. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26541. _this._previousButtonPressed = btn;
  26542. }
  26543. }
  26544. }
  26545. }
  26546. clickInfo.ignore = true;
  26547. cb(clickInfo, _this._currentPickResult);
  26548. };
  26549. this._onPointerMove = function (evt) {
  26550. _this._updatePointerPosition(evt);
  26551. // PreObservable support
  26552. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  26553. return;
  26554. }
  26555. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26556. return;
  26557. }
  26558. if (!_this.pointerMovePredicate) {
  26559. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  26560. }
  26561. // Meshes
  26562. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  26563. _this._processPointerMove(pickResult, evt);
  26564. };
  26565. this._onPointerDown = function (evt) {
  26566. _this._totalPointersPressed++;
  26567. _this._pickedDownMesh = null;
  26568. _this._meshPickProceed = false;
  26569. _this._updatePointerPosition(evt);
  26570. if (_this.preventDefaultOnPointerDown && canvas) {
  26571. evt.preventDefault();
  26572. canvas.focus();
  26573. }
  26574. // PreObservable support
  26575. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26576. return;
  26577. }
  26578. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26579. return;
  26580. }
  26581. _this._pointerCaptures[evt.pointerId] = true;
  26582. _this._startingPointerPosition.x = _this._pointerX;
  26583. _this._startingPointerPosition.y = _this._pointerY;
  26584. _this._startingPointerTime = Date.now();
  26585. if (!_this.pointerDownPredicate) {
  26586. _this.pointerDownPredicate = function (mesh) {
  26587. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26588. };
  26589. }
  26590. // Meshes
  26591. _this._pickedDownMesh = null;
  26592. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26593. _this._processPointerDown(pickResult, evt);
  26594. };
  26595. this._onPointerUp = function (evt) {
  26596. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  26597. return; // So we need to test it the pointer down was pressed before.
  26598. }
  26599. _this._totalPointersPressed--;
  26600. _this._pickedUpMesh = null;
  26601. _this._meshPickProceed = false;
  26602. _this._updatePointerPosition(evt);
  26603. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  26604. // PreObservable support
  26605. if (_this.onPrePointerObservable.hasObservers()) {
  26606. if (!clickInfo.ignore) {
  26607. if (!clickInfo.hasSwiped) {
  26608. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26609. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  26610. return;
  26611. }
  26612. }
  26613. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26614. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26615. return;
  26616. }
  26617. }
  26618. }
  26619. }
  26620. else {
  26621. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26622. return;
  26623. }
  26624. }
  26625. }
  26626. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26627. return;
  26628. }
  26629. _this._pointerCaptures[evt.pointerId] = false;
  26630. if (!_this.pointerUpPredicate) {
  26631. _this.pointerUpPredicate = function (mesh) {
  26632. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26633. };
  26634. }
  26635. // Meshes
  26636. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  26637. _this._initActionManager(null, clickInfo);
  26638. }
  26639. if (!pickResult) {
  26640. pickResult = _this._currentPickResult;
  26641. }
  26642. _this._processPointerUp(pickResult, evt, clickInfo);
  26643. _this._previousPickResult = _this._currentPickResult;
  26644. });
  26645. };
  26646. this._onKeyDown = function (evt) {
  26647. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  26648. if (_this.onPreKeyboardObservable.hasObservers()) {
  26649. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26650. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26651. if (pi.skipOnPointerObservable) {
  26652. return;
  26653. }
  26654. }
  26655. if (_this.onKeyboardObservable.hasObservers()) {
  26656. var pi = new BABYLON.KeyboardInfo(type, evt);
  26657. _this.onKeyboardObservable.notifyObservers(pi, type);
  26658. }
  26659. if (_this.actionManager) {
  26660. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26661. }
  26662. };
  26663. this._onKeyUp = function (evt) {
  26664. var type = BABYLON.KeyboardEventTypes.KEYUP;
  26665. if (_this.onPreKeyboardObservable.hasObservers()) {
  26666. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26667. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26668. if (pi.skipOnPointerObservable) {
  26669. return;
  26670. }
  26671. }
  26672. if (_this.onKeyboardObservable.hasObservers()) {
  26673. var pi = new BABYLON.KeyboardInfo(type, evt);
  26674. _this.onKeyboardObservable.notifyObservers(pi, type);
  26675. }
  26676. if (_this.actionManager) {
  26677. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26678. }
  26679. };
  26680. var engine = this.getEngine();
  26681. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  26682. if (!canvas) {
  26683. return;
  26684. }
  26685. canvas.addEventListener("keydown", _this._onKeyDown, false);
  26686. canvas.addEventListener("keyup", _this._onKeyUp, false);
  26687. });
  26688. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  26689. if (!canvas) {
  26690. return;
  26691. }
  26692. canvas.removeEventListener("keydown", _this._onKeyDown);
  26693. canvas.removeEventListener("keyup", _this._onKeyUp);
  26694. });
  26695. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26696. var canvas = this._engine.getRenderingCanvas();
  26697. if (!canvas) {
  26698. return;
  26699. }
  26700. if (attachMove) {
  26701. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  26702. // Wheel
  26703. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  26704. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  26705. }
  26706. if (attachDown) {
  26707. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  26708. }
  26709. if (attachUp) {
  26710. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  26711. }
  26712. canvas.tabIndex = 1;
  26713. };
  26714. /** Detaches all event handlers*/
  26715. Scene.prototype.detachControl = function () {
  26716. var engine = this.getEngine();
  26717. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26718. var canvas = engine.getRenderingCanvas();
  26719. if (!canvas) {
  26720. return;
  26721. }
  26722. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  26723. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  26724. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  26725. if (this._onCanvasBlurObserver) {
  26726. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  26727. }
  26728. if (this._onCanvasFocusObserver) {
  26729. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  26730. }
  26731. // Wheel
  26732. canvas.removeEventListener('mousewheel', this._onPointerMove);
  26733. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  26734. // Keyboard
  26735. canvas.removeEventListener("keydown", this._onKeyDown);
  26736. canvas.removeEventListener("keyup", this._onKeyUp);
  26737. // Observables
  26738. this.onKeyboardObservable.clear();
  26739. this.onPreKeyboardObservable.clear();
  26740. this.onPointerObservable.clear();
  26741. this.onPrePointerObservable.clear();
  26742. };
  26743. /**
  26744. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  26745. * Delay loaded resources are not taking in account
  26746. * @return true if all required resources are ready
  26747. */
  26748. Scene.prototype.isReady = function () {
  26749. if (this._isDisposed) {
  26750. return false;
  26751. }
  26752. if (this._pendingData.length > 0) {
  26753. return false;
  26754. }
  26755. var index;
  26756. var engine = this.getEngine();
  26757. // Geometries
  26758. for (index = 0; index < this.geometries.length; index++) {
  26759. var geometry = this.geometries[index];
  26760. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26761. return false;
  26762. }
  26763. }
  26764. // Meshes
  26765. for (index = 0; index < this.meshes.length; index++) {
  26766. var mesh = this.meshes[index];
  26767. if (!mesh.isEnabled()) {
  26768. continue;
  26769. }
  26770. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26771. continue;
  26772. }
  26773. if (!mesh.isReady(true)) {
  26774. return false;
  26775. }
  26776. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  26777. // Is Ready For Mesh
  26778. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  26779. var step = _a[_i];
  26780. if (!step.action(mesh, hardwareInstancedRendering)) {
  26781. return false;
  26782. }
  26783. }
  26784. }
  26785. // Post-processes
  26786. if (this.activeCameras && this.activeCameras.length > 0) {
  26787. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  26788. var camera = _c[_b];
  26789. if (!camera.isReady(true)) {
  26790. return false;
  26791. }
  26792. }
  26793. }
  26794. else if (this.activeCamera) {
  26795. if (!this.activeCamera.isReady(true)) {
  26796. return false;
  26797. }
  26798. }
  26799. // Particles
  26800. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  26801. var particleSystem = _e[_d];
  26802. if (!particleSystem.isReady()) {
  26803. return false;
  26804. }
  26805. }
  26806. return true;
  26807. };
  26808. /** Resets all cached information relative to material (including effect and visibility) */
  26809. Scene.prototype.resetCachedMaterial = function () {
  26810. this._cachedMaterial = null;
  26811. this._cachedEffect = null;
  26812. this._cachedVisibility = null;
  26813. };
  26814. /**
  26815. * Registers a function to be called before every frame render
  26816. * @param func defines the function to register
  26817. */
  26818. Scene.prototype.registerBeforeRender = function (func) {
  26819. this.onBeforeRenderObservable.add(func);
  26820. };
  26821. /**
  26822. * Unregisters a function called before every frame render
  26823. * @param func defines the function to unregister
  26824. */
  26825. Scene.prototype.unregisterBeforeRender = function (func) {
  26826. this.onBeforeRenderObservable.removeCallback(func);
  26827. };
  26828. /**
  26829. * Registers a function to be called after every frame render
  26830. * @param func defines the function to register
  26831. */
  26832. Scene.prototype.registerAfterRender = function (func) {
  26833. this.onAfterRenderObservable.add(func);
  26834. };
  26835. /**
  26836. * Unregisters a function called after every frame render
  26837. * @param func defines the function to unregister
  26838. */
  26839. Scene.prototype.unregisterAfterRender = function (func) {
  26840. this.onAfterRenderObservable.removeCallback(func);
  26841. };
  26842. Scene.prototype._executeOnceBeforeRender = function (func) {
  26843. var _this = this;
  26844. var execFunc = function () {
  26845. func();
  26846. setTimeout(function () {
  26847. _this.unregisterBeforeRender(execFunc);
  26848. });
  26849. };
  26850. this.registerBeforeRender(execFunc);
  26851. };
  26852. /**
  26853. * The provided function will run before render once and will be disposed afterwards.
  26854. * A timeout delay can be provided so that the function will be executed in N ms.
  26855. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  26856. * @param func The function to be executed.
  26857. * @param timeout optional delay in ms
  26858. */
  26859. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  26860. var _this = this;
  26861. if (timeout !== undefined) {
  26862. setTimeout(function () {
  26863. _this._executeOnceBeforeRender(func);
  26864. }, timeout);
  26865. }
  26866. else {
  26867. this._executeOnceBeforeRender(func);
  26868. }
  26869. };
  26870. /** @hidden */
  26871. Scene.prototype._addPendingData = function (data) {
  26872. this._pendingData.push(data);
  26873. };
  26874. /** @hidden */
  26875. Scene.prototype._removePendingData = function (data) {
  26876. var wasLoading = this.isLoading;
  26877. var index = this._pendingData.indexOf(data);
  26878. if (index !== -1) {
  26879. this._pendingData.splice(index, 1);
  26880. }
  26881. if (wasLoading && !this.isLoading) {
  26882. this.onDataLoadedObservable.notifyObservers(this);
  26883. }
  26884. };
  26885. /**
  26886. * Returns the number of items waiting to be loaded
  26887. * @returns the number of items waiting to be loaded
  26888. */
  26889. Scene.prototype.getWaitingItemsCount = function () {
  26890. return this._pendingData.length;
  26891. };
  26892. Object.defineProperty(Scene.prototype, "isLoading", {
  26893. /**
  26894. * Returns a boolean indicating if the scene is still loading data
  26895. */
  26896. get: function () {
  26897. return this._pendingData.length > 0;
  26898. },
  26899. enumerable: true,
  26900. configurable: true
  26901. });
  26902. /**
  26903. * Registers a function to be executed when the scene is ready
  26904. * @param {Function} func - the function to be executed
  26905. */
  26906. Scene.prototype.executeWhenReady = function (func) {
  26907. var _this = this;
  26908. this.onReadyObservable.add(func);
  26909. if (this._executeWhenReadyTimeoutId !== -1) {
  26910. return;
  26911. }
  26912. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26913. _this._checkIsReady();
  26914. }, 150);
  26915. };
  26916. /**
  26917. * Returns a promise that resolves when the scene is ready
  26918. * @returns A promise that resolves when the scene is ready
  26919. */
  26920. Scene.prototype.whenReadyAsync = function () {
  26921. var _this = this;
  26922. return new Promise(function (resolve) {
  26923. _this.executeWhenReady(function () {
  26924. resolve();
  26925. });
  26926. });
  26927. };
  26928. /** @hidden */
  26929. Scene.prototype._checkIsReady = function () {
  26930. var _this = this;
  26931. this._registerTransientComponents();
  26932. if (this.isReady()) {
  26933. this.onReadyObservable.notifyObservers(this);
  26934. this.onReadyObservable.clear();
  26935. this._executeWhenReadyTimeoutId = -1;
  26936. return;
  26937. }
  26938. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26939. _this._checkIsReady();
  26940. }, 150);
  26941. };
  26942. // Animations
  26943. /**
  26944. * Will start the animation sequence of a given target
  26945. * @param target defines the target
  26946. * @param from defines from which frame should animation start
  26947. * @param to defines until which frame should animation run.
  26948. * @param weight defines the weight to apply to the animation (1.0 by default)
  26949. * @param loop defines if the animation loops
  26950. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26951. * @param onAnimationEnd defines the function to be executed when the animation ends
  26952. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26953. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26954. * @returns the animatable object created for this animation
  26955. */
  26956. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  26957. if (weight === void 0) { weight = 1.0; }
  26958. if (speedRatio === void 0) { speedRatio = 1.0; }
  26959. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  26960. returnedAnimatable.weight = weight;
  26961. return returnedAnimatable;
  26962. };
  26963. /**
  26964. * Will start the animation sequence of a given target
  26965. * @param target defines the target
  26966. * @param from defines from which frame should animation start
  26967. * @param to defines until which frame should animation run.
  26968. * @param loop defines if the animation loops
  26969. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26970. * @param onAnimationEnd defines the function to be executed when the animation ends
  26971. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26972. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26973. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26974. * @returns the animatable object created for this animation
  26975. */
  26976. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  26977. if (speedRatio === void 0) { speedRatio = 1.0; }
  26978. if (stopCurrent === void 0) { stopCurrent = true; }
  26979. if (from > to && speedRatio > 0) {
  26980. speedRatio *= -1;
  26981. }
  26982. if (stopCurrent) {
  26983. this.stopAnimation(target, undefined, targetMask);
  26984. }
  26985. if (!animatable) {
  26986. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26987. }
  26988. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  26989. // Local animations
  26990. if (target.animations && shouldRunTargetAnimations) {
  26991. animatable.appendAnimations(target, target.animations);
  26992. }
  26993. // Children animations
  26994. if (target.getAnimatables) {
  26995. var animatables = target.getAnimatables();
  26996. for (var index = 0; index < animatables.length; index++) {
  26997. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  26998. }
  26999. }
  27000. animatable.reset();
  27001. return animatable;
  27002. };
  27003. /**
  27004. * Begin a new animation on a given node
  27005. * @param target defines the target where the animation will take place
  27006. * @param animations defines the list of animations to start
  27007. * @param from defines the initial value
  27008. * @param to defines the final value
  27009. * @param loop defines if you want animation to loop (off by default)
  27010. * @param speedRatio defines the speed ratio to apply to all animations
  27011. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  27012. * @returns the list of created animatables
  27013. */
  27014. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  27015. if (speedRatio === undefined) {
  27016. speedRatio = 1.0;
  27017. }
  27018. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  27019. return animatable;
  27020. };
  27021. /**
  27022. * Begin a new animation on a given node and its hierarchy
  27023. * @param target defines the root node where the animation will take place
  27024. * @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.
  27025. * @param animations defines the list of animations to start
  27026. * @param from defines the initial value
  27027. * @param to defines the final value
  27028. * @param loop defines if you want animation to loop (off by default)
  27029. * @param speedRatio defines the speed ratio to apply to all animations
  27030. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  27031. * @returns the list of animatables created for all nodes
  27032. */
  27033. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  27034. var children = target.getDescendants(directDescendantsOnly);
  27035. var result = [];
  27036. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  27037. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  27038. var child = children_1[_i];
  27039. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  27040. }
  27041. return result;
  27042. };
  27043. /**
  27044. * Gets the animatable associated with a specific target
  27045. * @param target defines the target of the animatable
  27046. * @returns the required animatable if found
  27047. */
  27048. Scene.prototype.getAnimatableByTarget = function (target) {
  27049. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27050. if (this._activeAnimatables[index].target === target) {
  27051. return this._activeAnimatables[index];
  27052. }
  27053. }
  27054. return null;
  27055. };
  27056. /**
  27057. * Gets all animatables associated with a given target
  27058. * @param target defines the target to look animatables for
  27059. * @returns an array of Animatables
  27060. */
  27061. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  27062. var result = [];
  27063. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27064. if (this._activeAnimatables[index].target === target) {
  27065. result.push(this._activeAnimatables[index]);
  27066. }
  27067. }
  27068. return result;
  27069. };
  27070. Object.defineProperty(Scene.prototype, "animatables", {
  27071. /**
  27072. * Gets all animatable attached to the scene
  27073. */
  27074. get: function () {
  27075. return this._activeAnimatables;
  27076. },
  27077. enumerable: true,
  27078. configurable: true
  27079. });
  27080. /**
  27081. * Will stop the animation of the given target
  27082. * @param target - the target
  27083. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  27084. * @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)
  27085. */
  27086. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  27087. var animatables = this.getAllAnimatablesByTarget(target);
  27088. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  27089. var animatable = animatables_1[_i];
  27090. animatable.stop(animationName, targetMask);
  27091. }
  27092. };
  27093. /**
  27094. * Stops and removes all animations that have been applied to the scene
  27095. */
  27096. Scene.prototype.stopAllAnimations = function () {
  27097. if (this._activeAnimatables) {
  27098. for (var i = 0; i < this._activeAnimatables.length; i++) {
  27099. this._activeAnimatables[i].stop();
  27100. }
  27101. this._activeAnimatables = [];
  27102. }
  27103. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  27104. var group = _a[_i];
  27105. group.stop();
  27106. }
  27107. };
  27108. Scene.prototype._animate = function () {
  27109. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  27110. return;
  27111. }
  27112. // Getting time
  27113. var now = BABYLON.Tools.Now;
  27114. if (!this._animationTimeLast) {
  27115. if (this._pendingData.length > 0) {
  27116. return;
  27117. }
  27118. this._animationTimeLast = now;
  27119. }
  27120. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  27121. this._animationTime += deltaTime;
  27122. this._animationTimeLast = now;
  27123. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27124. this._activeAnimatables[index]._animate(this._animationTime);
  27125. }
  27126. // Late animation bindings
  27127. this._processLateAnimationBindings();
  27128. };
  27129. /** @hidden */
  27130. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  27131. var target = runtimeAnimation.target;
  27132. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  27133. if (!target._lateAnimationHolders) {
  27134. target._lateAnimationHolders = {};
  27135. }
  27136. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  27137. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  27138. totalWeight: 0,
  27139. animations: [],
  27140. originalValue: originalValue
  27141. };
  27142. }
  27143. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  27144. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  27145. };
  27146. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  27147. var normalizer = 1.0;
  27148. var finalPosition = BABYLON.Tmp.Vector3[0];
  27149. var finalScaling = BABYLON.Tmp.Vector3[1];
  27150. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  27151. var startIndex = 0;
  27152. var originalAnimation = holder.animations[0];
  27153. var originalValue = holder.originalValue;
  27154. var scale = 1;
  27155. if (holder.totalWeight < 1.0) {
  27156. // We need to mix the original value in
  27157. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27158. scale = 1.0 - holder.totalWeight;
  27159. }
  27160. else {
  27161. startIndex = 1;
  27162. // We need to normalize the weights
  27163. normalizer = holder.totalWeight;
  27164. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27165. scale = originalAnimation.weight / normalizer;
  27166. if (scale == 1) {
  27167. return originalAnimation.currentValue;
  27168. }
  27169. }
  27170. finalScaling.scaleInPlace(scale);
  27171. finalPosition.scaleInPlace(scale);
  27172. finalQuaternion.scaleInPlace(scale);
  27173. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27174. var runtimeAnimation = holder.animations[animIndex];
  27175. var scale = runtimeAnimation.weight / normalizer;
  27176. var currentPosition = BABYLON.Tmp.Vector3[2];
  27177. var currentScaling = BABYLON.Tmp.Vector3[3];
  27178. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  27179. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  27180. currentScaling.scaleAndAddToRef(scale, finalScaling);
  27181. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  27182. currentPosition.scaleAndAddToRef(scale, finalPosition);
  27183. }
  27184. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  27185. return originalAnimation._workValue;
  27186. };
  27187. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  27188. var originalAnimation = holder.animations[0];
  27189. var originalValue = holder.originalValue;
  27190. if (holder.animations.length === 1) {
  27191. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  27192. return refQuaternion;
  27193. }
  27194. var normalizer = 1.0;
  27195. var quaternions;
  27196. var weights;
  27197. if (holder.totalWeight < 1.0) {
  27198. var scale = 1.0 - holder.totalWeight;
  27199. quaternions = [];
  27200. weights = [];
  27201. quaternions.push(originalValue);
  27202. weights.push(scale);
  27203. }
  27204. else {
  27205. if (holder.animations.length === 2) { // Slerp as soon as we can
  27206. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  27207. return refQuaternion;
  27208. }
  27209. quaternions = [];
  27210. weights = [];
  27211. normalizer = holder.totalWeight;
  27212. }
  27213. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  27214. var runtimeAnimation = holder.animations[animIndex];
  27215. quaternions.push(runtimeAnimation.currentValue);
  27216. weights.push(runtimeAnimation.weight / normalizer);
  27217. }
  27218. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  27219. var cumulativeAmount = 0;
  27220. var cumulativeQuaternion = null;
  27221. for (var index = 0; index < quaternions.length;) {
  27222. if (!cumulativeQuaternion) {
  27223. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  27224. cumulativeQuaternion = refQuaternion;
  27225. cumulativeAmount = weights[index] + weights[index + 1];
  27226. index += 2;
  27227. continue;
  27228. }
  27229. cumulativeAmount += weights[index];
  27230. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  27231. index++;
  27232. }
  27233. return cumulativeQuaternion;
  27234. };
  27235. Scene.prototype._processLateAnimationBindings = function () {
  27236. if (!this._registeredForLateAnimationBindings.length) {
  27237. return;
  27238. }
  27239. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  27240. var target = this._registeredForLateAnimationBindings.data[index];
  27241. for (var path in target._lateAnimationHolders) {
  27242. var holder = target._lateAnimationHolders[path];
  27243. var originalAnimation = holder.animations[0];
  27244. var originalValue = holder.originalValue;
  27245. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  27246. var finalValue = target[path];
  27247. if (matrixDecomposeMode) {
  27248. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  27249. }
  27250. else {
  27251. var quaternionMode = originalValue.w !== undefined;
  27252. if (quaternionMode) {
  27253. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  27254. }
  27255. else {
  27256. var startIndex = 0;
  27257. var normalizer = 1.0;
  27258. if (holder.totalWeight < 1.0) {
  27259. // We need to mix the original value in
  27260. if (originalValue.scale) {
  27261. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  27262. }
  27263. else {
  27264. finalValue = originalValue * (1.0 - holder.totalWeight);
  27265. }
  27266. }
  27267. else {
  27268. // We need to normalize the weights
  27269. normalizer = holder.totalWeight;
  27270. var scale_1 = originalAnimation.weight / normalizer;
  27271. if (scale_1 !== 1) {
  27272. if (originalAnimation.currentValue.scale) {
  27273. finalValue = originalAnimation.currentValue.scale(scale_1);
  27274. }
  27275. else {
  27276. finalValue = originalAnimation.currentValue * scale_1;
  27277. }
  27278. }
  27279. else {
  27280. finalValue = originalAnimation.currentValue;
  27281. }
  27282. startIndex = 1;
  27283. }
  27284. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27285. var runtimeAnimation = holder.animations[animIndex];
  27286. var scale = runtimeAnimation.weight / normalizer;
  27287. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  27288. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  27289. }
  27290. else {
  27291. finalValue += runtimeAnimation.currentValue * scale;
  27292. }
  27293. }
  27294. }
  27295. }
  27296. target[path] = finalValue;
  27297. }
  27298. target._lateAnimationHolders = {};
  27299. }
  27300. this._registeredForLateAnimationBindings.reset();
  27301. };
  27302. // Matrix
  27303. /** @hidden */
  27304. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  27305. this._useAlternateCameraConfiguration = active;
  27306. };
  27307. /**
  27308. * Gets the current view matrix
  27309. * @returns a Matrix
  27310. */
  27311. Scene.prototype.getViewMatrix = function () {
  27312. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  27313. };
  27314. /**
  27315. * Gets the current projection matrix
  27316. * @returns a Matrix
  27317. */
  27318. Scene.prototype.getProjectionMatrix = function () {
  27319. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  27320. };
  27321. /**
  27322. * Gets the current transform matrix
  27323. * @returns a Matrix made of View * Projection
  27324. */
  27325. Scene.prototype.getTransformMatrix = function () {
  27326. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  27327. };
  27328. /**
  27329. * Sets the current transform matrix
  27330. * @param view defines the View matrix to use
  27331. * @param projection defines the Projection matrix to use
  27332. */
  27333. Scene.prototype.setTransformMatrix = function (view, projection) {
  27334. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  27335. return;
  27336. }
  27337. this._viewUpdateFlag = view.updateFlag;
  27338. this._projectionUpdateFlag = projection.updateFlag;
  27339. this._viewMatrix = view;
  27340. this._projectionMatrix = projection;
  27341. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  27342. // Update frustum
  27343. if (!this._frustumPlanes) {
  27344. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  27345. }
  27346. else {
  27347. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  27348. }
  27349. if (this.activeCamera && this.activeCamera._alternateCamera) {
  27350. var otherCamera = this.activeCamera._alternateCamera;
  27351. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  27352. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  27353. }
  27354. if (this._sceneUbo.useUbo) {
  27355. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  27356. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  27357. this._sceneUbo.update();
  27358. }
  27359. };
  27360. /** @hidden */
  27361. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  27362. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  27363. return;
  27364. }
  27365. this._alternateViewUpdateFlag = view.updateFlag;
  27366. this._alternateProjectionUpdateFlag = projection.updateFlag;
  27367. this._alternateViewMatrix = view;
  27368. this._alternateProjectionMatrix = projection;
  27369. if (!this._alternateTransformMatrix) {
  27370. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  27371. }
  27372. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  27373. if (!this._alternateSceneUbo) {
  27374. this._createAlternateUbo();
  27375. }
  27376. if (this._alternateSceneUbo.useUbo) {
  27377. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  27378. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  27379. this._alternateSceneUbo.update();
  27380. }
  27381. };
  27382. /**
  27383. * Gets the uniform buffer used to store scene data
  27384. * @returns a UniformBuffer
  27385. */
  27386. Scene.prototype.getSceneUniformBuffer = function () {
  27387. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  27388. };
  27389. /**
  27390. * Gets an unique (relatively to the current scene) Id
  27391. * @returns an unique number for the scene
  27392. */
  27393. Scene.prototype.getUniqueId = function () {
  27394. var result = Scene._uniqueIdCounter;
  27395. Scene._uniqueIdCounter++;
  27396. return result;
  27397. };
  27398. /**
  27399. * Add a mesh to the list of scene's meshes
  27400. * @param newMesh defines the mesh to add
  27401. * @param recursive if all child meshes should also be added to the scene
  27402. */
  27403. Scene.prototype.addMesh = function (newMesh, recursive) {
  27404. var _this = this;
  27405. if (recursive === void 0) { recursive = false; }
  27406. this.meshes.push(newMesh);
  27407. //notify the collision coordinator
  27408. if (this.collisionCoordinator) {
  27409. this.collisionCoordinator.onMeshAdded(newMesh);
  27410. }
  27411. newMesh._resyncLightSources();
  27412. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  27413. if (recursive) {
  27414. newMesh.getChildMeshes().forEach(function (m) {
  27415. _this.addMesh(m);
  27416. });
  27417. }
  27418. };
  27419. /**
  27420. * Remove a mesh for the list of scene's meshes
  27421. * @param toRemove defines the mesh to remove
  27422. * @param recursive if all child meshes should also be removed from the scene
  27423. * @returns the index where the mesh was in the mesh list
  27424. */
  27425. Scene.prototype.removeMesh = function (toRemove, recursive) {
  27426. var _this = this;
  27427. if (recursive === void 0) { recursive = false; }
  27428. var index = this.meshes.indexOf(toRemove);
  27429. if (index !== -1) {
  27430. // Remove from the scene if mesh found
  27431. this.meshes.splice(index, 1);
  27432. }
  27433. this.onMeshRemovedObservable.notifyObservers(toRemove);
  27434. if (recursive) {
  27435. toRemove.getChildMeshes().forEach(function (m) {
  27436. _this.removeMesh(m);
  27437. });
  27438. }
  27439. return index;
  27440. };
  27441. /**
  27442. * Add a transform node to the list of scene's transform nodes
  27443. * @param newTransformNode defines the transform node to add
  27444. */
  27445. Scene.prototype.addTransformNode = function (newTransformNode) {
  27446. this.transformNodes.push(newTransformNode);
  27447. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  27448. };
  27449. /**
  27450. * Remove a transform node for the list of scene's transform nodes
  27451. * @param toRemove defines the transform node to remove
  27452. * @returns the index where the transform node was in the transform node list
  27453. */
  27454. Scene.prototype.removeTransformNode = function (toRemove) {
  27455. var index = this.transformNodes.indexOf(toRemove);
  27456. if (index !== -1) {
  27457. // Remove from the scene if found
  27458. this.transformNodes.splice(index, 1);
  27459. }
  27460. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  27461. return index;
  27462. };
  27463. /**
  27464. * Remove a skeleton for the list of scene's skeletons
  27465. * @param toRemove defines the skeleton to remove
  27466. * @returns the index where the skeleton was in the skeleton list
  27467. */
  27468. Scene.prototype.removeSkeleton = function (toRemove) {
  27469. var index = this.skeletons.indexOf(toRemove);
  27470. if (index !== -1) {
  27471. // Remove from the scene if found
  27472. this.skeletons.splice(index, 1);
  27473. }
  27474. return index;
  27475. };
  27476. /**
  27477. * Remove a morph target for the list of scene's morph targets
  27478. * @param toRemove defines the morph target to remove
  27479. * @returns the index where the morph target was in the morph target list
  27480. */
  27481. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  27482. var index = this.morphTargetManagers.indexOf(toRemove);
  27483. if (index !== -1) {
  27484. // Remove from the scene if found
  27485. this.morphTargetManagers.splice(index, 1);
  27486. }
  27487. return index;
  27488. };
  27489. /**
  27490. * Remove a light for the list of scene's lights
  27491. * @param toRemove defines the light to remove
  27492. * @returns the index where the light was in the light list
  27493. */
  27494. Scene.prototype.removeLight = function (toRemove) {
  27495. var index = this.lights.indexOf(toRemove);
  27496. if (index !== -1) {
  27497. // Remove from meshes
  27498. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27499. var mesh = _a[_i];
  27500. mesh._removeLightSource(toRemove);
  27501. }
  27502. // Remove from the scene if mesh found
  27503. this.lights.splice(index, 1);
  27504. this.sortLightsByPriority();
  27505. }
  27506. this.onLightRemovedObservable.notifyObservers(toRemove);
  27507. return index;
  27508. };
  27509. /**
  27510. * Remove a camera for the list of scene's cameras
  27511. * @param toRemove defines the camera to remove
  27512. * @returns the index where the camera was in the camera list
  27513. */
  27514. Scene.prototype.removeCamera = function (toRemove) {
  27515. var index = this.cameras.indexOf(toRemove);
  27516. if (index !== -1) {
  27517. // Remove from the scene if mesh found
  27518. this.cameras.splice(index, 1);
  27519. }
  27520. // Remove from activeCameras
  27521. var index2 = this.activeCameras.indexOf(toRemove);
  27522. if (index2 !== -1) {
  27523. // Remove from the scene if mesh found
  27524. this.activeCameras.splice(index2, 1);
  27525. }
  27526. // Reset the activeCamera
  27527. if (this.activeCamera === toRemove) {
  27528. if (this.cameras.length > 0) {
  27529. this.activeCamera = this.cameras[0];
  27530. }
  27531. else {
  27532. this.activeCamera = null;
  27533. }
  27534. }
  27535. this.onCameraRemovedObservable.notifyObservers(toRemove);
  27536. return index;
  27537. };
  27538. /**
  27539. * Remove a particle system for the list of scene's particle systems
  27540. * @param toRemove defines the particle system to remove
  27541. * @returns the index where the particle system was in the particle system list
  27542. */
  27543. Scene.prototype.removeParticleSystem = function (toRemove) {
  27544. var index = this.particleSystems.indexOf(toRemove);
  27545. if (index !== -1) {
  27546. this.particleSystems.splice(index, 1);
  27547. }
  27548. return index;
  27549. };
  27550. /**
  27551. * Remove a animation for the list of scene's animations
  27552. * @param toRemove defines the animation to remove
  27553. * @returns the index where the animation was in the animation list
  27554. */
  27555. Scene.prototype.removeAnimation = function (toRemove) {
  27556. var index = this.animations.indexOf(toRemove);
  27557. if (index !== -1) {
  27558. this.animations.splice(index, 1);
  27559. }
  27560. return index;
  27561. };
  27562. /**
  27563. * Removes the given animation group from this scene.
  27564. * @param toRemove The animation group to remove
  27565. * @returns The index of the removed animation group
  27566. */
  27567. Scene.prototype.removeAnimationGroup = function (toRemove) {
  27568. var index = this.animationGroups.indexOf(toRemove);
  27569. if (index !== -1) {
  27570. this.animationGroups.splice(index, 1);
  27571. }
  27572. return index;
  27573. };
  27574. /**
  27575. * Removes the given multi-material from this scene.
  27576. * @param toRemove The multi-material to remove
  27577. * @returns The index of the removed multi-material
  27578. */
  27579. Scene.prototype.removeMultiMaterial = function (toRemove) {
  27580. var index = this.multiMaterials.indexOf(toRemove);
  27581. if (index !== -1) {
  27582. this.multiMaterials.splice(index, 1);
  27583. }
  27584. return index;
  27585. };
  27586. /**
  27587. * Removes the given material from this scene.
  27588. * @param toRemove The material to remove
  27589. * @returns The index of the removed material
  27590. */
  27591. Scene.prototype.removeMaterial = function (toRemove) {
  27592. var index = this.materials.indexOf(toRemove);
  27593. if (index !== -1) {
  27594. this.materials.splice(index, 1);
  27595. }
  27596. this.onMaterialRemovedObservable.notifyObservers(toRemove);
  27597. return index;
  27598. };
  27599. /**
  27600. * Removes the given action manager from this scene.
  27601. * @param toRemove The action manager to remove
  27602. * @returns The index of the removed action manager
  27603. */
  27604. Scene.prototype.removeActionManager = function (toRemove) {
  27605. var index = this.actionManagers.indexOf(toRemove);
  27606. if (index !== -1) {
  27607. this.actionManagers.splice(index, 1);
  27608. }
  27609. return index;
  27610. };
  27611. /**
  27612. * Removes the given texture from this scene.
  27613. * @param toRemove The texture to remove
  27614. * @returns The index of the removed texture
  27615. */
  27616. Scene.prototype.removeTexture = function (toRemove) {
  27617. var index = this.textures.indexOf(toRemove);
  27618. if (index !== -1) {
  27619. this.textures.splice(index, 1);
  27620. }
  27621. this.onTextureRemovedObservable.notifyObservers(toRemove);
  27622. return index;
  27623. };
  27624. /**
  27625. * Adds the given light to this scene
  27626. * @param newLight The light to add
  27627. */
  27628. Scene.prototype.addLight = function (newLight) {
  27629. this.lights.push(newLight);
  27630. this.sortLightsByPriority();
  27631. // Add light to all meshes (To support if the light is removed and then readded)
  27632. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27633. var mesh = _a[_i];
  27634. if (mesh._lightSources.indexOf(newLight) === -1) {
  27635. mesh._lightSources.push(newLight);
  27636. mesh._resyncLightSources();
  27637. }
  27638. }
  27639. this.onNewLightAddedObservable.notifyObservers(newLight);
  27640. };
  27641. /**
  27642. * Sorts the list list based on light priorities
  27643. */
  27644. Scene.prototype.sortLightsByPriority = function () {
  27645. if (this.requireLightSorting) {
  27646. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  27647. }
  27648. };
  27649. /**
  27650. * Adds the given camera to this scene
  27651. * @param newCamera The camera to add
  27652. */
  27653. Scene.prototype.addCamera = function (newCamera) {
  27654. this.cameras.push(newCamera);
  27655. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  27656. };
  27657. /**
  27658. * Adds the given skeleton to this scene
  27659. * @param newSkeleton The skeleton to add
  27660. */
  27661. Scene.prototype.addSkeleton = function (newSkeleton) {
  27662. this.skeletons.push(newSkeleton);
  27663. };
  27664. /**
  27665. * Adds the given particle system to this scene
  27666. * @param newParticleSystem The particle system to add
  27667. */
  27668. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  27669. this.particleSystems.push(newParticleSystem);
  27670. };
  27671. /**
  27672. * Adds the given animation to this scene
  27673. * @param newAnimation The animation to add
  27674. */
  27675. Scene.prototype.addAnimation = function (newAnimation) {
  27676. this.animations.push(newAnimation);
  27677. };
  27678. /**
  27679. * Adds the given animation group to this scene.
  27680. * @param newAnimationGroup The animation group to add
  27681. */
  27682. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  27683. this.animationGroups.push(newAnimationGroup);
  27684. };
  27685. /**
  27686. * Adds the given multi-material to this scene
  27687. * @param newMultiMaterial The multi-material to add
  27688. */
  27689. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  27690. this.multiMaterials.push(newMultiMaterial);
  27691. };
  27692. /**
  27693. * Adds the given material to this scene
  27694. * @param newMaterial The material to add
  27695. */
  27696. Scene.prototype.addMaterial = function (newMaterial) {
  27697. this.materials.push(newMaterial);
  27698. this.onNewMaterialAddedObservable.notifyObservers(newMaterial);
  27699. };
  27700. /**
  27701. * Adds the given morph target to this scene
  27702. * @param newMorphTargetManager The morph target to add
  27703. */
  27704. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  27705. this.morphTargetManagers.push(newMorphTargetManager);
  27706. };
  27707. /**
  27708. * Adds the given geometry to this scene
  27709. * @param newGeometry The geometry to add
  27710. */
  27711. Scene.prototype.addGeometry = function (newGeometry) {
  27712. this.geometries.push(newGeometry);
  27713. };
  27714. /**
  27715. * Adds the given action manager to this scene
  27716. * @param newActionManager The action manager to add
  27717. */
  27718. Scene.prototype.addActionManager = function (newActionManager) {
  27719. this.actionManagers.push(newActionManager);
  27720. };
  27721. /**
  27722. * Adds the given texture to this scene.
  27723. * @param newTexture The texture to add
  27724. */
  27725. Scene.prototype.addTexture = function (newTexture) {
  27726. this.textures.push(newTexture);
  27727. this.onNewTextureAddedObservable.notifyObservers(newTexture);
  27728. };
  27729. /**
  27730. * Switch active camera
  27731. * @param newCamera defines the new active camera
  27732. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  27733. */
  27734. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  27735. if (attachControl === void 0) { attachControl = true; }
  27736. var canvas = this._engine.getRenderingCanvas();
  27737. if (!canvas) {
  27738. return;
  27739. }
  27740. if (this.activeCamera) {
  27741. this.activeCamera.detachControl(canvas);
  27742. }
  27743. this.activeCamera = newCamera;
  27744. if (attachControl) {
  27745. newCamera.attachControl(canvas);
  27746. }
  27747. };
  27748. /**
  27749. * sets the active camera of the scene using its ID
  27750. * @param id defines the camera's ID
  27751. * @return the new active camera or null if none found.
  27752. */
  27753. Scene.prototype.setActiveCameraByID = function (id) {
  27754. var camera = this.getCameraByID(id);
  27755. if (camera) {
  27756. this.activeCamera = camera;
  27757. return camera;
  27758. }
  27759. return null;
  27760. };
  27761. /**
  27762. * sets the active camera of the scene using its name
  27763. * @param name defines the camera's name
  27764. * @returns the new active camera or null if none found.
  27765. */
  27766. Scene.prototype.setActiveCameraByName = function (name) {
  27767. var camera = this.getCameraByName(name);
  27768. if (camera) {
  27769. this.activeCamera = camera;
  27770. return camera;
  27771. }
  27772. return null;
  27773. };
  27774. /**
  27775. * get an animation group using its name
  27776. * @param name defines the material's name
  27777. * @return the animation group or null if none found.
  27778. */
  27779. Scene.prototype.getAnimationGroupByName = function (name) {
  27780. for (var index = 0; index < this.animationGroups.length; index++) {
  27781. if (this.animationGroups[index].name === name) {
  27782. return this.animationGroups[index];
  27783. }
  27784. }
  27785. return null;
  27786. };
  27787. /**
  27788. * get a material using its id
  27789. * @param id defines the material's ID
  27790. * @return the material or null if none found.
  27791. */
  27792. Scene.prototype.getMaterialByID = function (id) {
  27793. for (var index = 0; index < this.materials.length; index++) {
  27794. if (this.materials[index].id === id) {
  27795. return this.materials[index];
  27796. }
  27797. }
  27798. return null;
  27799. };
  27800. /**
  27801. * Gets a material using its name
  27802. * @param name defines the material's name
  27803. * @return the material or null if none found.
  27804. */
  27805. Scene.prototype.getMaterialByName = function (name) {
  27806. for (var index = 0; index < this.materials.length; index++) {
  27807. if (this.materials[index].name === name) {
  27808. return this.materials[index];
  27809. }
  27810. }
  27811. return null;
  27812. };
  27813. /**
  27814. * Gets a camera using its id
  27815. * @param id defines the id to look for
  27816. * @returns the camera or null if not found
  27817. */
  27818. Scene.prototype.getCameraByID = function (id) {
  27819. for (var index = 0; index < this.cameras.length; index++) {
  27820. if (this.cameras[index].id === id) {
  27821. return this.cameras[index];
  27822. }
  27823. }
  27824. return null;
  27825. };
  27826. /**
  27827. * Gets a camera using its unique id
  27828. * @param uniqueId defines the unique id to look for
  27829. * @returns the camera or null if not found
  27830. */
  27831. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  27832. for (var index = 0; index < this.cameras.length; index++) {
  27833. if (this.cameras[index].uniqueId === uniqueId) {
  27834. return this.cameras[index];
  27835. }
  27836. }
  27837. return null;
  27838. };
  27839. /**
  27840. * Gets a camera using its name
  27841. * @param name defines the camera's name
  27842. * @return the camera or null if none found.
  27843. */
  27844. Scene.prototype.getCameraByName = function (name) {
  27845. for (var index = 0; index < this.cameras.length; index++) {
  27846. if (this.cameras[index].name === name) {
  27847. return this.cameras[index];
  27848. }
  27849. }
  27850. return null;
  27851. };
  27852. /**
  27853. * Gets a bone using its id
  27854. * @param id defines the bone's id
  27855. * @return the bone or null if not found
  27856. */
  27857. Scene.prototype.getBoneByID = function (id) {
  27858. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27859. var skeleton = this.skeletons[skeletonIndex];
  27860. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27861. if (skeleton.bones[boneIndex].id === id) {
  27862. return skeleton.bones[boneIndex];
  27863. }
  27864. }
  27865. }
  27866. return null;
  27867. };
  27868. /**
  27869. * Gets a bone using its id
  27870. * @param name defines the bone's name
  27871. * @return the bone or null if not found
  27872. */
  27873. Scene.prototype.getBoneByName = function (name) {
  27874. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27875. var skeleton = this.skeletons[skeletonIndex];
  27876. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27877. if (skeleton.bones[boneIndex].name === name) {
  27878. return skeleton.bones[boneIndex];
  27879. }
  27880. }
  27881. }
  27882. return null;
  27883. };
  27884. /**
  27885. * Gets a light node using its name
  27886. * @param name defines the the light's name
  27887. * @return the light or null if none found.
  27888. */
  27889. Scene.prototype.getLightByName = function (name) {
  27890. for (var index = 0; index < this.lights.length; index++) {
  27891. if (this.lights[index].name === name) {
  27892. return this.lights[index];
  27893. }
  27894. }
  27895. return null;
  27896. };
  27897. /**
  27898. * Gets a light node using its id
  27899. * @param id defines the light's id
  27900. * @return the light or null if none found.
  27901. */
  27902. Scene.prototype.getLightByID = function (id) {
  27903. for (var index = 0; index < this.lights.length; index++) {
  27904. if (this.lights[index].id === id) {
  27905. return this.lights[index];
  27906. }
  27907. }
  27908. return null;
  27909. };
  27910. /**
  27911. * Gets a light node using its scene-generated unique ID
  27912. * @param uniqueId defines the light's unique id
  27913. * @return the light or null if none found.
  27914. */
  27915. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  27916. for (var index = 0; index < this.lights.length; index++) {
  27917. if (this.lights[index].uniqueId === uniqueId) {
  27918. return this.lights[index];
  27919. }
  27920. }
  27921. return null;
  27922. };
  27923. /**
  27924. * Gets a particle system by id
  27925. * @param id defines the particle system id
  27926. * @return the corresponding system or null if none found
  27927. */
  27928. Scene.prototype.getParticleSystemByID = function (id) {
  27929. for (var index = 0; index < this.particleSystems.length; index++) {
  27930. if (this.particleSystems[index].id === id) {
  27931. return this.particleSystems[index];
  27932. }
  27933. }
  27934. return null;
  27935. };
  27936. /**
  27937. * Gets a geometry using its ID
  27938. * @param id defines the geometry's id
  27939. * @return the geometry or null if none found.
  27940. */
  27941. Scene.prototype.getGeometryByID = function (id) {
  27942. for (var index = 0; index < this.geometries.length; index++) {
  27943. if (this.geometries[index].id === id) {
  27944. return this.geometries[index];
  27945. }
  27946. }
  27947. return null;
  27948. };
  27949. /**
  27950. * Add a new geometry to this scene
  27951. * @param geometry defines the geometry to be added to the scene.
  27952. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  27953. * @return a boolean defining if the geometry was added or not
  27954. */
  27955. Scene.prototype.pushGeometry = function (geometry, force) {
  27956. if (!force && this.getGeometryByID(geometry.id)) {
  27957. return false;
  27958. }
  27959. this.geometries.push(geometry);
  27960. //notify the collision coordinator
  27961. if (this.collisionCoordinator) {
  27962. this.collisionCoordinator.onGeometryAdded(geometry);
  27963. }
  27964. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27965. return true;
  27966. };
  27967. /**
  27968. * Removes an existing geometry
  27969. * @param geometry defines the geometry to be removed from the scene
  27970. * @return a boolean defining if the geometry was removed or not
  27971. */
  27972. Scene.prototype.removeGeometry = function (geometry) {
  27973. var index = this.geometries.indexOf(geometry);
  27974. if (index > -1) {
  27975. this.geometries.splice(index, 1);
  27976. //notify the collision coordinator
  27977. if (this.collisionCoordinator) {
  27978. this.collisionCoordinator.onGeometryDeleted(geometry);
  27979. }
  27980. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27981. return true;
  27982. }
  27983. return false;
  27984. };
  27985. /**
  27986. * Gets the list of geometries attached to the scene
  27987. * @returns an array of Geometry
  27988. */
  27989. Scene.prototype.getGeometries = function () {
  27990. return this.geometries;
  27991. };
  27992. /**
  27993. * Gets the first added mesh found of a given ID
  27994. * @param id defines the id to search for
  27995. * @return the mesh found or null if not found at all
  27996. */
  27997. Scene.prototype.getMeshByID = function (id) {
  27998. for (var index = 0; index < this.meshes.length; index++) {
  27999. if (this.meshes[index].id === id) {
  28000. return this.meshes[index];
  28001. }
  28002. }
  28003. return null;
  28004. };
  28005. /**
  28006. * Gets a list of meshes using their id
  28007. * @param id defines the id to search for
  28008. * @returns a list of meshes
  28009. */
  28010. Scene.prototype.getMeshesByID = function (id) {
  28011. return this.meshes.filter(function (m) {
  28012. return m.id === id;
  28013. });
  28014. };
  28015. /**
  28016. * Gets the first added transform node found of a given ID
  28017. * @param id defines the id to search for
  28018. * @return the found transform node or null if not found at all.
  28019. */
  28020. Scene.prototype.getTransformNodeByID = function (id) {
  28021. for (var index = 0; index < this.transformNodes.length; index++) {
  28022. if (this.transformNodes[index].id === id) {
  28023. return this.transformNodes[index];
  28024. }
  28025. }
  28026. return null;
  28027. };
  28028. /**
  28029. * Gets a list of transform nodes using their id
  28030. * @param id defines the id to search for
  28031. * @returns a list of transform nodes
  28032. */
  28033. Scene.prototype.getTransformNodesByID = function (id) {
  28034. return this.transformNodes.filter(function (m) {
  28035. return m.id === id;
  28036. });
  28037. };
  28038. /**
  28039. * Gets a mesh with its auto-generated unique id
  28040. * @param uniqueId defines the unique id to search for
  28041. * @return the found mesh or null if not found at all.
  28042. */
  28043. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  28044. for (var index = 0; index < this.meshes.length; index++) {
  28045. if (this.meshes[index].uniqueId === uniqueId) {
  28046. return this.meshes[index];
  28047. }
  28048. }
  28049. return null;
  28050. };
  28051. /**
  28052. * Gets a the last added mesh using a given id
  28053. * @param id defines the id to search for
  28054. * @return the found mesh or null if not found at all.
  28055. */
  28056. Scene.prototype.getLastMeshByID = function (id) {
  28057. for (var index = this.meshes.length - 1; index >= 0; index--) {
  28058. if (this.meshes[index].id === id) {
  28059. return this.meshes[index];
  28060. }
  28061. }
  28062. return null;
  28063. };
  28064. /**
  28065. * Gets a the last added node (Mesh, Camera, Light) using a given id
  28066. * @param id defines the id to search for
  28067. * @return the found node or null if not found at all
  28068. */
  28069. Scene.prototype.getLastEntryByID = function (id) {
  28070. var index;
  28071. for (index = this.meshes.length - 1; index >= 0; index--) {
  28072. if (this.meshes[index].id === id) {
  28073. return this.meshes[index];
  28074. }
  28075. }
  28076. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  28077. if (this.transformNodes[index].id === id) {
  28078. return this.transformNodes[index];
  28079. }
  28080. }
  28081. for (index = this.cameras.length - 1; index >= 0; index--) {
  28082. if (this.cameras[index].id === id) {
  28083. return this.cameras[index];
  28084. }
  28085. }
  28086. for (index = this.lights.length - 1; index >= 0; index--) {
  28087. if (this.lights[index].id === id) {
  28088. return this.lights[index];
  28089. }
  28090. }
  28091. return null;
  28092. };
  28093. /**
  28094. * Gets a node (Mesh, Camera, Light) using a given id
  28095. * @param id defines the id to search for
  28096. * @return the found node or null if not found at all
  28097. */
  28098. Scene.prototype.getNodeByID = function (id) {
  28099. var mesh = this.getMeshByID(id);
  28100. if (mesh) {
  28101. return mesh;
  28102. }
  28103. var light = this.getLightByID(id);
  28104. if (light) {
  28105. return light;
  28106. }
  28107. var camera = this.getCameraByID(id);
  28108. if (camera) {
  28109. return camera;
  28110. }
  28111. var bone = this.getBoneByID(id);
  28112. return bone;
  28113. };
  28114. /**
  28115. * Gets a node (Mesh, Camera, Light) using a given name
  28116. * @param name defines the name to search for
  28117. * @return the found node or null if not found at all.
  28118. */
  28119. Scene.prototype.getNodeByName = function (name) {
  28120. var mesh = this.getMeshByName(name);
  28121. if (mesh) {
  28122. return mesh;
  28123. }
  28124. var light = this.getLightByName(name);
  28125. if (light) {
  28126. return light;
  28127. }
  28128. var camera = this.getCameraByName(name);
  28129. if (camera) {
  28130. return camera;
  28131. }
  28132. var bone = this.getBoneByName(name);
  28133. return bone;
  28134. };
  28135. /**
  28136. * Gets a mesh using a given name
  28137. * @param name defines the name to search for
  28138. * @return the found mesh or null if not found at all.
  28139. */
  28140. Scene.prototype.getMeshByName = function (name) {
  28141. for (var index = 0; index < this.meshes.length; index++) {
  28142. if (this.meshes[index].name === name) {
  28143. return this.meshes[index];
  28144. }
  28145. }
  28146. return null;
  28147. };
  28148. /**
  28149. * Gets a transform node using a given name
  28150. * @param name defines the name to search for
  28151. * @return the found transform node or null if not found at all.
  28152. */
  28153. Scene.prototype.getTransformNodeByName = function (name) {
  28154. for (var index = 0; index < this.transformNodes.length; index++) {
  28155. if (this.transformNodes[index].name === name) {
  28156. return this.transformNodes[index];
  28157. }
  28158. }
  28159. return null;
  28160. };
  28161. /**
  28162. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  28163. * @param id defines the id to search for
  28164. * @return the found skeleton or null if not found at all.
  28165. */
  28166. Scene.prototype.getLastSkeletonByID = function (id) {
  28167. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  28168. if (this.skeletons[index].id === id) {
  28169. return this.skeletons[index];
  28170. }
  28171. }
  28172. return null;
  28173. };
  28174. /**
  28175. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  28176. * @param id defines the id to search for
  28177. * @return the found skeleton or null if not found at all.
  28178. */
  28179. Scene.prototype.getSkeletonById = function (id) {
  28180. for (var index = 0; index < this.skeletons.length; index++) {
  28181. if (this.skeletons[index].id === id) {
  28182. return this.skeletons[index];
  28183. }
  28184. }
  28185. return null;
  28186. };
  28187. /**
  28188. * Gets a skeleton using a given name
  28189. * @param name defines the name to search for
  28190. * @return the found skeleton or null if not found at all.
  28191. */
  28192. Scene.prototype.getSkeletonByName = function (name) {
  28193. for (var index = 0; index < this.skeletons.length; index++) {
  28194. if (this.skeletons[index].name === name) {
  28195. return this.skeletons[index];
  28196. }
  28197. }
  28198. return null;
  28199. };
  28200. /**
  28201. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  28202. * @param id defines the id to search for
  28203. * @return the found morph target manager or null if not found at all.
  28204. */
  28205. Scene.prototype.getMorphTargetManagerById = function (id) {
  28206. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  28207. if (this.morphTargetManagers[index].uniqueId === id) {
  28208. return this.morphTargetManagers[index];
  28209. }
  28210. }
  28211. return null;
  28212. };
  28213. /**
  28214. * Gets a boolean indicating if the given mesh is active
  28215. * @param mesh defines the mesh to look for
  28216. * @returns true if the mesh is in the active list
  28217. */
  28218. Scene.prototype.isActiveMesh = function (mesh) {
  28219. return (this._activeMeshes.indexOf(mesh) !== -1);
  28220. };
  28221. Object.defineProperty(Scene.prototype, "uid", {
  28222. /**
  28223. * Return a unique id as a string which can serve as an identifier for the scene
  28224. */
  28225. get: function () {
  28226. if (!this._uid) {
  28227. this._uid = BABYLON.Tools.RandomId();
  28228. }
  28229. return this._uid;
  28230. },
  28231. enumerable: true,
  28232. configurable: true
  28233. });
  28234. /**
  28235. * Add an externaly attached data from its key.
  28236. * This method call will fail and return false, if such key already exists.
  28237. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  28238. * @param key the unique key that identifies the data
  28239. * @param data the data object to associate to the key for this Engine instance
  28240. * @return true if no such key were already present and the data was added successfully, false otherwise
  28241. */
  28242. Scene.prototype.addExternalData = function (key, data) {
  28243. if (!this._externalData) {
  28244. this._externalData = new BABYLON.StringDictionary();
  28245. }
  28246. return this._externalData.add(key, data);
  28247. };
  28248. /**
  28249. * Get an externaly attached data from its key
  28250. * @param key the unique key that identifies the data
  28251. * @return the associated data, if present (can be null), or undefined if not present
  28252. */
  28253. Scene.prototype.getExternalData = function (key) {
  28254. if (!this._externalData) {
  28255. return null;
  28256. }
  28257. return this._externalData.get(key);
  28258. };
  28259. /**
  28260. * Get an externaly attached data from its key, create it using a factory if it's not already present
  28261. * @param key the unique key that identifies the data
  28262. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  28263. * @return the associated data, can be null if the factory returned null.
  28264. */
  28265. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  28266. if (!this._externalData) {
  28267. this._externalData = new BABYLON.StringDictionary();
  28268. }
  28269. return this._externalData.getOrAddWithFactory(key, factory);
  28270. };
  28271. /**
  28272. * Remove an externaly attached data from the Engine instance
  28273. * @param key the unique key that identifies the data
  28274. * @return true if the data was successfully removed, false if it doesn't exist
  28275. */
  28276. Scene.prototype.removeExternalData = function (key) {
  28277. return this._externalData.remove(key);
  28278. };
  28279. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  28280. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  28281. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  28282. var step = _a[_i];
  28283. step.action(mesh, subMesh);
  28284. }
  28285. var material = subMesh.getMaterial();
  28286. if (material !== null && material !== undefined) {
  28287. // Render targets
  28288. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  28289. if (this._processedMaterials.indexOf(material) === -1) {
  28290. this._processedMaterials.push(material);
  28291. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  28292. }
  28293. }
  28294. // Dispatch
  28295. this._activeIndices.addCount(subMesh.indexCount, false);
  28296. this._renderingManager.dispatch(subMesh, mesh, material);
  28297. }
  28298. }
  28299. };
  28300. /**
  28301. * Clear the processed materials smart array preventing retention point in material dispose.
  28302. */
  28303. Scene.prototype.freeProcessedMaterials = function () {
  28304. this._processedMaterials.dispose();
  28305. };
  28306. /**
  28307. * Clear the active meshes smart array preventing retention point in mesh dispose.
  28308. */
  28309. Scene.prototype.freeActiveMeshes = function () {
  28310. this._activeMeshes.dispose();
  28311. if (this.activeCamera && this.activeCamera._activeMeshes) {
  28312. this.activeCamera._activeMeshes.dispose();
  28313. }
  28314. if (this.activeCameras) {
  28315. for (var i = 0; i < this.activeCameras.length; i++) {
  28316. var activeCamera = this.activeCameras[i];
  28317. if (activeCamera && activeCamera._activeMeshes) {
  28318. activeCamera._activeMeshes.dispose();
  28319. }
  28320. }
  28321. }
  28322. };
  28323. /**
  28324. * Clear the info related to rendering groups preventing retention points during dispose.
  28325. */
  28326. Scene.prototype.freeRenderingGroups = function () {
  28327. if (this._renderingManager) {
  28328. this._renderingManager.freeRenderingGroups();
  28329. }
  28330. if (this.textures) {
  28331. for (var i = 0; i < this.textures.length; i++) {
  28332. var texture = this.textures[i];
  28333. if (texture && texture.renderList) {
  28334. texture.freeRenderingGroups();
  28335. }
  28336. }
  28337. }
  28338. };
  28339. /** @hidden */
  28340. Scene.prototype._isInIntermediateRendering = function () {
  28341. return this._intermediateRendering;
  28342. };
  28343. /**
  28344. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  28345. * @returns the current scene
  28346. */
  28347. Scene.prototype.freezeActiveMeshes = function () {
  28348. if (!this.activeCamera) {
  28349. return this;
  28350. }
  28351. if (!this._frustumPlanes) {
  28352. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  28353. }
  28354. this._evaluateActiveMeshes();
  28355. this._activeMeshesFrozen = true;
  28356. return this;
  28357. };
  28358. /**
  28359. * Use this function to restart evaluating active meshes on every frame
  28360. * @returns the current scene
  28361. */
  28362. Scene.prototype.unfreezeActiveMeshes = function () {
  28363. this._activeMeshesFrozen = false;
  28364. return this;
  28365. };
  28366. Scene.prototype._evaluateActiveMeshes = function () {
  28367. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  28368. return;
  28369. }
  28370. if (!this.activeCamera) {
  28371. return;
  28372. }
  28373. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  28374. this.activeCamera._activeMeshes.reset();
  28375. this._activeMeshes.reset();
  28376. this._renderingManager.reset();
  28377. this._processedMaterials.reset();
  28378. this._activeParticleSystems.reset();
  28379. this._activeSkeletons.reset();
  28380. this._softwareSkinnedMeshes.reset();
  28381. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  28382. var step = _a[_i];
  28383. step.action();
  28384. }
  28385. // Determine mesh candidates
  28386. var meshes = this.getActiveMeshCandidates();
  28387. // Check each mesh
  28388. var len = meshes.length;
  28389. for (var i = 0; i < len; i++) {
  28390. var mesh = meshes.data[i];
  28391. if (mesh.isBlocked) {
  28392. continue;
  28393. }
  28394. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  28395. if (!mesh.isReady() || !mesh.isEnabled()) {
  28396. continue;
  28397. }
  28398. mesh.computeWorldMatrix();
  28399. // Intersections
  28400. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  28401. this._meshesForIntersections.pushNoDuplicate(mesh);
  28402. }
  28403. // Switch to current LOD
  28404. var meshLOD = mesh.getLOD(this.activeCamera);
  28405. if (meshLOD === undefined || meshLOD === null) {
  28406. continue;
  28407. }
  28408. mesh._preActivate();
  28409. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  28410. this._activeMeshes.push(mesh);
  28411. this.activeCamera._activeMeshes.push(mesh);
  28412. mesh._activate(this._renderId);
  28413. if (meshLOD !== mesh) {
  28414. meshLOD._activate(this._renderId);
  28415. }
  28416. this._activeMesh(mesh, meshLOD);
  28417. }
  28418. }
  28419. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  28420. // Particle systems
  28421. if (this.particlesEnabled) {
  28422. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  28423. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  28424. var particleSystem = this.particleSystems[particleIndex];
  28425. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  28426. continue;
  28427. }
  28428. var emitter = particleSystem.emitter;
  28429. if (!emitter.position || emitter.isEnabled()) {
  28430. this._activeParticleSystems.push(particleSystem);
  28431. particleSystem.animate();
  28432. this._renderingManager.dispatchParticles(particleSystem);
  28433. }
  28434. }
  28435. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  28436. }
  28437. };
  28438. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  28439. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  28440. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  28441. mesh.skeleton.prepare();
  28442. }
  28443. if (!mesh.computeBonesUsingShaders) {
  28444. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  28445. }
  28446. }
  28447. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  28448. var step = _a[_i];
  28449. step.action(sourceMesh, mesh);
  28450. }
  28451. if (mesh !== undefined && mesh !== null
  28452. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  28453. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  28454. var len = subMeshes.length;
  28455. for (var i = 0; i < len; i++) {
  28456. var subMesh = subMeshes.data[i];
  28457. this._evaluateSubMesh(subMesh, mesh);
  28458. }
  28459. }
  28460. };
  28461. /**
  28462. * Update the transform matrix to update from the current active camera
  28463. * @param force defines a boolean used to force the update even if cache is up to date
  28464. */
  28465. Scene.prototype.updateTransformMatrix = function (force) {
  28466. if (!this.activeCamera) {
  28467. return;
  28468. }
  28469. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  28470. };
  28471. /**
  28472. * 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)
  28473. * @param alternateCamera defines the camera to use
  28474. */
  28475. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  28476. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  28477. };
  28478. Scene.prototype._renderForCamera = function (camera, rigParent) {
  28479. if (camera && camera._skipRendering) {
  28480. return;
  28481. }
  28482. var engine = this._engine;
  28483. this.activeCamera = camera;
  28484. if (!this.activeCamera)
  28485. throw new Error("Active camera not set");
  28486. // Viewport
  28487. engine.setViewport(this.activeCamera.viewport);
  28488. // Camera
  28489. this.resetCachedMaterial();
  28490. this._renderId++;
  28491. this.updateTransformMatrix();
  28492. if (camera._alternateCamera) {
  28493. this.updateAlternateTransformMatrix(camera._alternateCamera);
  28494. this._alternateRendering = true;
  28495. }
  28496. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  28497. // Meshes
  28498. this._evaluateActiveMeshes();
  28499. // Software skinning
  28500. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  28501. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  28502. mesh.applySkeleton(mesh.skeleton);
  28503. }
  28504. // Render targets
  28505. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28506. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  28507. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  28508. }
  28509. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  28510. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  28511. }
  28512. // Collects render targets from external components.
  28513. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  28514. var step = _a[_i];
  28515. step.action(this._renderTargets);
  28516. }
  28517. if (this.renderTargetsEnabled) {
  28518. this._intermediateRendering = true;
  28519. if (this._renderTargets.length > 0) {
  28520. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28521. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  28522. var renderTarget = this._renderTargets.data[renderIndex];
  28523. if (renderTarget._shouldRender()) {
  28524. this._renderId++;
  28525. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  28526. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  28527. }
  28528. }
  28529. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28530. this._renderId++;
  28531. }
  28532. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  28533. var step = _c[_b];
  28534. step.action(this.activeCamera);
  28535. }
  28536. this._intermediateRendering = false;
  28537. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  28538. }
  28539. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28540. // Prepare Frame
  28541. if (this.postProcessManager) {
  28542. this.postProcessManager._prepareFrame();
  28543. }
  28544. // Before Camera Draw
  28545. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  28546. var step = _e[_d];
  28547. step.action(this.activeCamera);
  28548. }
  28549. // Render
  28550. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  28551. this._renderingManager.render(null, null, true, true);
  28552. this.onAfterDrawPhaseObservable.notifyObservers(this);
  28553. // After Camera Draw
  28554. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  28555. var step = _g[_f];
  28556. step.action(this.activeCamera);
  28557. }
  28558. // Finalize frame
  28559. if (this.postProcessManager) {
  28560. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  28561. }
  28562. // Reset some special arrays
  28563. this._renderTargets.reset();
  28564. this._alternateRendering = false;
  28565. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  28566. };
  28567. Scene.prototype._processSubCameras = function (camera) {
  28568. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  28569. this._renderForCamera(camera);
  28570. return;
  28571. }
  28572. // rig cameras
  28573. for (var index = 0; index < camera._rigCameras.length; index++) {
  28574. this._renderForCamera(camera._rigCameras[index], camera);
  28575. }
  28576. this.activeCamera = camera;
  28577. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  28578. };
  28579. Scene.prototype._checkIntersections = function () {
  28580. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  28581. var sourceMesh = this._meshesForIntersections.data[index];
  28582. if (!sourceMesh.actionManager) {
  28583. continue;
  28584. }
  28585. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  28586. var action = sourceMesh.actionManager.actions[actionIndex];
  28587. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28588. var parameters = action.getTriggerParameter();
  28589. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  28590. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  28591. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  28592. if (areIntersecting && currentIntersectionInProgress === -1) {
  28593. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  28594. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  28595. sourceMesh._intersectionsInProgress.push(otherMesh);
  28596. }
  28597. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28598. sourceMesh._intersectionsInProgress.push(otherMesh);
  28599. }
  28600. }
  28601. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  28602. //They intersected, and now they don't.
  28603. //is this trigger an exit trigger? execute an event.
  28604. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28605. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  28606. }
  28607. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  28608. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  28609. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  28610. return otherMesh === parameterMesh;
  28611. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28612. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  28613. }
  28614. }
  28615. }
  28616. }
  28617. }
  28618. };
  28619. /** @hidden */
  28620. Scene.prototype._advancePhysicsEngineStep = function (step) {
  28621. // Do nothing. Code will be replaced if physics engine component is referenced
  28622. };
  28623. /**
  28624. * Render the scene
  28625. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  28626. */
  28627. Scene.prototype.render = function (updateCameras) {
  28628. if (updateCameras === void 0) { updateCameras = true; }
  28629. if (this.isDisposed) {
  28630. return;
  28631. }
  28632. this._frameId++;
  28633. // Register components that have been associated lately to the scene.
  28634. this._registerTransientComponents();
  28635. this._activeParticles.fetchNewFrame();
  28636. this._totalVertices.fetchNewFrame();
  28637. this._activeIndices.fetchNewFrame();
  28638. this._activeBones.fetchNewFrame();
  28639. this._meshesForIntersections.reset();
  28640. this.resetCachedMaterial();
  28641. this.onBeforeAnimationsObservable.notifyObservers(this);
  28642. // Actions
  28643. if (this.actionManager) {
  28644. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  28645. }
  28646. if (this._engine.isDeterministicLockStep()) {
  28647. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  28648. var defaultFPS = (60.0 / 1000.0);
  28649. var defaultFrameTime = this.getDeterministicFrameTime();
  28650. var stepsTaken = 0;
  28651. var maxSubSteps = this._engine.getLockstepMaxSteps();
  28652. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  28653. internalSteps = Math.min(internalSteps, maxSubSteps);
  28654. do {
  28655. this.onBeforeStepObservable.notifyObservers(this);
  28656. // Animations
  28657. this._animationRatio = defaultFrameTime * defaultFPS;
  28658. this._animate();
  28659. this.onAfterAnimationsObservable.notifyObservers(this);
  28660. // Physics
  28661. this._advancePhysicsEngineStep(defaultFrameTime);
  28662. this.onAfterStepObservable.notifyObservers(this);
  28663. this._currentStepId++;
  28664. stepsTaken++;
  28665. deltaTime -= defaultFrameTime;
  28666. } while (deltaTime > 0 && stepsTaken < internalSteps);
  28667. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  28668. }
  28669. else {
  28670. // Animations
  28671. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  28672. this._animationRatio = deltaTime * (60.0 / 1000.0);
  28673. this._animate();
  28674. this.onAfterAnimationsObservable.notifyObservers(this);
  28675. // Physics
  28676. this._advancePhysicsEngineStep(deltaTime);
  28677. }
  28678. // Before camera update steps
  28679. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  28680. var step = _a[_i];
  28681. step.action();
  28682. }
  28683. // Update Cameras
  28684. if (updateCameras) {
  28685. if (this.activeCameras.length > 0) {
  28686. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28687. var camera = this.activeCameras[cameraIndex];
  28688. camera.update();
  28689. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28690. // rig cameras
  28691. for (var index = 0; index < camera._rigCameras.length; index++) {
  28692. camera._rigCameras[index].update();
  28693. }
  28694. }
  28695. }
  28696. }
  28697. else if (this.activeCamera) {
  28698. this.activeCamera.update();
  28699. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28700. // rig cameras
  28701. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  28702. this.activeCamera._rigCameras[index].update();
  28703. }
  28704. }
  28705. }
  28706. }
  28707. // Before render
  28708. this.onBeforeRenderObservable.notifyObservers(this);
  28709. // Customs render targets
  28710. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28711. var engine = this.getEngine();
  28712. var currentActiveCamera = this.activeCamera;
  28713. if (this.renderTargetsEnabled) {
  28714. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28715. this._intermediateRendering = true;
  28716. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  28717. var renderTarget = this.customRenderTargets[customIndex];
  28718. if (renderTarget._shouldRender()) {
  28719. this._renderId++;
  28720. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  28721. if (!this.activeCamera)
  28722. throw new Error("Active camera not set");
  28723. // Viewport
  28724. engine.setViewport(this.activeCamera.viewport);
  28725. // Camera
  28726. this.updateTransformMatrix();
  28727. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  28728. }
  28729. }
  28730. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28731. this._intermediateRendering = false;
  28732. this._renderId++;
  28733. }
  28734. // Restore back buffer
  28735. if (this.customRenderTargets.length > 0) {
  28736. engine.restoreDefaultFramebuffer();
  28737. }
  28738. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28739. this.activeCamera = currentActiveCamera;
  28740. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  28741. var step = _c[_b];
  28742. step.action();
  28743. }
  28744. // Clear
  28745. if (this.autoClearDepthAndStencil || this.autoClear) {
  28746. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  28747. }
  28748. // Collects render targets from external components.
  28749. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  28750. var step = _e[_d];
  28751. step.action(this._renderTargets);
  28752. }
  28753. // Multi-cameras?
  28754. if (this.activeCameras.length > 0) {
  28755. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28756. if (cameraIndex > 0) {
  28757. this._engine.clear(null, false, true, true);
  28758. }
  28759. this._processSubCameras(this.activeCameras[cameraIndex]);
  28760. }
  28761. }
  28762. else {
  28763. if (!this.activeCamera) {
  28764. throw new Error("No camera defined");
  28765. }
  28766. this._processSubCameras(this.activeCamera);
  28767. }
  28768. // Intersection checks
  28769. this._checkIntersections();
  28770. // Executes the after render stage actions.
  28771. for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
  28772. var step = _g[_f];
  28773. step.action();
  28774. }
  28775. // After render
  28776. if (this.afterRender) {
  28777. this.afterRender();
  28778. }
  28779. this.onAfterRenderObservable.notifyObservers(this);
  28780. // Cleaning
  28781. if (this._toBeDisposed.length) {
  28782. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28783. var data = this._toBeDisposed[index];
  28784. if (data) {
  28785. data.dispose();
  28786. }
  28787. }
  28788. this._toBeDisposed = [];
  28789. }
  28790. if (this.dumpNextRenderTargets) {
  28791. this.dumpNextRenderTargets = false;
  28792. }
  28793. this._activeBones.addCount(0, true);
  28794. this._activeIndices.addCount(0, true);
  28795. this._activeParticles.addCount(0, true);
  28796. };
  28797. /**
  28798. * Freeze all materials
  28799. * A frozen material will not be updatable but should be faster to render
  28800. */
  28801. Scene.prototype.freezeMaterials = function () {
  28802. for (var i = 0; i < this.materials.length; i++) {
  28803. this.materials[i].freeze();
  28804. }
  28805. };
  28806. /**
  28807. * Unfreeze all materials
  28808. * A frozen material will not be updatable but should be faster to render
  28809. */
  28810. Scene.prototype.unfreezeMaterials = function () {
  28811. for (var i = 0; i < this.materials.length; i++) {
  28812. this.materials[i].unfreeze();
  28813. }
  28814. };
  28815. /**
  28816. * Releases all held ressources
  28817. */
  28818. Scene.prototype.dispose = function () {
  28819. this.beforeRender = null;
  28820. this.afterRender = null;
  28821. this.skeletons = [];
  28822. this.morphTargetManagers = [];
  28823. this._transientComponents = [];
  28824. this._isReadyForMeshStage.clear();
  28825. this._beforeEvaluateActiveMeshStage.clear();
  28826. this._evaluateSubMeshStage.clear();
  28827. this._activeMeshStage.clear();
  28828. this._cameraDrawRenderTargetStage.clear();
  28829. this._beforeCameraDrawStage.clear();
  28830. this._beforeRenderingGroupDrawStage.clear();
  28831. this._beforeRenderingMeshStage.clear();
  28832. this._afterRenderingMeshStage.clear();
  28833. this._afterRenderingGroupDrawStage.clear();
  28834. this._afterCameraDrawStage.clear();
  28835. this._afterRenderStage.clear();
  28836. this._beforeCameraUpdateStage.clear();
  28837. this._beforeClearStage.clear();
  28838. this._gatherRenderTargetsStage.clear();
  28839. this._gatherActiveCameraRenderTargetsStage.clear();
  28840. this._pointerMoveStage.clear();
  28841. this._pointerDownStage.clear();
  28842. this._pointerUpStage.clear();
  28843. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  28844. var component = _a[_i];
  28845. component.dispose();
  28846. }
  28847. this.importedMeshesFiles = new Array();
  28848. this.stopAllAnimations();
  28849. this.resetCachedMaterial();
  28850. // Smart arrays
  28851. if (this.activeCamera) {
  28852. this.activeCamera._activeMeshes.dispose();
  28853. this.activeCamera = null;
  28854. }
  28855. this._activeMeshes.dispose();
  28856. this._renderingManager.dispose();
  28857. this._processedMaterials.dispose();
  28858. this._activeParticleSystems.dispose();
  28859. this._activeSkeletons.dispose();
  28860. this._softwareSkinnedMeshes.dispose();
  28861. this._renderTargets.dispose();
  28862. this._registeredForLateAnimationBindings.dispose();
  28863. this._meshesForIntersections.dispose();
  28864. this._toBeDisposed = [];
  28865. // Abort active requests
  28866. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28867. var request = _c[_b];
  28868. request.abort();
  28869. }
  28870. // Events
  28871. this.onDisposeObservable.notifyObservers(this);
  28872. this.onDisposeObservable.clear();
  28873. this.onBeforeRenderObservable.clear();
  28874. this.onAfterRenderObservable.clear();
  28875. this.onBeforeRenderTargetsRenderObservable.clear();
  28876. this.onAfterRenderTargetsRenderObservable.clear();
  28877. this.onAfterStepObservable.clear();
  28878. this.onBeforeStepObservable.clear();
  28879. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28880. this.onAfterActiveMeshesEvaluationObservable.clear();
  28881. this.onBeforeParticlesRenderingObservable.clear();
  28882. this.onAfterParticlesRenderingObservable.clear();
  28883. this.onBeforeDrawPhaseObservable.clear();
  28884. this.onAfterDrawPhaseObservable.clear();
  28885. this.onBeforeAnimationsObservable.clear();
  28886. this.onAfterAnimationsObservable.clear();
  28887. this.onDataLoadedObservable.clear();
  28888. this.onBeforeRenderingGroupObservable.clear();
  28889. this.onAfterRenderingGroupObservable.clear();
  28890. this.onMeshImportedObservable.clear();
  28891. this.onBeforeCameraRenderObservable.clear();
  28892. this.onAfterCameraRenderObservable.clear();
  28893. this.onReadyObservable.clear();
  28894. this.onNewCameraAddedObservable.clear();
  28895. this.onCameraRemovedObservable.clear();
  28896. this.onNewLightAddedObservable.clear();
  28897. this.onLightRemovedObservable.clear();
  28898. this.onNewGeometryAddedObservable.clear();
  28899. this.onGeometryRemovedObservable.clear();
  28900. this.onNewTransformNodeAddedObservable.clear();
  28901. this.onTransformNodeRemovedObservable.clear();
  28902. this.onNewMeshAddedObservable.clear();
  28903. this.onMeshRemovedObservable.clear();
  28904. this.onNewMaterialAddedObservable.clear();
  28905. this.onMaterialRemovedObservable.clear();
  28906. this.onNewTextureAddedObservable.clear();
  28907. this.onTextureRemovedObservable.clear();
  28908. this.onPrePointerObservable.clear();
  28909. this.onPointerObservable.clear();
  28910. this.onPreKeyboardObservable.clear();
  28911. this.onKeyboardObservable.clear();
  28912. this.detachControl();
  28913. // Detach cameras
  28914. var canvas = this._engine.getRenderingCanvas();
  28915. if (canvas) {
  28916. var index;
  28917. for (index = 0; index < this.cameras.length; index++) {
  28918. this.cameras[index].detachControl(canvas);
  28919. }
  28920. }
  28921. // Release animation groups
  28922. while (this.animationGroups.length) {
  28923. this.animationGroups[0].dispose();
  28924. }
  28925. // Release lights
  28926. while (this.lights.length) {
  28927. this.lights[0].dispose();
  28928. }
  28929. // Release meshes
  28930. while (this.meshes.length) {
  28931. this.meshes[0].dispose(true);
  28932. }
  28933. while (this.transformNodes.length) {
  28934. this.removeTransformNode(this.transformNodes[0]);
  28935. }
  28936. // Release cameras
  28937. while (this.cameras.length) {
  28938. this.cameras[0].dispose();
  28939. }
  28940. // Release materials
  28941. if (this.defaultMaterial) {
  28942. this.defaultMaterial.dispose();
  28943. }
  28944. while (this.multiMaterials.length) {
  28945. this.multiMaterials[0].dispose();
  28946. }
  28947. while (this.materials.length) {
  28948. this.materials[0].dispose();
  28949. }
  28950. // Release particles
  28951. while (this.particleSystems.length) {
  28952. this.particleSystems[0].dispose();
  28953. }
  28954. // Release postProcesses
  28955. while (this.postProcesses.length) {
  28956. this.postProcesses[0].dispose();
  28957. }
  28958. // Release textures
  28959. while (this.textures.length) {
  28960. this.textures[0].dispose();
  28961. }
  28962. // Release UBO
  28963. this._sceneUbo.dispose();
  28964. if (this._alternateSceneUbo) {
  28965. this._alternateSceneUbo.dispose();
  28966. }
  28967. // Post-processes
  28968. this.postProcessManager.dispose();
  28969. // Remove from engine
  28970. index = this._engine.scenes.indexOf(this);
  28971. if (index > -1) {
  28972. this._engine.scenes.splice(index, 1);
  28973. }
  28974. this._engine.wipeCaches(true);
  28975. this._isDisposed = true;
  28976. };
  28977. Object.defineProperty(Scene.prototype, "isDisposed", {
  28978. /**
  28979. * Gets if the scene is already disposed
  28980. */
  28981. get: function () {
  28982. return this._isDisposed;
  28983. },
  28984. enumerable: true,
  28985. configurable: true
  28986. });
  28987. /**
  28988. * Call this function to reduce memory footprint of the scene.
  28989. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28990. */
  28991. Scene.prototype.clearCachedVertexData = function () {
  28992. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28993. var mesh = this.meshes[meshIndex];
  28994. var geometry = mesh.geometry;
  28995. if (geometry) {
  28996. geometry._indices = [];
  28997. for (var vbName in geometry._vertexBuffers) {
  28998. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28999. continue;
  29000. }
  29001. geometry._vertexBuffers[vbName]._buffer._data = null;
  29002. }
  29003. }
  29004. }
  29005. };
  29006. /**
  29007. * This function will remove the local cached buffer data from texture.
  29008. * It will save memory but will prevent the texture from being rebuilt
  29009. */
  29010. Scene.prototype.cleanCachedTextureBuffer = function () {
  29011. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29012. var baseTexture = _a[_i];
  29013. var buffer = baseTexture._buffer;
  29014. if (buffer) {
  29015. baseTexture._buffer = null;
  29016. }
  29017. }
  29018. };
  29019. /**
  29020. * Get the world extend vectors with an optional filter
  29021. *
  29022. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  29023. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  29024. */
  29025. Scene.prototype.getWorldExtends = function (filterPredicate) {
  29026. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29027. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  29028. filterPredicate = filterPredicate || (function () { return true; });
  29029. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  29030. mesh.computeWorldMatrix(true);
  29031. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  29032. return;
  29033. }
  29034. var boundingInfo = mesh.getBoundingInfo();
  29035. var minBox = boundingInfo.boundingBox.minimumWorld;
  29036. var maxBox = boundingInfo.boundingBox.maximumWorld;
  29037. BABYLON.Tools.CheckExtends(minBox, min, max);
  29038. BABYLON.Tools.CheckExtends(maxBox, min, max);
  29039. });
  29040. return {
  29041. min: min,
  29042. max: max
  29043. };
  29044. };
  29045. // Picking
  29046. /**
  29047. * Creates a ray that can be used to pick in the scene
  29048. * @param x defines the x coordinate of the origin (on-screen)
  29049. * @param y defines the y coordinate of the origin (on-screen)
  29050. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  29051. * @param camera defines the camera to use for the picking
  29052. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  29053. * @returns a Ray
  29054. */
  29055. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  29056. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  29057. var result = BABYLON.Ray.Zero();
  29058. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  29059. return result;
  29060. };
  29061. /**
  29062. * Creates a ray that can be used to pick in the scene
  29063. * @param x defines the x coordinate of the origin (on-screen)
  29064. * @param y defines the y coordinate of the origin (on-screen)
  29065. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  29066. * @param result defines the ray where to store the picking ray
  29067. * @param camera defines the camera to use for the picking
  29068. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  29069. * @returns the current scene
  29070. */
  29071. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  29072. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  29073. var engine = this._engine;
  29074. if (!camera) {
  29075. if (!this.activeCamera)
  29076. throw new Error("Active camera not set");
  29077. camera = this.activeCamera;
  29078. }
  29079. var cameraViewport = camera.viewport;
  29080. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29081. // Moving coordinates to local viewport world
  29082. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29083. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29084. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  29085. return this;
  29086. };
  29087. /**
  29088. * Creates a ray that can be used to pick in the scene
  29089. * @param x defines the x coordinate of the origin (on-screen)
  29090. * @param y defines the y coordinate of the origin (on-screen)
  29091. * @param camera defines the camera to use for the picking
  29092. * @returns a Ray
  29093. */
  29094. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  29095. var result = BABYLON.Ray.Zero();
  29096. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  29097. return result;
  29098. };
  29099. /**
  29100. * Creates a ray that can be used to pick in the scene
  29101. * @param x defines the x coordinate of the origin (on-screen)
  29102. * @param y defines the y coordinate of the origin (on-screen)
  29103. * @param result defines the ray where to store the picking ray
  29104. * @param camera defines the camera to use for the picking
  29105. * @returns the current scene
  29106. */
  29107. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  29108. if (!BABYLON.PickingInfo) {
  29109. return this;
  29110. }
  29111. var engine = this._engine;
  29112. if (!camera) {
  29113. if (!this.activeCamera)
  29114. throw new Error("Active camera not set");
  29115. camera = this.activeCamera;
  29116. }
  29117. var cameraViewport = camera.viewport;
  29118. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29119. var identity = BABYLON.Matrix.Identity();
  29120. // Moving coordinates to local viewport world
  29121. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29122. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29123. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  29124. return this;
  29125. };
  29126. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  29127. if (!BABYLON.PickingInfo) {
  29128. return null;
  29129. }
  29130. var pickingInfo = null;
  29131. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29132. var mesh = this.meshes[meshIndex];
  29133. if (predicate) {
  29134. if (!predicate(mesh)) {
  29135. continue;
  29136. }
  29137. }
  29138. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29139. continue;
  29140. }
  29141. var world = mesh.getWorldMatrix();
  29142. var ray = rayFunction(world);
  29143. var result = mesh.intersects(ray, fastCheck);
  29144. if (!result || !result.hit)
  29145. continue;
  29146. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  29147. continue;
  29148. pickingInfo = result;
  29149. if (fastCheck) {
  29150. break;
  29151. }
  29152. }
  29153. return pickingInfo || new BABYLON.PickingInfo();
  29154. };
  29155. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  29156. if (!BABYLON.PickingInfo) {
  29157. return null;
  29158. }
  29159. var pickingInfos = new Array();
  29160. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29161. var mesh = this.meshes[meshIndex];
  29162. if (predicate) {
  29163. if (!predicate(mesh)) {
  29164. continue;
  29165. }
  29166. }
  29167. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29168. continue;
  29169. }
  29170. var world = mesh.getWorldMatrix();
  29171. var ray = rayFunction(world);
  29172. var result = mesh.intersects(ray, false);
  29173. if (!result || !result.hit)
  29174. continue;
  29175. pickingInfos.push(result);
  29176. }
  29177. return pickingInfos;
  29178. };
  29179. /** Launch a ray to try to pick a mesh in the scene
  29180. * @param x position on screen
  29181. * @param y position on screen
  29182. * @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
  29183. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  29184. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29185. * @returns a PickingInfo
  29186. */
  29187. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  29188. var _this = this;
  29189. if (!BABYLON.PickingInfo) {
  29190. return null;
  29191. }
  29192. var result = this._internalPick(function (world) {
  29193. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  29194. return _this._tempPickingRay;
  29195. }, predicate, fastCheck);
  29196. if (result) {
  29197. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  29198. }
  29199. return result;
  29200. };
  29201. /** Use the given ray to pick a mesh in the scene
  29202. * @param ray The ray to use to pick meshes
  29203. * @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
  29204. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  29205. * @returns a PickingInfo
  29206. */
  29207. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  29208. var _this = this;
  29209. var result = this._internalPick(function (world) {
  29210. if (!_this._pickWithRayInverseMatrix) {
  29211. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29212. }
  29213. world.invertToRef(_this._pickWithRayInverseMatrix);
  29214. if (!_this._cachedRayForTransform) {
  29215. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29216. }
  29217. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29218. return _this._cachedRayForTransform;
  29219. }, predicate, fastCheck);
  29220. if (result) {
  29221. result.ray = ray;
  29222. }
  29223. return result;
  29224. };
  29225. /**
  29226. * Launch a ray to try to pick a mesh in the scene
  29227. * @param x X position on screen
  29228. * @param y Y position on screen
  29229. * @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
  29230. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29231. * @returns an array of PickingInfo
  29232. */
  29233. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  29234. var _this = this;
  29235. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  29236. };
  29237. /**
  29238. * Launch a ray to try to pick a mesh in the scene
  29239. * @param ray Ray to use
  29240. * @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
  29241. * @returns an array of PickingInfo
  29242. */
  29243. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  29244. var _this = this;
  29245. return this._internalMultiPick(function (world) {
  29246. if (!_this._pickWithRayInverseMatrix) {
  29247. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29248. }
  29249. world.invertToRef(_this._pickWithRayInverseMatrix);
  29250. if (!_this._cachedRayForTransform) {
  29251. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29252. }
  29253. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29254. return _this._cachedRayForTransform;
  29255. }, predicate);
  29256. };
  29257. /**
  29258. * Force the value of meshUnderPointer
  29259. * @param mesh defines the mesh to use
  29260. */
  29261. Scene.prototype.setPointerOverMesh = function (mesh) {
  29262. if (this._pointerOverMesh === mesh) {
  29263. return;
  29264. }
  29265. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29266. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29267. }
  29268. this._pointerOverMesh = mesh;
  29269. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29270. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29271. }
  29272. };
  29273. /**
  29274. * Gets the mesh under the pointer
  29275. * @returns a Mesh or null if no mesh is under the pointer
  29276. */
  29277. Scene.prototype.getPointerOverMesh = function () {
  29278. return this._pointerOverMesh;
  29279. };
  29280. // Misc.
  29281. /** @hidden */
  29282. Scene.prototype._rebuildGeometries = function () {
  29283. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  29284. var geometry = _a[_i];
  29285. geometry._rebuild();
  29286. }
  29287. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  29288. var mesh = _c[_b];
  29289. mesh._rebuild();
  29290. }
  29291. if (this.postProcessManager) {
  29292. this.postProcessManager._rebuild();
  29293. }
  29294. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  29295. var component = _e[_d];
  29296. component.rebuild();
  29297. }
  29298. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  29299. var system = _g[_f];
  29300. system.rebuild();
  29301. }
  29302. };
  29303. /** @hidden */
  29304. Scene.prototype._rebuildTextures = function () {
  29305. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29306. var texture = _a[_i];
  29307. texture._rebuild();
  29308. }
  29309. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29310. };
  29311. // Tags
  29312. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29313. if (tagsQuery === undefined) {
  29314. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29315. return list;
  29316. }
  29317. var listByTags = [];
  29318. forEach = forEach || (function (item) { return; });
  29319. for (var i in list) {
  29320. var item = list[i];
  29321. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29322. listByTags.push(item);
  29323. forEach(item);
  29324. }
  29325. }
  29326. return listByTags;
  29327. };
  29328. /**
  29329. * Get a list of meshes by tags
  29330. * @param tagsQuery defines the tags query to use
  29331. * @param forEach defines a predicate used to filter results
  29332. * @returns an array of Mesh
  29333. */
  29334. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29335. return this._getByTags(this.meshes, tagsQuery, forEach);
  29336. };
  29337. /**
  29338. * Get a list of cameras by tags
  29339. * @param tagsQuery defines the tags query to use
  29340. * @param forEach defines a predicate used to filter results
  29341. * @returns an array of Camera
  29342. */
  29343. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29344. return this._getByTags(this.cameras, tagsQuery, forEach);
  29345. };
  29346. /**
  29347. * Get a list of lights by tags
  29348. * @param tagsQuery defines the tags query to use
  29349. * @param forEach defines a predicate used to filter results
  29350. * @returns an array of Light
  29351. */
  29352. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29353. return this._getByTags(this.lights, tagsQuery, forEach);
  29354. };
  29355. /**
  29356. * Get a list of materials by tags
  29357. * @param tagsQuery defines the tags query to use
  29358. * @param forEach defines a predicate used to filter results
  29359. * @returns an array of Material
  29360. */
  29361. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29362. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29363. };
  29364. /**
  29365. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29366. * This allowed control for front to back rendering or reversly depending of the special needs.
  29367. *
  29368. * @param renderingGroupId The rendering group id corresponding to its index
  29369. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29370. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29371. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29372. */
  29373. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29374. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29375. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29376. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29377. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29378. };
  29379. /**
  29380. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29381. *
  29382. * @param renderingGroupId The rendering group id corresponding to its index
  29383. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29384. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29385. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29386. */
  29387. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29388. if (depth === void 0) { depth = true; }
  29389. if (stencil === void 0) { stencil = true; }
  29390. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29391. };
  29392. /**
  29393. * Gets the current auto clear configuration for one rendering group of the rendering
  29394. * manager.
  29395. * @param index the rendering group index to get the information for
  29396. * @returns The auto clear setup for the requested rendering group
  29397. */
  29398. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  29399. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  29400. };
  29401. Object.defineProperty(Scene.prototype, "blockMaterialDirtyMechanism", {
  29402. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  29403. get: function () {
  29404. return this._blockMaterialDirtyMechanism;
  29405. },
  29406. set: function (value) {
  29407. if (this._blockMaterialDirtyMechanism === value) {
  29408. return;
  29409. }
  29410. this._blockMaterialDirtyMechanism = value;
  29411. if (!value) { // Do a complete update
  29412. this.markAllMaterialsAsDirty(BABYLON.Material.AllDirtyFlag);
  29413. }
  29414. },
  29415. enumerable: true,
  29416. configurable: true
  29417. });
  29418. /**
  29419. * Will flag all materials as dirty to trigger new shader compilation
  29420. * @param flag defines the flag used to specify which material part must be marked as dirty
  29421. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29422. */
  29423. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29424. if (this._blockMaterialDirtyMechanism) {
  29425. return;
  29426. }
  29427. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29428. var material = _a[_i];
  29429. if (predicate && !predicate(material)) {
  29430. continue;
  29431. }
  29432. material.markAsDirty(flag);
  29433. }
  29434. };
  29435. /** @hidden */
  29436. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29437. var _this = this;
  29438. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29439. this._activeRequests.push(request);
  29440. request.onCompleteObservable.add(function (request) {
  29441. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29442. });
  29443. return request;
  29444. };
  29445. /** @hidden */
  29446. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29447. var _this = this;
  29448. return new Promise(function (resolve, reject) {
  29449. _this._loadFile(url, function (data) {
  29450. resolve(data);
  29451. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29452. reject(exception);
  29453. });
  29454. });
  29455. };
  29456. // Statics
  29457. Scene._uniqueIdCounter = 0;
  29458. /** The fog is deactivated */
  29459. Scene.FOGMODE_NONE = 0;
  29460. /** The fog density is following an exponential function */
  29461. Scene.FOGMODE_EXP = 1;
  29462. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  29463. Scene.FOGMODE_EXP2 = 2;
  29464. /** The fog density is following a linear function. */
  29465. Scene.FOGMODE_LINEAR = 3;
  29466. /**
  29467. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29468. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29469. */
  29470. Scene.MinDeltaTime = 1.0;
  29471. /**
  29472. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29473. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29474. */
  29475. Scene.MaxDeltaTime = 1000.0;
  29476. /** The distance in pixel that you have to move to prevent some events */
  29477. Scene.DragMovementThreshold = 10; // in pixels
  29478. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29479. Scene.LongPressDelay = 500; // in milliseconds
  29480. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29481. Scene.DoubleClickDelay = 300; // in milliseconds
  29482. /** If you need to check double click without raising a single click at first click, enable this flag */
  29483. Scene.ExclusiveDoubleClickMode = false;
  29484. return Scene;
  29485. }(BABYLON.AbstractScene));
  29486. BABYLON.Scene = Scene;
  29487. })(BABYLON || (BABYLON = {}));
  29488. //# sourceMappingURL=babylon.scene.js.map
  29489. var BABYLON;
  29490. (function (BABYLON) {
  29491. /**
  29492. * Set of assets to keep when moving a scene into an asset container.
  29493. */
  29494. var KeepAssets = /** @class */ (function (_super) {
  29495. __extends(KeepAssets, _super);
  29496. function KeepAssets() {
  29497. return _super !== null && _super.apply(this, arguments) || this;
  29498. }
  29499. return KeepAssets;
  29500. }(BABYLON.AbstractScene));
  29501. BABYLON.KeepAssets = KeepAssets;
  29502. /**
  29503. * Container with a set of assets that can be added or removed from a scene.
  29504. */
  29505. var AssetContainer = /** @class */ (function (_super) {
  29506. __extends(AssetContainer, _super);
  29507. /**
  29508. * Instantiates an AssetContainer.
  29509. * @param scene The scene the AssetContainer belongs to.
  29510. */
  29511. function AssetContainer(scene) {
  29512. var _this = _super.call(this) || this;
  29513. _this.scene = scene;
  29514. return _this;
  29515. }
  29516. /**
  29517. * Adds all the assets from the container to the scene.
  29518. */
  29519. AssetContainer.prototype.addAllToScene = function () {
  29520. var _this = this;
  29521. this.cameras.forEach(function (o) {
  29522. _this.scene.addCamera(o);
  29523. });
  29524. this.lights.forEach(function (o) {
  29525. _this.scene.addLight(o);
  29526. });
  29527. this.meshes.forEach(function (o) {
  29528. _this.scene.addMesh(o);
  29529. });
  29530. this.skeletons.forEach(function (o) {
  29531. _this.scene.addSkeleton(o);
  29532. });
  29533. this.animations.forEach(function (o) {
  29534. _this.scene.addAnimation(o);
  29535. });
  29536. this.animationGroups.forEach(function (o) {
  29537. _this.scene.addAnimationGroup(o);
  29538. });
  29539. this.multiMaterials.forEach(function (o) {
  29540. _this.scene.addMultiMaterial(o);
  29541. });
  29542. this.materials.forEach(function (o) {
  29543. _this.scene.addMaterial(o);
  29544. });
  29545. this.morphTargetManagers.forEach(function (o) {
  29546. _this.scene.addMorphTargetManager(o);
  29547. });
  29548. this.geometries.forEach(function (o) {
  29549. _this.scene.addGeometry(o);
  29550. });
  29551. this.transformNodes.forEach(function (o) {
  29552. _this.scene.addTransformNode(o);
  29553. });
  29554. this.actionManagers.forEach(function (o) {
  29555. _this.scene.addActionManager(o);
  29556. });
  29557. this.textures.forEach(function (o) {
  29558. _this.scene.addTexture(o);
  29559. });
  29560. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29561. var component = _a[_i];
  29562. component.addFromContainer(this.scene);
  29563. }
  29564. };
  29565. /**
  29566. * Removes all the assets in the container from the scene
  29567. */
  29568. AssetContainer.prototype.removeAllFromScene = function () {
  29569. var _this = this;
  29570. this.cameras.forEach(function (o) {
  29571. _this.scene.removeCamera(o);
  29572. });
  29573. this.lights.forEach(function (o) {
  29574. _this.scene.removeLight(o);
  29575. });
  29576. this.meshes.forEach(function (o) {
  29577. _this.scene.removeMesh(o);
  29578. });
  29579. this.skeletons.forEach(function (o) {
  29580. _this.scene.removeSkeleton(o);
  29581. });
  29582. this.animations.forEach(function (o) {
  29583. _this.scene.removeAnimation(o);
  29584. });
  29585. this.animationGroups.forEach(function (o) {
  29586. _this.scene.removeAnimationGroup(o);
  29587. });
  29588. this.multiMaterials.forEach(function (o) {
  29589. _this.scene.removeMultiMaterial(o);
  29590. });
  29591. this.materials.forEach(function (o) {
  29592. _this.scene.removeMaterial(o);
  29593. });
  29594. this.morphTargetManagers.forEach(function (o) {
  29595. _this.scene.removeMorphTargetManager(o);
  29596. });
  29597. this.geometries.forEach(function (o) {
  29598. _this.scene.removeGeometry(o);
  29599. });
  29600. this.transformNodes.forEach(function (o) {
  29601. _this.scene.removeTransformNode(o);
  29602. });
  29603. this.actionManagers.forEach(function (o) {
  29604. _this.scene.removeActionManager(o);
  29605. });
  29606. this.textures.forEach(function (o) {
  29607. _this.scene.removeTexture(o);
  29608. });
  29609. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29610. var component = _a[_i];
  29611. component.removeFromContainer(this.scene);
  29612. }
  29613. };
  29614. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29615. if (!sourceAssets) {
  29616. return;
  29617. }
  29618. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29619. var asset = sourceAssets_1[_i];
  29620. var move = true;
  29621. if (keepAssets) {
  29622. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29623. var keepAsset = keepAssets_1[_a];
  29624. if (asset === keepAsset) {
  29625. move = false;
  29626. break;
  29627. }
  29628. }
  29629. }
  29630. if (move) {
  29631. targetAssets.push(asset);
  29632. }
  29633. }
  29634. };
  29635. /**
  29636. * Removes all the assets contained in the scene and adds them to the container.
  29637. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29638. */
  29639. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29640. if (keepAssets === undefined) {
  29641. keepAssets = new KeepAssets();
  29642. }
  29643. for (var key in this) {
  29644. if (this.hasOwnProperty(key)) {
  29645. this[key] = this[key] || [];
  29646. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29647. }
  29648. }
  29649. this.removeAllFromScene();
  29650. };
  29651. /**
  29652. * 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.
  29653. * @returns the root mesh
  29654. */
  29655. AssetContainer.prototype.createRootMesh = function () {
  29656. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29657. this.meshes.forEach(function (m) {
  29658. if (!m.parent) {
  29659. rootMesh.addChild(m);
  29660. }
  29661. });
  29662. this.meshes.unshift(rootMesh);
  29663. return rootMesh;
  29664. };
  29665. return AssetContainer;
  29666. }(BABYLON.AbstractScene));
  29667. BABYLON.AssetContainer = AssetContainer;
  29668. })(BABYLON || (BABYLON = {}));
  29669. //# sourceMappingURL=babylon.assetContainer.js.map
  29670. var BABYLON;
  29671. (function (BABYLON) {
  29672. /**
  29673. * Class used to store data that will be store in GPU memory
  29674. */
  29675. var Buffer = /** @class */ (function () {
  29676. /**
  29677. * Constructor
  29678. * @param engine the engine
  29679. * @param data the data to use for this buffer
  29680. * @param updatable whether the data is updatable
  29681. * @param stride the stride (optional)
  29682. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29683. * @param instanced whether the buffer is instanced (optional)
  29684. * @param useBytes set to true if the stride in in bytes (optional)
  29685. */
  29686. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29687. if (stride === void 0) { stride = 0; }
  29688. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29689. if (instanced === void 0) { instanced = false; }
  29690. if (useBytes === void 0) { useBytes = false; }
  29691. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29692. this._engine = engine.getScene().getEngine();
  29693. }
  29694. else {
  29695. this._engine = engine;
  29696. }
  29697. this._updatable = updatable;
  29698. this._instanced = instanced;
  29699. this._data = data;
  29700. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29701. if (!postponeInternalCreation) { // by default
  29702. this.create();
  29703. }
  29704. }
  29705. /**
  29706. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29707. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29708. * @param offset defines offset in the buffer (0 by default)
  29709. * @param size defines the size in floats of attributes (position is 3 for instance)
  29710. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29711. * @param instanced defines if the vertex buffer contains indexed data
  29712. * @param useBytes defines if the offset and stride are in bytes
  29713. * @returns the new vertex buffer
  29714. */
  29715. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29716. if (useBytes === void 0) { useBytes = false; }
  29717. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29718. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29719. // a lot of these parameters are ignored as they are overriden by the buffer
  29720. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29721. };
  29722. // Properties
  29723. /**
  29724. * Gets a boolean indicating if the Buffer is updatable?
  29725. * @returns true if the buffer is updatable
  29726. */
  29727. Buffer.prototype.isUpdatable = function () {
  29728. return this._updatable;
  29729. };
  29730. /**
  29731. * Gets current buffer's data
  29732. * @returns a DataArray or null
  29733. */
  29734. Buffer.prototype.getData = function () {
  29735. return this._data;
  29736. };
  29737. /**
  29738. * Gets underlying native buffer
  29739. * @returns underlying native buffer
  29740. */
  29741. Buffer.prototype.getBuffer = function () {
  29742. return this._buffer;
  29743. };
  29744. /**
  29745. * Gets the stride in float32 units (i.e. byte stride / 4).
  29746. * May not be an integer if the byte stride is not divisible by 4.
  29747. * DEPRECATED. Use byteStride instead.
  29748. * @returns the stride in float32 units
  29749. */
  29750. Buffer.prototype.getStrideSize = function () {
  29751. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29752. };
  29753. // Methods
  29754. /**
  29755. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  29756. * @param data defines the data to store
  29757. */
  29758. Buffer.prototype.create = function (data) {
  29759. if (data === void 0) { data = null; }
  29760. if (!data && this._buffer) {
  29761. return; // nothing to do
  29762. }
  29763. data = data || this._data;
  29764. if (!data) {
  29765. return;
  29766. }
  29767. if (!this._buffer) { // create buffer
  29768. if (this._updatable) {
  29769. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29770. this._data = data;
  29771. }
  29772. else {
  29773. this._buffer = this._engine.createVertexBuffer(data);
  29774. }
  29775. }
  29776. else if (this._updatable) { // update buffer
  29777. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29778. this._data = data;
  29779. }
  29780. };
  29781. /** @hidden */
  29782. Buffer.prototype._rebuild = function () {
  29783. this._buffer = null;
  29784. this.create(this._data);
  29785. };
  29786. /**
  29787. * Update current buffer data
  29788. * @param data defines the data to store
  29789. */
  29790. Buffer.prototype.update = function (data) {
  29791. this.create(data);
  29792. };
  29793. /**
  29794. * Updates the data directly.
  29795. * @param data the new data
  29796. * @param offset the new offset
  29797. * @param vertexCount the vertex count (optional)
  29798. * @param useBytes set to true if the offset is in bytes
  29799. */
  29800. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29801. if (useBytes === void 0) { useBytes = false; }
  29802. if (!this._buffer) {
  29803. return;
  29804. }
  29805. if (this._updatable) { // update buffer
  29806. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29807. this._data = null;
  29808. }
  29809. };
  29810. /**
  29811. * Release all resources
  29812. */
  29813. Buffer.prototype.dispose = function () {
  29814. if (!this._buffer) {
  29815. return;
  29816. }
  29817. if (this._engine._releaseBuffer(this._buffer)) {
  29818. this._buffer = null;
  29819. }
  29820. };
  29821. return Buffer;
  29822. }());
  29823. BABYLON.Buffer = Buffer;
  29824. })(BABYLON || (BABYLON = {}));
  29825. //# sourceMappingURL=babylon.buffer.js.map
  29826. var BABYLON;
  29827. (function (BABYLON) {
  29828. /**
  29829. * Specialized buffer used to store vertex data
  29830. */
  29831. var VertexBuffer = /** @class */ (function () {
  29832. /**
  29833. * Constructor
  29834. * @param engine the engine
  29835. * @param data the data to use for this vertex buffer
  29836. * @param kind the vertex buffer kind
  29837. * @param updatable whether the data is updatable
  29838. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29839. * @param stride the stride (optional)
  29840. * @param instanced whether the buffer is instanced (optional)
  29841. * @param offset the offset of the data (optional)
  29842. * @param size the number of components (optional)
  29843. * @param type the type of the component (optional)
  29844. * @param normalized whether the data contains normalized data (optional)
  29845. * @param useBytes set to true if stride and offset are in bytes (optional)
  29846. */
  29847. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29848. if (normalized === void 0) { normalized = false; }
  29849. if (useBytes === void 0) { useBytes = false; }
  29850. if (data instanceof BABYLON.Buffer) {
  29851. this._buffer = data;
  29852. this._ownsBuffer = false;
  29853. }
  29854. else {
  29855. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29856. this._ownsBuffer = true;
  29857. }
  29858. this._kind = kind;
  29859. if (type == undefined) {
  29860. var data_1 = this.getData();
  29861. this.type = VertexBuffer.FLOAT;
  29862. if (data_1 instanceof Int8Array)
  29863. this.type = VertexBuffer.BYTE;
  29864. else if (data_1 instanceof Uint8Array)
  29865. this.type = VertexBuffer.UNSIGNED_BYTE;
  29866. else if (data_1 instanceof Int16Array)
  29867. this.type = VertexBuffer.SHORT;
  29868. else if (data_1 instanceof Uint16Array)
  29869. this.type = VertexBuffer.UNSIGNED_SHORT;
  29870. else if (data_1 instanceof Int32Array)
  29871. this.type = VertexBuffer.INT;
  29872. else if (data_1 instanceof Uint32Array)
  29873. this.type = VertexBuffer.UNSIGNED_INT;
  29874. }
  29875. else {
  29876. this.type = type;
  29877. }
  29878. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29879. if (useBytes) {
  29880. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29881. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29882. this.byteOffset = offset || 0;
  29883. }
  29884. else {
  29885. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29886. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29887. this.byteOffset = (offset || 0) * typeByteLength;
  29888. }
  29889. this.normalized = normalized;
  29890. this._instanced = instanced !== undefined ? instanced : false;
  29891. this._instanceDivisor = instanced ? 1 : 0;
  29892. }
  29893. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29894. /**
  29895. * Gets or sets the instance divisor when in instanced mode
  29896. */
  29897. get: function () {
  29898. return this._instanceDivisor;
  29899. },
  29900. set: function (value) {
  29901. this._instanceDivisor = value;
  29902. if (value == 0) {
  29903. this._instanced = false;
  29904. }
  29905. else {
  29906. this._instanced = true;
  29907. }
  29908. },
  29909. enumerable: true,
  29910. configurable: true
  29911. });
  29912. /** @hidden */
  29913. VertexBuffer.prototype._rebuild = function () {
  29914. if (!this._buffer) {
  29915. return;
  29916. }
  29917. this._buffer._rebuild();
  29918. };
  29919. /**
  29920. * Returns the kind of the VertexBuffer (string)
  29921. * @returns a string
  29922. */
  29923. VertexBuffer.prototype.getKind = function () {
  29924. return this._kind;
  29925. };
  29926. // Properties
  29927. /**
  29928. * Gets a boolean indicating if the VertexBuffer is updatable?
  29929. * @returns true if the buffer is updatable
  29930. */
  29931. VertexBuffer.prototype.isUpdatable = function () {
  29932. return this._buffer.isUpdatable();
  29933. };
  29934. /**
  29935. * Gets current buffer's data
  29936. * @returns a DataArray or null
  29937. */
  29938. VertexBuffer.prototype.getData = function () {
  29939. return this._buffer.getData();
  29940. };
  29941. /**
  29942. * Gets underlying native buffer
  29943. * @returns underlying native buffer
  29944. */
  29945. VertexBuffer.prototype.getBuffer = function () {
  29946. return this._buffer.getBuffer();
  29947. };
  29948. /**
  29949. * Gets the stride in float32 units (i.e. byte stride / 4).
  29950. * May not be an integer if the byte stride is not divisible by 4.
  29951. * DEPRECATED. Use byteStride instead.
  29952. * @returns the stride in float32 units
  29953. */
  29954. VertexBuffer.prototype.getStrideSize = function () {
  29955. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29956. };
  29957. /**
  29958. * Returns the offset as a multiple of the type byte length.
  29959. * DEPRECATED. Use byteOffset instead.
  29960. * @returns the offset in bytes
  29961. */
  29962. VertexBuffer.prototype.getOffset = function () {
  29963. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29964. };
  29965. /**
  29966. * Returns the number of components per vertex attribute (integer)
  29967. * @returns the size in float
  29968. */
  29969. VertexBuffer.prototype.getSize = function () {
  29970. return this._size;
  29971. };
  29972. /**
  29973. * Gets a boolean indicating is the internal buffer of the VertexBuffer is instanced
  29974. * @returns true if this buffer is instanced
  29975. */
  29976. VertexBuffer.prototype.getIsInstanced = function () {
  29977. return this._instanced;
  29978. };
  29979. /**
  29980. * Returns the instancing divisor, zero for non-instanced (integer).
  29981. * @returns a number
  29982. */
  29983. VertexBuffer.prototype.getInstanceDivisor = function () {
  29984. return this._instanceDivisor;
  29985. };
  29986. // Methods
  29987. /**
  29988. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  29989. * @param data defines the data to store
  29990. */
  29991. VertexBuffer.prototype.create = function (data) {
  29992. this._buffer.create(data);
  29993. };
  29994. /**
  29995. * Updates the underlying buffer according to the passed numeric array or Float32Array.
  29996. * This function will create a new buffer if the current one is not updatable
  29997. * @param data defines the data to store
  29998. */
  29999. VertexBuffer.prototype.update = function (data) {
  30000. this._buffer.update(data);
  30001. };
  30002. /**
  30003. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  30004. * Returns the directly updated WebGLBuffer.
  30005. * @param data the new data
  30006. * @param offset the new offset
  30007. * @param useBytes set to true if the offset is in bytes
  30008. */
  30009. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  30010. if (useBytes === void 0) { useBytes = false; }
  30011. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  30012. };
  30013. /**
  30014. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  30015. */
  30016. VertexBuffer.prototype.dispose = function () {
  30017. if (this._ownsBuffer) {
  30018. this._buffer.dispose();
  30019. }
  30020. };
  30021. /**
  30022. * Enumerates each value of this vertex buffer as numbers.
  30023. * @param count the number of values to enumerate
  30024. * @param callback the callback function called for each value
  30025. */
  30026. VertexBuffer.prototype.forEach = function (count, callback) {
  30027. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  30028. };
  30029. /**
  30030. * Deduces the stride given a kind.
  30031. * @param kind The kind string to deduce
  30032. * @returns The deduced stride
  30033. */
  30034. VertexBuffer.DeduceStride = function (kind) {
  30035. switch (kind) {
  30036. case VertexBuffer.UVKind:
  30037. case VertexBuffer.UV2Kind:
  30038. case VertexBuffer.UV3Kind:
  30039. case VertexBuffer.UV4Kind:
  30040. case VertexBuffer.UV5Kind:
  30041. case VertexBuffer.UV6Kind:
  30042. return 2;
  30043. case VertexBuffer.NormalKind:
  30044. case VertexBuffer.PositionKind:
  30045. return 3;
  30046. case VertexBuffer.ColorKind:
  30047. case VertexBuffer.MatricesIndicesKind:
  30048. case VertexBuffer.MatricesIndicesExtraKind:
  30049. case VertexBuffer.MatricesWeightsKind:
  30050. case VertexBuffer.MatricesWeightsExtraKind:
  30051. case VertexBuffer.TangentKind:
  30052. return 4;
  30053. default:
  30054. throw new Error("Invalid kind '" + kind + "'");
  30055. }
  30056. };
  30057. /**
  30058. * Gets the byte length of the given type.
  30059. * @param type the type
  30060. * @returns the number of bytes
  30061. */
  30062. VertexBuffer.GetTypeByteLength = function (type) {
  30063. switch (type) {
  30064. case VertexBuffer.BYTE:
  30065. case VertexBuffer.UNSIGNED_BYTE:
  30066. return 1;
  30067. case VertexBuffer.SHORT:
  30068. case VertexBuffer.UNSIGNED_SHORT:
  30069. return 2;
  30070. case VertexBuffer.INT:
  30071. case VertexBuffer.FLOAT:
  30072. return 4;
  30073. default:
  30074. throw new Error("Invalid type '" + type + "'");
  30075. }
  30076. };
  30077. /**
  30078. * Enumerates each value of the given parameters as numbers.
  30079. * @param data the data to enumerate
  30080. * @param byteOffset the byte offset of the data
  30081. * @param byteStride the byte stride of the data
  30082. * @param componentCount the number of components per element
  30083. * @param componentType the type of the component
  30084. * @param count the total number of components
  30085. * @param normalized whether the data is normalized
  30086. * @param callback the callback function called for each value
  30087. */
  30088. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  30089. if (data instanceof Array) {
  30090. var offset = byteOffset / 4;
  30091. var stride = byteStride / 4;
  30092. for (var index = 0; index < count; index += componentCount) {
  30093. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30094. callback(data[offset + componentIndex], index + componentIndex);
  30095. }
  30096. offset += stride;
  30097. }
  30098. }
  30099. else {
  30100. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  30101. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  30102. for (var index = 0; index < count; index += componentCount) {
  30103. var componentByteOffset = byteOffset;
  30104. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30105. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  30106. callback(value, index + componentIndex);
  30107. componentByteOffset += componentByteLength;
  30108. }
  30109. byteOffset += byteStride;
  30110. }
  30111. }
  30112. };
  30113. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30114. switch (type) {
  30115. case VertexBuffer.BYTE: {
  30116. var value = dataView.getInt8(byteOffset);
  30117. if (normalized) {
  30118. value = Math.max(value / 127, -1);
  30119. }
  30120. return value;
  30121. }
  30122. case VertexBuffer.UNSIGNED_BYTE: {
  30123. var value = dataView.getUint8(byteOffset);
  30124. if (normalized) {
  30125. value = value / 255;
  30126. }
  30127. return value;
  30128. }
  30129. case VertexBuffer.SHORT: {
  30130. var value = dataView.getInt16(byteOffset, true);
  30131. if (normalized) {
  30132. value = Math.max(value / 16383, -1);
  30133. }
  30134. return value;
  30135. }
  30136. case VertexBuffer.UNSIGNED_SHORT: {
  30137. var value = dataView.getUint16(byteOffset, true);
  30138. if (normalized) {
  30139. value = value / 65535;
  30140. }
  30141. return value;
  30142. }
  30143. case VertexBuffer.FLOAT: {
  30144. return dataView.getFloat32(byteOffset, true);
  30145. }
  30146. default: {
  30147. throw new Error("Invalid component type " + type);
  30148. }
  30149. }
  30150. };
  30151. /**
  30152. * The byte type.
  30153. */
  30154. VertexBuffer.BYTE = 5120;
  30155. /**
  30156. * The unsigned byte type.
  30157. */
  30158. VertexBuffer.UNSIGNED_BYTE = 5121;
  30159. /**
  30160. * The short type.
  30161. */
  30162. VertexBuffer.SHORT = 5122;
  30163. /**
  30164. * The unsigned short type.
  30165. */
  30166. VertexBuffer.UNSIGNED_SHORT = 5123;
  30167. /**
  30168. * The integer type.
  30169. */
  30170. VertexBuffer.INT = 5124;
  30171. /**
  30172. * The unsigned integer type.
  30173. */
  30174. VertexBuffer.UNSIGNED_INT = 5125;
  30175. /**
  30176. * The float type.
  30177. */
  30178. VertexBuffer.FLOAT = 5126;
  30179. // Enums
  30180. /**
  30181. * Positions
  30182. */
  30183. VertexBuffer.PositionKind = "position";
  30184. /**
  30185. * Normals
  30186. */
  30187. VertexBuffer.NormalKind = "normal";
  30188. /**
  30189. * Tangents
  30190. */
  30191. VertexBuffer.TangentKind = "tangent";
  30192. /**
  30193. * Texture coordinates
  30194. */
  30195. VertexBuffer.UVKind = "uv";
  30196. /**
  30197. * Texture coordinates 2
  30198. */
  30199. VertexBuffer.UV2Kind = "uv2";
  30200. /**
  30201. * Texture coordinates 3
  30202. */
  30203. VertexBuffer.UV3Kind = "uv3";
  30204. /**
  30205. * Texture coordinates 4
  30206. */
  30207. VertexBuffer.UV4Kind = "uv4";
  30208. /**
  30209. * Texture coordinates 5
  30210. */
  30211. VertexBuffer.UV5Kind = "uv5";
  30212. /**
  30213. * Texture coordinates 6
  30214. */
  30215. VertexBuffer.UV6Kind = "uv6";
  30216. /**
  30217. * Colors
  30218. */
  30219. VertexBuffer.ColorKind = "color";
  30220. /**
  30221. * Matrix indices (for bones)
  30222. */
  30223. VertexBuffer.MatricesIndicesKind = "matricesIndices";
  30224. /**
  30225. * Matrix weights (for bones)
  30226. */
  30227. VertexBuffer.MatricesWeightsKind = "matricesWeights";
  30228. /**
  30229. * Additional matrix indices (for bones)
  30230. */
  30231. VertexBuffer.MatricesIndicesExtraKind = "matricesIndicesExtra";
  30232. /**
  30233. * Additional matrix weights (for bones)
  30234. */
  30235. VertexBuffer.MatricesWeightsExtraKind = "matricesWeightsExtra";
  30236. return VertexBuffer;
  30237. }());
  30238. BABYLON.VertexBuffer = VertexBuffer;
  30239. })(BABYLON || (BABYLON = {}));
  30240. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30241. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  30242. var BABYLON;
  30243. (function (BABYLON) {
  30244. /**
  30245. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30246. */
  30247. var DummyInternalTextureTracker = /** @class */ (function () {
  30248. function DummyInternalTextureTracker() {
  30249. /**
  30250. * Gets or set the previous tracker in the list
  30251. */
  30252. this.previous = null;
  30253. /**
  30254. * Gets or set the next tracker in the list
  30255. */
  30256. this.next = null;
  30257. }
  30258. return DummyInternalTextureTracker;
  30259. }());
  30260. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30261. })(BABYLON || (BABYLON = {}));
  30262. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30263. var BABYLON;
  30264. (function (BABYLON) {
  30265. /**
  30266. * Class used to store data associated with WebGL texture data for the engine
  30267. * This class should not be used directly
  30268. */
  30269. var InternalTexture = /** @class */ (function () {
  30270. /**
  30271. * Creates a new InternalTexture
  30272. * @param engine defines the engine to use
  30273. * @param dataSource defines the type of data that will be used
  30274. */
  30275. function InternalTexture(engine, dataSource) {
  30276. /**
  30277. * Observable called when the texture is loaded
  30278. */
  30279. this.onLoadedObservable = new BABYLON.Observable();
  30280. /**
  30281. * Gets or set the previous tracker in the list
  30282. */
  30283. this.previous = null;
  30284. /**
  30285. * Gets or set the next tracker in the list
  30286. */
  30287. this.next = null;
  30288. // Private
  30289. /** @hidden */
  30290. this._initialSlot = -1;
  30291. /** @hidden */
  30292. this._designatedSlot = -1;
  30293. /** @hidden */
  30294. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30295. /** @hidden */
  30296. this._comparisonFunction = 0;
  30297. /** @hidden */
  30298. this._sphericalPolynomial = null;
  30299. /** @hidden */
  30300. this._lodGenerationScale = 0;
  30301. /** @hidden */
  30302. this._lodGenerationOffset = 0;
  30303. /** @hidden */
  30304. this._isRGBD = false;
  30305. /** @hidden */
  30306. this._references = 1;
  30307. this._engine = engine;
  30308. this._dataSource = dataSource;
  30309. this._webGLTexture = engine._createTexture();
  30310. }
  30311. /**
  30312. * Gets the Engine the texture belongs to.
  30313. * @returns The babylon engine
  30314. */
  30315. InternalTexture.prototype.getEngine = function () {
  30316. return this._engine;
  30317. };
  30318. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30319. /**
  30320. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30321. */
  30322. get: function () {
  30323. return this._dataSource;
  30324. },
  30325. enumerable: true,
  30326. configurable: true
  30327. });
  30328. /**
  30329. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30330. */
  30331. InternalTexture.prototype.incrementReferences = function () {
  30332. this._references++;
  30333. };
  30334. /**
  30335. * Change the size of the texture (not the size of the content)
  30336. * @param width defines the new width
  30337. * @param height defines the new height
  30338. * @param depth defines the new depth (1 by default)
  30339. */
  30340. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30341. if (depth === void 0) { depth = 1; }
  30342. this.width = width;
  30343. this.height = height;
  30344. this.depth = depth;
  30345. this.baseWidth = width;
  30346. this.baseHeight = height;
  30347. this.baseDepth = depth;
  30348. this._size = width * height * depth;
  30349. };
  30350. /** @hidden */
  30351. InternalTexture.prototype._rebuild = function () {
  30352. var _this = this;
  30353. var proxy;
  30354. this.isReady = false;
  30355. this._cachedCoordinatesMode = null;
  30356. this._cachedWrapU = null;
  30357. this._cachedWrapV = null;
  30358. this._cachedAnisotropicFilteringLevel = null;
  30359. switch (this._dataSource) {
  30360. case InternalTexture.DATASOURCE_TEMP:
  30361. return;
  30362. case InternalTexture.DATASOURCE_URL:
  30363. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30364. _this.isReady = true;
  30365. }, null, this._buffer, undefined, this.format);
  30366. proxy._swapAndDie(this);
  30367. return;
  30368. case InternalTexture.DATASOURCE_RAW:
  30369. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30370. proxy._swapAndDie(this);
  30371. this.isReady = true;
  30372. return;
  30373. case InternalTexture.DATASOURCE_RAW3D:
  30374. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30375. proxy._swapAndDie(this);
  30376. this.isReady = true;
  30377. return;
  30378. case InternalTexture.DATASOURCE_DYNAMIC:
  30379. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30380. proxy._swapAndDie(this);
  30381. // The engine will make sure to update content so no need to flag it as isReady = true
  30382. return;
  30383. case InternalTexture.DATASOURCE_RENDERTARGET:
  30384. var options = new BABYLON.RenderTargetCreationOptions();
  30385. options.generateDepthBuffer = this._generateDepthBuffer;
  30386. options.generateMipMaps = this.generateMipMaps;
  30387. options.generateStencilBuffer = this._generateStencilBuffer;
  30388. options.samplingMode = this.samplingMode;
  30389. options.type = this.type;
  30390. if (this.isCube) {
  30391. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30392. }
  30393. else {
  30394. var size = {
  30395. width: this.width,
  30396. height: this.height
  30397. };
  30398. proxy = this._engine.createRenderTargetTexture(size, options);
  30399. }
  30400. proxy._swapAndDie(this);
  30401. this.isReady = true;
  30402. return;
  30403. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30404. var depthTextureOptions = {
  30405. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30406. comparisonFunction: this._comparisonFunction,
  30407. generateStencil: this._generateStencilBuffer,
  30408. isCube: this.isCube
  30409. };
  30410. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30411. proxy._swapAndDie(this);
  30412. this.isReady = true;
  30413. return;
  30414. case InternalTexture.DATASOURCE_CUBE:
  30415. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30416. _this.isReady = true;
  30417. }, null, this.format, this._extension);
  30418. proxy._swapAndDie(this);
  30419. return;
  30420. case InternalTexture.DATASOURCE_CUBERAW:
  30421. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30422. proxy._swapAndDie(this);
  30423. this.isReady = true;
  30424. return;
  30425. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  30426. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30427. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  30428. _this.isReady = true;
  30429. });
  30430. proxy._swapAndDie(this);
  30431. return;
  30432. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30433. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30434. if (proxy) {
  30435. proxy._swapAndDie(_this);
  30436. }
  30437. _this.isReady = true;
  30438. }, null, this.format, this._extension);
  30439. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30440. return;
  30441. }
  30442. };
  30443. /** @hidden */
  30444. InternalTexture.prototype._swapAndDie = function (target) {
  30445. target._webGLTexture = this._webGLTexture;
  30446. if (this._framebuffer) {
  30447. target._framebuffer = this._framebuffer;
  30448. }
  30449. if (this._depthStencilBuffer) {
  30450. target._depthStencilBuffer = this._depthStencilBuffer;
  30451. }
  30452. if (this._lodTextureHigh) {
  30453. if (target._lodTextureHigh) {
  30454. target._lodTextureHigh.dispose();
  30455. }
  30456. target._lodTextureHigh = this._lodTextureHigh;
  30457. }
  30458. if (this._lodTextureMid) {
  30459. if (target._lodTextureMid) {
  30460. target._lodTextureMid.dispose();
  30461. }
  30462. target._lodTextureMid = this._lodTextureMid;
  30463. }
  30464. if (this._lodTextureLow) {
  30465. if (target._lodTextureLow) {
  30466. target._lodTextureLow.dispose();
  30467. }
  30468. target._lodTextureLow = this._lodTextureLow;
  30469. }
  30470. var cache = this._engine.getLoadedTexturesCache();
  30471. var index = cache.indexOf(this);
  30472. if (index !== -1) {
  30473. cache.splice(index, 1);
  30474. }
  30475. };
  30476. /**
  30477. * Dispose the current allocated resources
  30478. */
  30479. InternalTexture.prototype.dispose = function () {
  30480. if (!this._webGLTexture) {
  30481. return;
  30482. }
  30483. this._references--;
  30484. if (this._references === 0) {
  30485. this._engine._releaseTexture(this);
  30486. this._webGLTexture = null;
  30487. this.previous = null;
  30488. this.next = null;
  30489. }
  30490. };
  30491. /**
  30492. * The source of the texture data is unknown
  30493. */
  30494. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30495. /**
  30496. * Texture data comes from an URL
  30497. */
  30498. InternalTexture.DATASOURCE_URL = 1;
  30499. /**
  30500. * Texture data is only used for temporary storage
  30501. */
  30502. InternalTexture.DATASOURCE_TEMP = 2;
  30503. /**
  30504. * Texture data comes from raw data (ArrayBuffer)
  30505. */
  30506. InternalTexture.DATASOURCE_RAW = 3;
  30507. /**
  30508. * Texture content is dynamic (video or dynamic texture)
  30509. */
  30510. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30511. /**
  30512. * Texture content is generated by rendering to it
  30513. */
  30514. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30515. /**
  30516. * Texture content is part of a multi render target process
  30517. */
  30518. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30519. /**
  30520. * Texture data comes from a cube data file
  30521. */
  30522. InternalTexture.DATASOURCE_CUBE = 7;
  30523. /**
  30524. * Texture data comes from a raw cube data
  30525. */
  30526. InternalTexture.DATASOURCE_CUBERAW = 8;
  30527. /**
  30528. * Texture data come from a prefiltered cube data file
  30529. */
  30530. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30531. /**
  30532. * Texture content is raw 3D data
  30533. */
  30534. InternalTexture.DATASOURCE_RAW3D = 10;
  30535. /**
  30536. * Texture content is a depth texture
  30537. */
  30538. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30539. /**
  30540. * Texture data comes from a raw cube data encoded with RGBD
  30541. */
  30542. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  30543. return InternalTexture;
  30544. }());
  30545. BABYLON.InternalTexture = InternalTexture;
  30546. })(BABYLON || (BABYLON = {}));
  30547. //# sourceMappingURL=babylon.internalTexture.js.map
  30548. var BABYLON;
  30549. (function (BABYLON) {
  30550. /**
  30551. * Base class of all the textures in babylon.
  30552. * It groups all the common properties the materials, post process, lights... might need
  30553. * in order to make a correct use of the texture.
  30554. */
  30555. var BaseTexture = /** @class */ (function () {
  30556. /**
  30557. * Instantiates a new BaseTexture.
  30558. * Base class of all the textures in babylon.
  30559. * It groups all the common properties the materials, post process, lights... might need
  30560. * in order to make a correct use of the texture.
  30561. * @param scene Define the scene the texture blongs to
  30562. */
  30563. function BaseTexture(scene) {
  30564. this._hasAlpha = false;
  30565. /**
  30566. * Defines if the alpha value should be determined via the rgb values.
  30567. * If true the luminance of the pixel might be used to find the corresponding alpha value.
  30568. */
  30569. this.getAlphaFromRGB = false;
  30570. /**
  30571. * Intensity or strength of the texture.
  30572. * It is commonly used by materials to fine tune the intensity of the texture
  30573. */
  30574. this.level = 1;
  30575. /**
  30576. * Define the UV chanel to use starting from 0 and defaulting to 0.
  30577. * This is part of the texture as textures usually maps to one uv set.
  30578. */
  30579. this.coordinatesIndex = 0;
  30580. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30581. /**
  30582. * | Value | Type | Description |
  30583. * | ----- | ------------------ | ----------- |
  30584. * | 0 | CLAMP_ADDRESSMODE | |
  30585. * | 1 | WRAP_ADDRESSMODE | |
  30586. * | 2 | MIRROR_ADDRESSMODE | |
  30587. */
  30588. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30589. /**
  30590. * | Value | Type | Description |
  30591. * | ----- | ------------------ | ----------- |
  30592. * | 0 | CLAMP_ADDRESSMODE | |
  30593. * | 1 | WRAP_ADDRESSMODE | |
  30594. * | 2 | MIRROR_ADDRESSMODE | |
  30595. */
  30596. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30597. /**
  30598. * | Value | Type | Description |
  30599. * | ----- | ------------------ | ----------- |
  30600. * | 0 | CLAMP_ADDRESSMODE | |
  30601. * | 1 | WRAP_ADDRESSMODE | |
  30602. * | 2 | MIRROR_ADDRESSMODE | |
  30603. */
  30604. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30605. /**
  30606. * With compliant hardware and browser (supporting anisotropic filtering)
  30607. * this defines the level of anisotropic filtering in the texture.
  30608. * The higher the better but the slower. This defaults to 4 as it seems to be the best tradeoff.
  30609. */
  30610. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30611. /**
  30612. * Define if the texture is a cube texture or if false a 2d texture.
  30613. */
  30614. this.isCube = false;
  30615. /**
  30616. * Define if the texture is a 3d texture (webgl 2) or if false a 2d texture.
  30617. */
  30618. this.is3D = false;
  30619. /**
  30620. * Define if the texture contains data in gamma space (most of the png/jpg aside bump).
  30621. * HDR texture are usually stored in linear space.
  30622. * This only impacts the PBR and Background materials
  30623. */
  30624. this.gammaSpace = true;
  30625. /**
  30626. * Is Z inverted in the texture (useful in a cube texture).
  30627. */
  30628. this.invertZ = false;
  30629. /**
  30630. * @hidden
  30631. */
  30632. this.lodLevelInAlpha = false;
  30633. /**
  30634. * Define if the texture is a render target.
  30635. */
  30636. this.isRenderTarget = false;
  30637. /**
  30638. * Define the list of animation attached to the texture.
  30639. */
  30640. this.animations = new Array();
  30641. /**
  30642. * An event triggered when the texture is disposed.
  30643. */
  30644. this.onDisposeObservable = new BABYLON.Observable();
  30645. /**
  30646. * Define the current state of the loading sequence when in delayed load mode.
  30647. */
  30648. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30649. this._cachedSize = BABYLON.Size.Zero();
  30650. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30651. if (this._scene) {
  30652. this._scene.textures.push(this);
  30653. this._scene.onNewTextureAddedObservable.notifyObservers(this);
  30654. }
  30655. this._uid = null;
  30656. }
  30657. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30658. get: function () {
  30659. return this._hasAlpha;
  30660. },
  30661. /**
  30662. * Define if the texture is having a usable alpha value (can be use for transparency or glossiness for instance).
  30663. */
  30664. set: function (value) {
  30665. if (this._hasAlpha === value) {
  30666. return;
  30667. }
  30668. this._hasAlpha = value;
  30669. if (this._scene) {
  30670. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30671. }
  30672. },
  30673. enumerable: true,
  30674. configurable: true
  30675. });
  30676. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30677. get: function () {
  30678. return this._coordinatesMode;
  30679. },
  30680. /**
  30681. * How a texture is mapped.
  30682. *
  30683. * | Value | Type | Description |
  30684. * | ----- | ----------------------------------- | ----------- |
  30685. * | 0 | EXPLICIT_MODE | |
  30686. * | 1 | SPHERICAL_MODE | |
  30687. * | 2 | PLANAR_MODE | |
  30688. * | 3 | CUBIC_MODE | |
  30689. * | 4 | PROJECTION_MODE | |
  30690. * | 5 | SKYBOX_MODE | |
  30691. * | 6 | INVCUBIC_MODE | |
  30692. * | 7 | EQUIRECTANGULAR_MODE | |
  30693. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30694. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30695. */
  30696. set: function (value) {
  30697. if (this._coordinatesMode === value) {
  30698. return;
  30699. }
  30700. this._coordinatesMode = value;
  30701. if (this._scene) {
  30702. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30703. }
  30704. },
  30705. enumerable: true,
  30706. configurable: true
  30707. });
  30708. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30709. /**
  30710. * Gets whether or not the texture contains RGBD data.
  30711. */
  30712. get: function () {
  30713. return this._texture != null && this._texture._isRGBD;
  30714. },
  30715. enumerable: true,
  30716. configurable: true
  30717. });
  30718. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30719. /**
  30720. * With prefiltered texture, defined the offset used during the prefiltering steps.
  30721. */
  30722. get: function () {
  30723. if (this._texture)
  30724. return this._texture._lodGenerationOffset;
  30725. return 0.0;
  30726. },
  30727. set: function (value) {
  30728. if (this._texture)
  30729. this._texture._lodGenerationOffset = value;
  30730. },
  30731. enumerable: true,
  30732. configurable: true
  30733. });
  30734. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30735. /**
  30736. * With prefiltered texture, defined the scale used during the prefiltering steps.
  30737. */
  30738. get: function () {
  30739. if (this._texture)
  30740. return this._texture._lodGenerationScale;
  30741. return 0.0;
  30742. },
  30743. set: function (value) {
  30744. if (this._texture)
  30745. this._texture._lodGenerationScale = value;
  30746. },
  30747. enumerable: true,
  30748. configurable: true
  30749. });
  30750. Object.defineProperty(BaseTexture.prototype, "uid", {
  30751. /**
  30752. * Define the unique id of the texture in the scene.
  30753. */
  30754. get: function () {
  30755. if (!this._uid) {
  30756. this._uid = BABYLON.Tools.RandomId();
  30757. }
  30758. return this._uid;
  30759. },
  30760. enumerable: true,
  30761. configurable: true
  30762. });
  30763. /**
  30764. * Return a string representation of the texture.
  30765. * @returns the texture as a string
  30766. */
  30767. BaseTexture.prototype.toString = function () {
  30768. return this.name;
  30769. };
  30770. /**
  30771. * Get the class name of the texture.
  30772. * @returns "BaseTexture"
  30773. */
  30774. BaseTexture.prototype.getClassName = function () {
  30775. return "BaseTexture";
  30776. };
  30777. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30778. /**
  30779. * Callback triggered when the texture has been disposed.
  30780. * Kept for back compatibility, you can use the onDisposeObservable instead.
  30781. */
  30782. set: function (callback) {
  30783. if (this._onDisposeObserver) {
  30784. this.onDisposeObservable.remove(this._onDisposeObserver);
  30785. }
  30786. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30787. },
  30788. enumerable: true,
  30789. configurable: true
  30790. });
  30791. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30792. /**
  30793. * Define if the texture is preventinga material to render or not.
  30794. * If not and the texture is not ready, the engine will use a default black texture instead.
  30795. */
  30796. get: function () {
  30797. return true;
  30798. },
  30799. enumerable: true,
  30800. configurable: true
  30801. });
  30802. /**
  30803. * Get the scene the texture belongs to.
  30804. * @returns the scene or null if undefined
  30805. */
  30806. BaseTexture.prototype.getScene = function () {
  30807. return this._scene;
  30808. };
  30809. /**
  30810. * Get the texture transform matrix used to offset tile the texture for istance.
  30811. * @returns the transformation matrix
  30812. */
  30813. BaseTexture.prototype.getTextureMatrix = function () {
  30814. return BABYLON.Matrix.IdentityReadOnly;
  30815. };
  30816. /**
  30817. * Get the texture reflection matrix used to rotate/transform the reflection.
  30818. * @returns the reflection matrix
  30819. */
  30820. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30821. return BABYLON.Matrix.IdentityReadOnly;
  30822. };
  30823. /**
  30824. * Get the underlying lower level texture from Babylon.
  30825. * @returns the insternal texture
  30826. */
  30827. BaseTexture.prototype.getInternalTexture = function () {
  30828. return this._texture;
  30829. };
  30830. /**
  30831. * Get if the texture is ready to be consumed (either it is ready or it is not blocking)
  30832. * @returns true if ready or not blocking
  30833. */
  30834. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30835. return !this.isBlocking || this.isReady();
  30836. };
  30837. /**
  30838. * Get if the texture is ready to be used (downloaded, converted, mip mapped...).
  30839. * @returns true if fully ready
  30840. */
  30841. BaseTexture.prototype.isReady = function () {
  30842. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30843. this.delayLoad();
  30844. return false;
  30845. }
  30846. if (this._texture) {
  30847. return this._texture.isReady;
  30848. }
  30849. return false;
  30850. };
  30851. /**
  30852. * Get the size of the texture.
  30853. * @returns the texture size.
  30854. */
  30855. BaseTexture.prototype.getSize = function () {
  30856. if (this._texture) {
  30857. if (this._texture.width) {
  30858. this._cachedSize.width = this._texture.width;
  30859. this._cachedSize.height = this._texture.height;
  30860. return this._cachedSize;
  30861. }
  30862. if (this._texture._size) {
  30863. this._cachedSize.width = this._texture._size;
  30864. this._cachedSize.height = this._texture._size;
  30865. return this._cachedSize;
  30866. }
  30867. }
  30868. return this._cachedSize;
  30869. };
  30870. /**
  30871. * Get the base size of the texture.
  30872. * It can be different from the size if the texture has been resized for POT for instance
  30873. * @returns the base size
  30874. */
  30875. BaseTexture.prototype.getBaseSize = function () {
  30876. if (!this.isReady() || !this._texture)
  30877. return BABYLON.Size.Zero();
  30878. if (this._texture._size) {
  30879. return new BABYLON.Size(this._texture._size, this._texture._size);
  30880. }
  30881. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30882. };
  30883. /**
  30884. * Scales the texture if is `canRescale()`
  30885. * @param ratio the resize factor we want to use to rescale
  30886. */
  30887. BaseTexture.prototype.scale = function (ratio) {
  30888. };
  30889. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30890. /**
  30891. * Get if the texture can rescale.
  30892. */
  30893. get: function () {
  30894. return false;
  30895. },
  30896. enumerable: true,
  30897. configurable: true
  30898. });
  30899. /** @hidden */
  30900. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30901. if (!this._scene) {
  30902. return null;
  30903. }
  30904. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30905. for (var index = 0; index < texturesCache.length; index++) {
  30906. var texturesCacheEntry = texturesCache[index];
  30907. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30908. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30909. texturesCacheEntry.incrementReferences();
  30910. return texturesCacheEntry;
  30911. }
  30912. }
  30913. }
  30914. return null;
  30915. };
  30916. /** @hidden */
  30917. BaseTexture.prototype._rebuild = function () {
  30918. };
  30919. /**
  30920. * Triggers the load sequence in delayed load mode.
  30921. */
  30922. BaseTexture.prototype.delayLoad = function () {
  30923. };
  30924. /**
  30925. * Clones the texture.
  30926. * @returns the cloned texture
  30927. */
  30928. BaseTexture.prototype.clone = function () {
  30929. return null;
  30930. };
  30931. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30932. /**
  30933. * Get the texture underlying type (INT, FLOAT...)
  30934. */
  30935. get: function () {
  30936. if (!this._texture) {
  30937. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30938. }
  30939. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30940. },
  30941. enumerable: true,
  30942. configurable: true
  30943. });
  30944. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30945. /**
  30946. * Get the texture underlying format (RGB, RGBA...)
  30947. */
  30948. get: function () {
  30949. if (!this._texture) {
  30950. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30951. }
  30952. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30953. },
  30954. enumerable: true,
  30955. configurable: true
  30956. });
  30957. /**
  30958. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30959. * This will returns an RGBA array buffer containing either in values (0-255) or
  30960. * float values (0-1) depending of the underlying buffer type.
  30961. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  30962. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  30963. * @param buffer defines a user defined buffer to fill with data (can be null)
  30964. * @returns The Array buffer containing the pixels data.
  30965. */
  30966. BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
  30967. if (faceIndex === void 0) { faceIndex = 0; }
  30968. if (level === void 0) { level = 0; }
  30969. if (buffer === void 0) { buffer = null; }
  30970. if (!this._texture) {
  30971. return null;
  30972. }
  30973. var size = this.getSize();
  30974. var width = size.width;
  30975. var height = size.height;
  30976. var scene = this.getScene();
  30977. if (!scene) {
  30978. return null;
  30979. }
  30980. var engine = scene.getEngine();
  30981. if (level != 0) {
  30982. width = width / Math.pow(2, level);
  30983. height = height / Math.pow(2, level);
  30984. width = Math.round(width);
  30985. height = Math.round(height);
  30986. }
  30987. if (this._texture.isCube) {
  30988. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  30989. }
  30990. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  30991. };
  30992. /**
  30993. * Release and destroy the underlying lower level texture aka internalTexture.
  30994. */
  30995. BaseTexture.prototype.releaseInternalTexture = function () {
  30996. if (this._texture) {
  30997. this._texture.dispose();
  30998. this._texture = null;
  30999. }
  31000. };
  31001. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  31002. /**
  31003. * Get the polynomial representation of the texture data.
  31004. * This is mainly use as a fast way to recover IBL Diffuse irradiance data.
  31005. * @see https://learnopengl.com/PBR/IBL/Diffuse-irradiance
  31006. */
  31007. get: function () {
  31008. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  31009. return null;
  31010. }
  31011. if (!this._texture._sphericalPolynomial) {
  31012. this._texture._sphericalPolynomial =
  31013. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  31014. }
  31015. return this._texture._sphericalPolynomial;
  31016. },
  31017. set: function (value) {
  31018. if (this._texture) {
  31019. this._texture._sphericalPolynomial = value;
  31020. }
  31021. },
  31022. enumerable: true,
  31023. configurable: true
  31024. });
  31025. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  31026. /** @hidden */
  31027. get: function () {
  31028. if (this._texture) {
  31029. return this._texture._lodTextureHigh;
  31030. }
  31031. return null;
  31032. },
  31033. enumerable: true,
  31034. configurable: true
  31035. });
  31036. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  31037. /** @hidden */
  31038. get: function () {
  31039. if (this._texture) {
  31040. return this._texture._lodTextureMid;
  31041. }
  31042. return null;
  31043. },
  31044. enumerable: true,
  31045. configurable: true
  31046. });
  31047. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  31048. /** @hidden */
  31049. get: function () {
  31050. if (this._texture) {
  31051. return this._texture._lodTextureLow;
  31052. }
  31053. return null;
  31054. },
  31055. enumerable: true,
  31056. configurable: true
  31057. });
  31058. /**
  31059. * Dispose the texture and release its associated resources.
  31060. */
  31061. BaseTexture.prototype.dispose = function () {
  31062. if (!this._scene) {
  31063. return;
  31064. }
  31065. // Animations
  31066. this._scene.stopAnimation(this);
  31067. // Remove from scene
  31068. this._scene._removePendingData(this);
  31069. var index = this._scene.textures.indexOf(this);
  31070. if (index >= 0) {
  31071. this._scene.textures.splice(index, 1);
  31072. }
  31073. this._scene.onTextureRemovedObservable.notifyObservers(this);
  31074. if (this._texture === undefined) {
  31075. return;
  31076. }
  31077. // Release
  31078. this.releaseInternalTexture();
  31079. // Callback
  31080. this.onDisposeObservable.notifyObservers(this);
  31081. this.onDisposeObservable.clear();
  31082. };
  31083. /**
  31084. * Serialize the texture into a JSON representation that can be parsed later on.
  31085. * @returns the JSON representation of the texture
  31086. */
  31087. BaseTexture.prototype.serialize = function () {
  31088. if (!this.name) {
  31089. return null;
  31090. }
  31091. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31092. // Animations
  31093. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  31094. return serializationObject;
  31095. };
  31096. /**
  31097. * Helper function to be called back once a list of texture contains only ready textures.
  31098. * @param textures Define the list of textures to wait for
  31099. * @param callback Define the callback triggered once the entire list will be ready
  31100. */
  31101. BaseTexture.WhenAllReady = function (textures, callback) {
  31102. var numRemaining = textures.length;
  31103. if (numRemaining === 0) {
  31104. callback();
  31105. return;
  31106. }
  31107. var _loop_1 = function () {
  31108. texture = textures[i];
  31109. if (texture.isReady()) {
  31110. if (--numRemaining === 0) {
  31111. callback();
  31112. }
  31113. }
  31114. else {
  31115. onLoadObservable = texture.onLoadObservable;
  31116. var onLoadCallback_1 = function () {
  31117. onLoadObservable.removeCallback(onLoadCallback_1);
  31118. if (--numRemaining === 0) {
  31119. callback();
  31120. }
  31121. };
  31122. onLoadObservable.add(onLoadCallback_1);
  31123. }
  31124. };
  31125. var texture, onLoadObservable;
  31126. for (var i = 0; i < textures.length; i++) {
  31127. _loop_1();
  31128. }
  31129. };
  31130. /**
  31131. * Default anisotropic filtering level for the application.
  31132. * It is set to 4 as a good tradeoff between perf and quality.
  31133. */
  31134. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  31135. __decorate([
  31136. BABYLON.serialize()
  31137. ], BaseTexture.prototype, "name", void 0);
  31138. __decorate([
  31139. BABYLON.serialize("hasAlpha")
  31140. ], BaseTexture.prototype, "_hasAlpha", void 0);
  31141. __decorate([
  31142. BABYLON.serialize()
  31143. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  31144. __decorate([
  31145. BABYLON.serialize()
  31146. ], BaseTexture.prototype, "level", void 0);
  31147. __decorate([
  31148. BABYLON.serialize()
  31149. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  31150. __decorate([
  31151. BABYLON.serialize("coordinatesMode")
  31152. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  31153. __decorate([
  31154. BABYLON.serialize()
  31155. ], BaseTexture.prototype, "wrapU", void 0);
  31156. __decorate([
  31157. BABYLON.serialize()
  31158. ], BaseTexture.prototype, "wrapV", void 0);
  31159. __decorate([
  31160. BABYLON.serialize()
  31161. ], BaseTexture.prototype, "wrapR", void 0);
  31162. __decorate([
  31163. BABYLON.serialize()
  31164. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  31165. __decorate([
  31166. BABYLON.serialize()
  31167. ], BaseTexture.prototype, "isCube", void 0);
  31168. __decorate([
  31169. BABYLON.serialize()
  31170. ], BaseTexture.prototype, "is3D", void 0);
  31171. __decorate([
  31172. BABYLON.serialize()
  31173. ], BaseTexture.prototype, "gammaSpace", void 0);
  31174. __decorate([
  31175. BABYLON.serialize()
  31176. ], BaseTexture.prototype, "invertZ", void 0);
  31177. __decorate([
  31178. BABYLON.serialize()
  31179. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  31180. __decorate([
  31181. BABYLON.serialize()
  31182. ], BaseTexture.prototype, "lodGenerationOffset", null);
  31183. __decorate([
  31184. BABYLON.serialize()
  31185. ], BaseTexture.prototype, "lodGenerationScale", null);
  31186. __decorate([
  31187. BABYLON.serialize()
  31188. ], BaseTexture.prototype, "isRenderTarget", void 0);
  31189. return BaseTexture;
  31190. }());
  31191. BABYLON.BaseTexture = BaseTexture;
  31192. })(BABYLON || (BABYLON = {}));
  31193. //# sourceMappingURL=babylon.baseTexture.js.map
  31194. var BABYLON;
  31195. (function (BABYLON) {
  31196. var Texture = /** @class */ (function (_super) {
  31197. __extends(Texture, _super);
  31198. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  31199. if (noMipmap === void 0) { noMipmap = false; }
  31200. if (invertY === void 0) { invertY = true; }
  31201. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31202. if (onLoad === void 0) { onLoad = null; }
  31203. if (onError === void 0) { onError = null; }
  31204. if (buffer === void 0) { buffer = null; }
  31205. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31206. var _this = _super.call(this, scene) || this;
  31207. _this.uOffset = 0;
  31208. _this.vOffset = 0;
  31209. _this.uScale = 1.0;
  31210. _this.vScale = 1.0;
  31211. _this.uAng = 0;
  31212. _this.vAng = 0;
  31213. _this.wAng = 0;
  31214. /**
  31215. * Defines the center of rotation (U)
  31216. */
  31217. _this.uRotationCenter = 0.5;
  31218. /**
  31219. * Defines the center of rotation (V)
  31220. */
  31221. _this.vRotationCenter = 0.5;
  31222. /**
  31223. * Defines the center of rotation (W)
  31224. */
  31225. _this.wRotationCenter = 0.5;
  31226. _this._isBlocking = true;
  31227. _this.name = url || "";
  31228. _this.url = url;
  31229. _this._noMipmap = noMipmap;
  31230. _this._invertY = invertY;
  31231. _this._samplingMode = samplingMode;
  31232. _this._buffer = buffer;
  31233. _this._deleteBuffer = deleteBuffer;
  31234. if (format) {
  31235. _this._format = format;
  31236. }
  31237. scene = _this.getScene();
  31238. if (!scene) {
  31239. return _this;
  31240. }
  31241. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  31242. var load = function () {
  31243. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  31244. _this.onLoadObservable.notifyObservers(_this);
  31245. }
  31246. if (onLoad) {
  31247. onLoad();
  31248. }
  31249. if (!_this.isBlocking && scene) {
  31250. scene.resetCachedMaterial();
  31251. }
  31252. };
  31253. if (!_this.url) {
  31254. _this._delayedOnLoad = load;
  31255. _this._delayedOnError = onError;
  31256. return _this;
  31257. }
  31258. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  31259. if (!_this._texture) {
  31260. if (!scene.useDelayedTextureLoading) {
  31261. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  31262. if (deleteBuffer) {
  31263. delete _this._buffer;
  31264. }
  31265. }
  31266. else {
  31267. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31268. _this._delayedOnLoad = load;
  31269. _this._delayedOnError = onError;
  31270. }
  31271. }
  31272. else {
  31273. if (_this._texture.isReady) {
  31274. BABYLON.Tools.SetImmediate(function () { return load(); });
  31275. }
  31276. else {
  31277. _this._texture.onLoadedObservable.add(load);
  31278. }
  31279. }
  31280. return _this;
  31281. }
  31282. Object.defineProperty(Texture.prototype, "noMipmap", {
  31283. get: function () {
  31284. return this._noMipmap;
  31285. },
  31286. enumerable: true,
  31287. configurable: true
  31288. });
  31289. Object.defineProperty(Texture.prototype, "isBlocking", {
  31290. get: function () {
  31291. return this._isBlocking;
  31292. },
  31293. set: function (value) {
  31294. this._isBlocking = value;
  31295. },
  31296. enumerable: true,
  31297. configurable: true
  31298. });
  31299. Object.defineProperty(Texture.prototype, "samplingMode", {
  31300. get: function () {
  31301. return this._samplingMode;
  31302. },
  31303. enumerable: true,
  31304. configurable: true
  31305. });
  31306. /**
  31307. * Update the url (and optional buffer) of this texture if url was null during construction.
  31308. * @param url the url of the texture
  31309. * @param buffer the buffer of the texture (defaults to null)
  31310. */
  31311. Texture.prototype.updateURL = function (url, buffer) {
  31312. if (buffer === void 0) { buffer = null; }
  31313. if (this.url) {
  31314. throw new Error("URL is already set");
  31315. }
  31316. this.url = url;
  31317. this._buffer = buffer;
  31318. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31319. this.delayLoad();
  31320. };
  31321. Texture.prototype.delayLoad = function () {
  31322. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31323. return;
  31324. }
  31325. var scene = this.getScene();
  31326. if (!scene) {
  31327. return;
  31328. }
  31329. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31330. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  31331. if (!this._texture) {
  31332. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  31333. if (this._deleteBuffer) {
  31334. delete this._buffer;
  31335. }
  31336. }
  31337. else {
  31338. if (this._delayedOnLoad) {
  31339. if (this._texture.isReady) {
  31340. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31341. }
  31342. else {
  31343. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31344. }
  31345. }
  31346. }
  31347. this._delayedOnLoad = null;
  31348. this._delayedOnError = null;
  31349. };
  31350. /**
  31351. * Default is Trilinear mode.
  31352. *
  31353. * | Value | Type | Description |
  31354. * | ----- | ------------------ | ----------- |
  31355. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  31356. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  31357. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  31358. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  31359. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  31360. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  31361. * | 7 | NEAREST_LINEAR | |
  31362. * | 8 | NEAREST_NEAREST | |
  31363. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  31364. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  31365. * | 11 | LINEAR_LINEAR | |
  31366. * | 12 | LINEAR_NEAREST | |
  31367. *
  31368. * > _mag_: magnification filter (close to the viewer)
  31369. * > _min_: minification filter (far from the viewer)
  31370. * > _mip_: filter used between mip map levels
  31371. *
  31372. */
  31373. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31374. if (!this._texture) {
  31375. return;
  31376. }
  31377. var scene = this.getScene();
  31378. if (!scene) {
  31379. return;
  31380. }
  31381. this._samplingMode = samplingMode;
  31382. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31383. };
  31384. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31385. x *= this.uScale;
  31386. y *= this.vScale;
  31387. x -= this.uRotationCenter * this.uScale;
  31388. y -= this.vRotationCenter * this.vScale;
  31389. z -= this.wRotationCenter;
  31390. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31391. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31392. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31393. t.z += this.wRotationCenter;
  31394. };
  31395. Texture.prototype.getTextureMatrix = function () {
  31396. var _this = this;
  31397. if (this.uOffset === this._cachedUOffset &&
  31398. this.vOffset === this._cachedVOffset &&
  31399. this.uScale === this._cachedUScale &&
  31400. this.vScale === this._cachedVScale &&
  31401. this.uAng === this._cachedUAng &&
  31402. this.vAng === this._cachedVAng &&
  31403. this.wAng === this._cachedWAng) {
  31404. return this._cachedTextureMatrix;
  31405. }
  31406. this._cachedUOffset = this.uOffset;
  31407. this._cachedVOffset = this.vOffset;
  31408. this._cachedUScale = this.uScale;
  31409. this._cachedVScale = this.vScale;
  31410. this._cachedUAng = this.uAng;
  31411. this._cachedVAng = this.vAng;
  31412. this._cachedWAng = this.wAng;
  31413. if (!this._cachedTextureMatrix) {
  31414. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31415. this._rowGenerationMatrix = new BABYLON.Matrix();
  31416. this._t0 = BABYLON.Vector3.Zero();
  31417. this._t1 = BABYLON.Vector3.Zero();
  31418. this._t2 = BABYLON.Vector3.Zero();
  31419. }
  31420. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31421. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31422. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31423. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31424. this._t1.subtractInPlace(this._t0);
  31425. this._t2.subtractInPlace(this._t0);
  31426. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31427. this._cachedTextureMatrix.m[0] = this._t1.x;
  31428. this._cachedTextureMatrix.m[1] = this._t1.y;
  31429. this._cachedTextureMatrix.m[2] = this._t1.z;
  31430. this._cachedTextureMatrix.m[4] = this._t2.x;
  31431. this._cachedTextureMatrix.m[5] = this._t2.y;
  31432. this._cachedTextureMatrix.m[6] = this._t2.z;
  31433. this._cachedTextureMatrix.m[8] = this._t0.x;
  31434. this._cachedTextureMatrix.m[9] = this._t0.y;
  31435. this._cachedTextureMatrix.m[10] = this._t0.z;
  31436. var scene = this.getScene();
  31437. if (!scene) {
  31438. return this._cachedTextureMatrix;
  31439. }
  31440. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31441. return mat.hasTexture(_this);
  31442. });
  31443. return this._cachedTextureMatrix;
  31444. };
  31445. Texture.prototype.getReflectionTextureMatrix = function () {
  31446. var _this = this;
  31447. var scene = this.getScene();
  31448. if (!scene) {
  31449. return this._cachedTextureMatrix;
  31450. }
  31451. if (this.uOffset === this._cachedUOffset &&
  31452. this.vOffset === this._cachedVOffset &&
  31453. this.uScale === this._cachedUScale &&
  31454. this.vScale === this._cachedVScale &&
  31455. this.coordinatesMode === this._cachedCoordinatesMode) {
  31456. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31457. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31458. return this._cachedTextureMatrix;
  31459. }
  31460. }
  31461. else {
  31462. return this._cachedTextureMatrix;
  31463. }
  31464. }
  31465. if (!this._cachedTextureMatrix) {
  31466. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31467. }
  31468. if (!this._projectionModeMatrix) {
  31469. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31470. }
  31471. this._cachedUOffset = this.uOffset;
  31472. this._cachedVOffset = this.vOffset;
  31473. this._cachedUScale = this.uScale;
  31474. this._cachedVScale = this.vScale;
  31475. this._cachedCoordinatesMode = this.coordinatesMode;
  31476. switch (this.coordinatesMode) {
  31477. case Texture.PLANAR_MODE:
  31478. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31479. this._cachedTextureMatrix[0] = this.uScale;
  31480. this._cachedTextureMatrix[5] = this.vScale;
  31481. this._cachedTextureMatrix[12] = this.uOffset;
  31482. this._cachedTextureMatrix[13] = this.vOffset;
  31483. break;
  31484. case Texture.PROJECTION_MODE:
  31485. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31486. this._projectionModeMatrix.m[0] = 0.5;
  31487. this._projectionModeMatrix.m[5] = -0.5;
  31488. this._projectionModeMatrix.m[10] = 0.0;
  31489. this._projectionModeMatrix.m[12] = 0.5;
  31490. this._projectionModeMatrix.m[13] = 0.5;
  31491. this._projectionModeMatrix.m[14] = 1.0;
  31492. this._projectionModeMatrix.m[15] = 1.0;
  31493. var projectionMatrix = scene.getProjectionMatrix();
  31494. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31495. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31496. break;
  31497. default:
  31498. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31499. break;
  31500. }
  31501. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31502. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31503. });
  31504. return this._cachedTextureMatrix;
  31505. };
  31506. Texture.prototype.clone = function () {
  31507. var _this = this;
  31508. return BABYLON.SerializationHelper.Clone(function () {
  31509. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31510. }, this);
  31511. };
  31512. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31513. get: function () {
  31514. if (!this._onLoadObservable) {
  31515. this._onLoadObservable = new BABYLON.Observable();
  31516. }
  31517. return this._onLoadObservable;
  31518. },
  31519. enumerable: true,
  31520. configurable: true
  31521. });
  31522. Texture.prototype.serialize = function () {
  31523. var serializationObject = _super.prototype.serialize.call(this);
  31524. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31525. serializationObject.base64String = this._buffer;
  31526. serializationObject.name = serializationObject.name.replace("data:", "");
  31527. }
  31528. serializationObject.invertY = this._invertY;
  31529. serializationObject.samplingMode = this.samplingMode;
  31530. return serializationObject;
  31531. };
  31532. Texture.prototype.getClassName = function () {
  31533. return "Texture";
  31534. };
  31535. Texture.prototype.dispose = function () {
  31536. _super.prototype.dispose.call(this);
  31537. if (this._onLoadObservable) {
  31538. this._onLoadObservable.clear();
  31539. this._onLoadObservable = null;
  31540. }
  31541. this._delayedOnLoad = null;
  31542. this._delayedOnError = null;
  31543. };
  31544. // Statics
  31545. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31546. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31547. if (onLoad === void 0) { onLoad = null; }
  31548. if (onError === void 0) { onError = null; }
  31549. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31550. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31551. };
  31552. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31553. if (parsedTexture.customType) {
  31554. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31555. // Update Sampling Mode
  31556. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31557. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31558. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31559. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31560. }
  31561. }
  31562. return parsedCustomTexture;
  31563. }
  31564. if (parsedTexture.isCube) {
  31565. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31566. }
  31567. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31568. return null;
  31569. }
  31570. var texture = BABYLON.SerializationHelper.Parse(function () {
  31571. var generateMipMaps = true;
  31572. if (parsedTexture.noMipmap) {
  31573. generateMipMaps = false;
  31574. }
  31575. if (parsedTexture.mirrorPlane) {
  31576. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31577. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31578. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31579. return mirrorTexture;
  31580. }
  31581. else if (parsedTexture.isRenderTarget) {
  31582. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31583. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31584. return renderTargetTexture;
  31585. }
  31586. else {
  31587. var texture;
  31588. if (parsedTexture.base64String) {
  31589. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31590. }
  31591. else {
  31592. var url = rootUrl + parsedTexture.name;
  31593. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31594. url = parsedTexture.url;
  31595. }
  31596. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31597. }
  31598. return texture;
  31599. }
  31600. }, parsedTexture, scene);
  31601. // Update Sampling Mode
  31602. if (parsedTexture.samplingMode) {
  31603. var sampling = parsedTexture.samplingMode;
  31604. if (texture._samplingMode !== sampling) {
  31605. texture.updateSamplingMode(sampling);
  31606. }
  31607. }
  31608. // Animations
  31609. if (parsedTexture.animations) {
  31610. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31611. var parsedAnimation = parsedTexture.animations[animationIndex];
  31612. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31613. }
  31614. }
  31615. return texture;
  31616. };
  31617. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31618. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31619. if (noMipmap === void 0) { noMipmap = false; }
  31620. if (invertY === void 0) { invertY = true; }
  31621. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31622. if (onLoad === void 0) { onLoad = null; }
  31623. if (onError === void 0) { onError = null; }
  31624. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31625. if (name.substr(0, 5) !== "data:") {
  31626. name = "data:" + name;
  31627. }
  31628. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31629. };
  31630. // Constants
  31631. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  31632. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  31633. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  31634. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  31635. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  31636. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  31637. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  31638. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  31639. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  31640. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  31641. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  31642. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  31643. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  31644. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  31645. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  31646. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  31647. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  31648. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  31649. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  31650. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  31651. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  31652. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  31653. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  31654. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  31655. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  31656. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  31657. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  31658. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  31659. /**
  31660. * 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
  31661. */
  31662. Texture.UseSerializedUrlIfAny = false;
  31663. __decorate([
  31664. BABYLON.serialize()
  31665. ], Texture.prototype, "url", void 0);
  31666. __decorate([
  31667. BABYLON.serialize()
  31668. ], Texture.prototype, "uOffset", void 0);
  31669. __decorate([
  31670. BABYLON.serialize()
  31671. ], Texture.prototype, "vOffset", void 0);
  31672. __decorate([
  31673. BABYLON.serialize()
  31674. ], Texture.prototype, "uScale", void 0);
  31675. __decorate([
  31676. BABYLON.serialize()
  31677. ], Texture.prototype, "vScale", void 0);
  31678. __decorate([
  31679. BABYLON.serialize()
  31680. ], Texture.prototype, "uAng", void 0);
  31681. __decorate([
  31682. BABYLON.serialize()
  31683. ], Texture.prototype, "vAng", void 0);
  31684. __decorate([
  31685. BABYLON.serialize()
  31686. ], Texture.prototype, "wAng", void 0);
  31687. __decorate([
  31688. BABYLON.serialize()
  31689. ], Texture.prototype, "uRotationCenter", void 0);
  31690. __decorate([
  31691. BABYLON.serialize()
  31692. ], Texture.prototype, "vRotationCenter", void 0);
  31693. __decorate([
  31694. BABYLON.serialize()
  31695. ], Texture.prototype, "wRotationCenter", void 0);
  31696. __decorate([
  31697. BABYLON.serialize()
  31698. ], Texture.prototype, "isBlocking", null);
  31699. return Texture;
  31700. }(BABYLON.BaseTexture));
  31701. BABYLON.Texture = Texture;
  31702. })(BABYLON || (BABYLON = {}));
  31703. //# sourceMappingURL=babylon.texture.js.map
  31704. var BABYLON;
  31705. (function (BABYLON) {
  31706. /**
  31707. * @hidden
  31708. **/
  31709. var _CreationDataStorage = /** @class */ (function () {
  31710. function _CreationDataStorage() {
  31711. }
  31712. return _CreationDataStorage;
  31713. }());
  31714. BABYLON._CreationDataStorage = _CreationDataStorage;
  31715. /**
  31716. * @hidden
  31717. **/
  31718. var _InstanceDataStorage = /** @class */ (function () {
  31719. function _InstanceDataStorage() {
  31720. this.visibleInstances = {};
  31721. this.renderIdForInstances = new Array();
  31722. this.batchCache = new _InstancesBatch();
  31723. this.instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31724. }
  31725. return _InstanceDataStorage;
  31726. }());
  31727. /**
  31728. * @hidden
  31729. **/
  31730. var _InstancesBatch = /** @class */ (function () {
  31731. function _InstancesBatch() {
  31732. this.mustReturn = false;
  31733. this.visibleInstances = new Array();
  31734. this.renderSelf = new Array();
  31735. }
  31736. return _InstancesBatch;
  31737. }());
  31738. BABYLON._InstancesBatch = _InstancesBatch;
  31739. /**
  31740. * Class used to represent renderable models
  31741. */
  31742. var Mesh = /** @class */ (function (_super) {
  31743. __extends(Mesh, _super);
  31744. /**
  31745. * @constructor
  31746. * @param name The value used by scene.getMeshByName() to do a lookup.
  31747. * @param scene The scene to add this mesh to.
  31748. * @param parent The parent of this mesh, if it has one
  31749. * @param source An optional Mesh from which geometry is shared, cloned.
  31750. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31751. * When false, achieved by calling a clone(), also passing False.
  31752. * This will make creation of children, recursive.
  31753. * @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31754. */
  31755. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31756. if (scene === void 0) { scene = null; }
  31757. if (parent === void 0) { parent = null; }
  31758. if (source === void 0) { source = null; }
  31759. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31760. var _this = _super.call(this, name, scene) || this;
  31761. // Members
  31762. /**
  31763. * Gets the delay loading state of the mesh (when delay loading is turned on)
  31764. * @see http://doc.babylonjs.com/how_to/using_the_incremental_loading_system
  31765. */
  31766. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31767. /**
  31768. * Gets the list of instances created from this mesh
  31769. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  31770. */
  31771. _this.instances = new Array();
  31772. _this._LODLevels = new Array();
  31773. /** @hidden */
  31774. _this._instanceDataStorage = new _InstanceDataStorage();
  31775. // Use by builder only to know what orientation were the mesh build in.
  31776. /** @hidden */
  31777. _this._originalBuilderSideOrientation = Mesh.DEFAULTSIDE;
  31778. /**
  31779. * Use this property to change the original side orientation defined at construction time
  31780. */
  31781. _this.overrideMaterialSideOrientation = null;
  31782. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31783. // Will be used to save a source mesh reference, If any
  31784. _this._source = null;
  31785. scene = _this.getScene();
  31786. if (source) {
  31787. // Geometry
  31788. if (source._geometry) {
  31789. source._geometry.applyToMesh(_this);
  31790. }
  31791. // Deep copy
  31792. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31793. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  31794. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  31795. ], ["_poseMatrix"]);
  31796. // Source mesh
  31797. _this._source = source;
  31798. // Construction Params
  31799. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  31800. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  31801. _this._creationDataStorage = source._creationDataStorage;
  31802. // Animation ranges
  31803. if (_this._source._ranges) {
  31804. var ranges = _this._source._ranges;
  31805. for (var name in ranges) {
  31806. if (!ranges.hasOwnProperty(name)) {
  31807. continue;
  31808. }
  31809. if (!ranges[name]) {
  31810. continue;
  31811. }
  31812. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  31813. }
  31814. }
  31815. // Metadata
  31816. if (source.metadata && source.metadata.clone) {
  31817. _this.metadata = source.metadata.clone();
  31818. }
  31819. else {
  31820. _this.metadata = source.metadata;
  31821. }
  31822. // Tags
  31823. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31824. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31825. }
  31826. // Parent
  31827. _this.parent = source.parent;
  31828. // Pivot
  31829. _this.setPivotMatrix(source.getPivotMatrix());
  31830. _this.id = name + "." + source.id;
  31831. // Material
  31832. _this.material = source.material;
  31833. var index;
  31834. if (!doNotCloneChildren) {
  31835. // Children
  31836. var directDescendants = source.getDescendants(true);
  31837. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31838. var child = directDescendants[index_1];
  31839. if (child.clone) {
  31840. child.clone(name + "." + child.name, _this);
  31841. }
  31842. }
  31843. }
  31844. // Physics clone
  31845. var physicsEngine = _this.getScene().getPhysicsEngine();
  31846. if (clonePhysicsImpostor && physicsEngine) {
  31847. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31848. if (impostor) {
  31849. _this.physicsImpostor = impostor.clone(_this);
  31850. }
  31851. }
  31852. // Particles
  31853. for (index = 0; index < scene.particleSystems.length; index++) {
  31854. var system = scene.particleSystems[index];
  31855. if (system.emitter === source) {
  31856. system.clone(system.name, _this);
  31857. }
  31858. }
  31859. _this.refreshBoundingInfo();
  31860. _this.computeWorldMatrix(true);
  31861. }
  31862. // Parent
  31863. if (parent !== null) {
  31864. _this.parent = parent;
  31865. }
  31866. return _this;
  31867. }
  31868. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  31869. /**
  31870. * An event triggered before rendering the mesh
  31871. */
  31872. get: function () {
  31873. if (!this._onBeforeRenderObservable) {
  31874. this._onBeforeRenderObservable = new BABYLON.Observable();
  31875. }
  31876. return this._onBeforeRenderObservable;
  31877. },
  31878. enumerable: true,
  31879. configurable: true
  31880. });
  31881. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  31882. /**
  31883. * An event triggered after rendering the mesh
  31884. */
  31885. get: function () {
  31886. if (!this._onAfterRenderObservable) {
  31887. this._onAfterRenderObservable = new BABYLON.Observable();
  31888. }
  31889. return this._onAfterRenderObservable;
  31890. },
  31891. enumerable: true,
  31892. configurable: true
  31893. });
  31894. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  31895. /**
  31896. * An event triggered before drawing the mesh
  31897. */
  31898. get: function () {
  31899. if (!this._onBeforeDrawObservable) {
  31900. this._onBeforeDrawObservable = new BABYLON.Observable();
  31901. }
  31902. return this._onBeforeDrawObservable;
  31903. },
  31904. enumerable: true,
  31905. configurable: true
  31906. });
  31907. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31908. /**
  31909. * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
  31910. */
  31911. set: function (callback) {
  31912. if (this._onBeforeDrawObserver) {
  31913. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31914. }
  31915. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31916. },
  31917. enumerable: true,
  31918. configurable: true
  31919. });
  31920. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31921. /**
  31922. * Gets or sets the morph target manager
  31923. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  31924. */
  31925. get: function () {
  31926. return this._morphTargetManager;
  31927. },
  31928. set: function (value) {
  31929. if (this._morphTargetManager === value) {
  31930. return;
  31931. }
  31932. this._morphTargetManager = value;
  31933. this._syncGeometryWithMorphTargetManager();
  31934. },
  31935. enumerable: true,
  31936. configurable: true
  31937. });
  31938. Object.defineProperty(Mesh.prototype, "source", {
  31939. /**
  31940. * Gets the source mesh (the one used to clone this one from)
  31941. */
  31942. get: function () {
  31943. return this._source;
  31944. },
  31945. enumerable: true,
  31946. configurable: true
  31947. });
  31948. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31949. /**
  31950. * Gets or sets a boolean indicating that this mesh does not use index buffer
  31951. */
  31952. get: function () {
  31953. return this._unIndexed;
  31954. },
  31955. set: function (value) {
  31956. if (this._unIndexed !== value) {
  31957. this._unIndexed = value;
  31958. this._markSubMeshesAsAttributesDirty();
  31959. }
  31960. },
  31961. enumerable: true,
  31962. configurable: true
  31963. });
  31964. // Methods
  31965. /**
  31966. * Gets the class name
  31967. * @returns the string "Mesh".
  31968. */
  31969. Mesh.prototype.getClassName = function () {
  31970. return "Mesh";
  31971. };
  31972. /**
  31973. * Returns a description of this mesh
  31974. * @param fullDetails define if full details about this mesh must be used
  31975. * @returns a descriptive string representing this mesh
  31976. */
  31977. Mesh.prototype.toString = function (fullDetails) {
  31978. var ret = _super.prototype.toString.call(this, fullDetails);
  31979. ret += ", n vertices: " + this.getTotalVertices();
  31980. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31981. if (this.animations) {
  31982. for (var i = 0; i < this.animations.length; i++) {
  31983. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31984. }
  31985. }
  31986. if (fullDetails) {
  31987. if (this._geometry) {
  31988. var ib = this.getIndices();
  31989. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31990. if (vb && ib) {
  31991. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31992. }
  31993. }
  31994. else {
  31995. ret += ", flat shading: UNKNOWN";
  31996. }
  31997. }
  31998. return ret;
  31999. };
  32000. /** @hidden */
  32001. Mesh.prototype._unBindEffect = function () {
  32002. _super.prototype._unBindEffect.call(this);
  32003. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  32004. var instance = _a[_i];
  32005. instance._unBindEffect();
  32006. }
  32007. };
  32008. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  32009. /**
  32010. * Gets a boolean indicating if this mesh has LOD
  32011. */
  32012. get: function () {
  32013. return this._LODLevels.length > 0;
  32014. },
  32015. enumerable: true,
  32016. configurable: true
  32017. });
  32018. /**
  32019. * Gets the list of MeshLODLevel associated with the current mesh
  32020. * @returns an array of MeshLODLevel
  32021. */
  32022. Mesh.prototype.getLODLevels = function () {
  32023. return this._LODLevels;
  32024. };
  32025. Mesh.prototype._sortLODLevels = function () {
  32026. this._LODLevels.sort(function (a, b) {
  32027. if (a.distance < b.distance) {
  32028. return 1;
  32029. }
  32030. if (a.distance > b.distance) {
  32031. return -1;
  32032. }
  32033. return 0;
  32034. });
  32035. };
  32036. /**
  32037. * Add a mesh as LOD level triggered at the given distance.
  32038. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32039. * @param distance The distance from the center of the object to show this level
  32040. * @param mesh The mesh to be added as LOD level (can be null)
  32041. * @return This mesh (for chaining)
  32042. */
  32043. Mesh.prototype.addLODLevel = function (distance, mesh) {
  32044. if (mesh && mesh._masterMesh) {
  32045. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  32046. return this;
  32047. }
  32048. var level = new BABYLON.MeshLODLevel(distance, mesh);
  32049. this._LODLevels.push(level);
  32050. if (mesh) {
  32051. mesh._masterMesh = this;
  32052. }
  32053. this._sortLODLevels();
  32054. return this;
  32055. };
  32056. /**
  32057. * Returns the LOD level mesh at the passed distance or null if not found.
  32058. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32059. * @param distance The distance from the center of the object to show this level
  32060. * @returns a Mesh or `null`
  32061. */
  32062. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  32063. for (var index = 0; index < this._LODLevels.length; index++) {
  32064. var level = this._LODLevels[index];
  32065. if (level.distance === distance) {
  32066. return level.mesh;
  32067. }
  32068. }
  32069. return null;
  32070. };
  32071. /**
  32072. * Remove a mesh from the LOD array
  32073. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32074. * @param mesh defines the mesh to be removed
  32075. * @return This mesh (for chaining)
  32076. */
  32077. Mesh.prototype.removeLODLevel = function (mesh) {
  32078. for (var index = 0; index < this._LODLevels.length; index++) {
  32079. if (this._LODLevels[index].mesh === mesh) {
  32080. this._LODLevels.splice(index, 1);
  32081. if (mesh) {
  32082. mesh._masterMesh = null;
  32083. }
  32084. }
  32085. }
  32086. this._sortLODLevels();
  32087. return this;
  32088. };
  32089. /**
  32090. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  32091. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32092. * @param camera defines the camera to use to compute distance
  32093. * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh
  32094. * @return This mesh (for chaining)
  32095. */
  32096. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  32097. if (!this._LODLevels || this._LODLevels.length === 0) {
  32098. return this;
  32099. }
  32100. var bSphere;
  32101. if (boundingSphere) {
  32102. bSphere = boundingSphere;
  32103. }
  32104. else {
  32105. var boundingInfo = this.getBoundingInfo();
  32106. bSphere = boundingInfo.boundingSphere;
  32107. }
  32108. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  32109. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  32110. if (this.onLODLevelSelection) {
  32111. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  32112. }
  32113. return this;
  32114. }
  32115. for (var index = 0; index < this._LODLevels.length; index++) {
  32116. var level = this._LODLevels[index];
  32117. if (level.distance < distanceToCamera) {
  32118. if (level.mesh) {
  32119. level.mesh._preActivate();
  32120. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  32121. }
  32122. if (this.onLODLevelSelection) {
  32123. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  32124. }
  32125. return level.mesh;
  32126. }
  32127. }
  32128. if (this.onLODLevelSelection) {
  32129. this.onLODLevelSelection(distanceToCamera, this, this);
  32130. }
  32131. return this;
  32132. };
  32133. Object.defineProperty(Mesh.prototype, "geometry", {
  32134. /**
  32135. * Gets the mesh internal Geometry object
  32136. */
  32137. get: function () {
  32138. return this._geometry;
  32139. },
  32140. enumerable: true,
  32141. configurable: true
  32142. });
  32143. /**
  32144. * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  32145. * @returns the total number of vertices
  32146. */
  32147. Mesh.prototype.getTotalVertices = function () {
  32148. if (this._geometry === null || this._geometry === undefined) {
  32149. return 0;
  32150. }
  32151. return this._geometry.getTotalVertices();
  32152. };
  32153. /**
  32154. * Returns the content of an associated vertex buffer
  32155. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32156. * - BABYLON.VertexBuffer.PositionKind
  32157. * - BABYLON.VertexBuffer.UVKind
  32158. * - BABYLON.VertexBuffer.UV2Kind
  32159. * - BABYLON.VertexBuffer.UV3Kind
  32160. * - BABYLON.VertexBuffer.UV4Kind
  32161. * - BABYLON.VertexBuffer.UV5Kind
  32162. * - BABYLON.VertexBuffer.UV6Kind
  32163. * - BABYLON.VertexBuffer.ColorKind
  32164. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32165. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32166. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32167. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32168. * @param copyWhenShared defines a boolean indicating that if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one
  32169. * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
  32170. * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind.
  32171. */
  32172. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  32173. if (!this._geometry) {
  32174. return null;
  32175. }
  32176. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  32177. };
  32178. /**
  32179. * Returns the mesh VertexBuffer object from the requested `kind`
  32180. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32181. * - BABYLON.VertexBuffer.PositionKind
  32182. * - BABYLON.VertexBuffer.UVKind
  32183. * - BABYLON.VertexBuffer.UV2Kind
  32184. * - BABYLON.VertexBuffer.UV3Kind
  32185. * - BABYLON.VertexBuffer.UV4Kind
  32186. * - BABYLON.VertexBuffer.UV5Kind
  32187. * - BABYLON.VertexBuffer.UV6Kind
  32188. * - BABYLON.VertexBuffer.ColorKind
  32189. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32190. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32191. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32192. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32193. * @returns a FloatArray or null if the mesh has no vertex buffer for this kind.
  32194. */
  32195. Mesh.prototype.getVertexBuffer = function (kind) {
  32196. if (!this._geometry) {
  32197. return null;
  32198. }
  32199. return this._geometry.getVertexBuffer(kind);
  32200. };
  32201. /**
  32202. * Tests if a specific vertex buffer is associated with this mesh
  32203. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  32204. * - BABYLON.VertexBuffer.PositionKind
  32205. * - BABYLON.VertexBuffer.UVKind
  32206. * - BABYLON.VertexBuffer.UV2Kind
  32207. * - BABYLON.VertexBuffer.UV3Kind
  32208. * - BABYLON.VertexBuffer.UV4Kind
  32209. * - BABYLON.VertexBuffer.UV5Kind
  32210. * - BABYLON.VertexBuffer.UV6Kind
  32211. * - BABYLON.VertexBuffer.ColorKind
  32212. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32213. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32214. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32215. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32216. * @returns a boolean
  32217. */
  32218. Mesh.prototype.isVerticesDataPresent = function (kind) {
  32219. if (!this._geometry) {
  32220. if (this._delayInfo) {
  32221. return this._delayInfo.indexOf(kind) !== -1;
  32222. }
  32223. return false;
  32224. }
  32225. return this._geometry.isVerticesDataPresent(kind);
  32226. };
  32227. /**
  32228. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  32229. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  32230. * - BABYLON.VertexBuffer.PositionKind
  32231. * - BABYLON.VertexBuffer.UVKind
  32232. * - BABYLON.VertexBuffer.UV2Kind
  32233. * - BABYLON.VertexBuffer.UV3Kind
  32234. * - BABYLON.VertexBuffer.UV4Kind
  32235. * - BABYLON.VertexBuffer.UV5Kind
  32236. * - BABYLON.VertexBuffer.UV6Kind
  32237. * - BABYLON.VertexBuffer.ColorKind
  32238. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32239. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32240. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32241. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32242. * @returns a boolean
  32243. */
  32244. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  32245. if (!this._geometry) {
  32246. if (this._delayInfo) {
  32247. return this._delayInfo.indexOf(kind) !== -1;
  32248. }
  32249. return false;
  32250. }
  32251. return this._geometry.isVertexBufferUpdatable(kind);
  32252. };
  32253. /**
  32254. * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh.
  32255. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32256. * - BABYLON.VertexBuffer.PositionKind
  32257. * - BABYLON.VertexBuffer.UVKind
  32258. * - BABYLON.VertexBuffer.UV2Kind
  32259. * - BABYLON.VertexBuffer.UV3Kind
  32260. * - BABYLON.VertexBuffer.UV4Kind
  32261. * - BABYLON.VertexBuffer.UV5Kind
  32262. * - BABYLON.VertexBuffer.UV6Kind
  32263. * - BABYLON.VertexBuffer.ColorKind
  32264. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32265. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32266. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32267. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32268. * @returns an array of strings
  32269. */
  32270. Mesh.prototype.getVerticesDataKinds = function () {
  32271. if (!this._geometry) {
  32272. var result = new Array();
  32273. if (this._delayInfo) {
  32274. this._delayInfo.forEach(function (kind, index, array) {
  32275. result.push(kind);
  32276. });
  32277. }
  32278. return result;
  32279. }
  32280. return this._geometry.getVerticesDataKinds();
  32281. };
  32282. /**
  32283. * Returns a positive integer : the total number of indices in this mesh geometry.
  32284. * @returns the numner of indices or zero if the mesh has no geometry.
  32285. */
  32286. Mesh.prototype.getTotalIndices = function () {
  32287. if (!this._geometry) {
  32288. return 0;
  32289. }
  32290. return this._geometry.getTotalIndices();
  32291. };
  32292. /**
  32293. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  32294. * @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.
  32295. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  32296. * @returns the indices array or an empty array if the mesh has no geometry
  32297. */
  32298. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  32299. if (!this._geometry) {
  32300. return [];
  32301. }
  32302. return this._geometry.getIndices(copyWhenShared, forceCopy);
  32303. };
  32304. Object.defineProperty(Mesh.prototype, "isBlocked", {
  32305. get: function () {
  32306. return this._masterMesh !== null && this._masterMesh !== undefined;
  32307. },
  32308. enumerable: true,
  32309. configurable: true
  32310. });
  32311. /**
  32312. * Determine if the current mesh is ready to be rendered
  32313. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  32314. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  32315. * @returns true if all associated assets are ready (material, textures, shaders)
  32316. */
  32317. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  32318. if (completeCheck === void 0) { completeCheck = false; }
  32319. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  32320. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32321. return false;
  32322. }
  32323. if (!_super.prototype.isReady.call(this, completeCheck)) {
  32324. return false;
  32325. }
  32326. if (!this.subMeshes || this.subMeshes.length === 0) {
  32327. return true;
  32328. }
  32329. if (!completeCheck) {
  32330. return true;
  32331. }
  32332. var engine = this.getEngine();
  32333. var scene = this.getScene();
  32334. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  32335. this.computeWorldMatrix();
  32336. var mat = this.material || scene.defaultMaterial;
  32337. if (mat) {
  32338. if (mat.storeEffectOnSubMeshes) {
  32339. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32340. var subMesh = _a[_i];
  32341. var effectiveMaterial = subMesh.getMaterial();
  32342. if (effectiveMaterial) {
  32343. if (effectiveMaterial.storeEffectOnSubMeshes) {
  32344. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32345. return false;
  32346. }
  32347. }
  32348. else {
  32349. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32350. return false;
  32351. }
  32352. }
  32353. }
  32354. }
  32355. }
  32356. else {
  32357. if (!mat.isReady(this, hardwareInstancedRendering)) {
  32358. return false;
  32359. }
  32360. }
  32361. }
  32362. // Shadows
  32363. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  32364. var light = _c[_b];
  32365. var generator = light.getShadowGenerator();
  32366. if (generator) {
  32367. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  32368. var subMesh = _e[_d];
  32369. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  32370. return false;
  32371. }
  32372. }
  32373. }
  32374. }
  32375. // LOD
  32376. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  32377. var lod = _g[_f];
  32378. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  32379. return false;
  32380. }
  32381. }
  32382. return true;
  32383. };
  32384. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  32385. /**
  32386. * Gets a boolean indicating if the normals aren't to be recomputed on next mesh `positions` array update. This property is pertinent only for updatable parametric shapes.
  32387. */
  32388. get: function () {
  32389. return this._areNormalsFrozen;
  32390. },
  32391. enumerable: true,
  32392. configurable: true
  32393. });
  32394. /**
  32395. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It prevents the mesh normals from being recomputed on next `positions` array update.
  32396. * @returns the current mesh
  32397. */
  32398. Mesh.prototype.freezeNormals = function () {
  32399. this._areNormalsFrozen = true;
  32400. return this;
  32401. };
  32402. /**
  32403. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It reactivates the mesh normals computation if it was previously frozen
  32404. * @returns the current mesh
  32405. */
  32406. Mesh.prototype.unfreezeNormals = function () {
  32407. this._areNormalsFrozen = false;
  32408. return this;
  32409. };
  32410. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  32411. /**
  32412. * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  32413. */
  32414. set: function (count) {
  32415. this._instanceDataStorage.overridenInstanceCount = count;
  32416. },
  32417. enumerable: true,
  32418. configurable: true
  32419. });
  32420. // Methods
  32421. /** @hidden */
  32422. Mesh.prototype._preActivate = function () {
  32423. var sceneRenderId = this.getScene().getRenderId();
  32424. if (this._preActivateId === sceneRenderId) {
  32425. return this;
  32426. }
  32427. this._preActivateId = sceneRenderId;
  32428. this._instanceDataStorage.visibleInstances = null;
  32429. return this;
  32430. };
  32431. /** @hidden */
  32432. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  32433. if (this._instanceDataStorage.visibleInstances) {
  32434. this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId = renderId;
  32435. }
  32436. return this;
  32437. };
  32438. /** @hidden */
  32439. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32440. if (!this._instanceDataStorage.visibleInstances) {
  32441. this._instanceDataStorage.visibleInstances = {};
  32442. this._instanceDataStorage.visibleInstances.defaultRenderId = renderId;
  32443. this._instanceDataStorage.visibleInstances.selfDefaultRenderId = this._renderId;
  32444. }
  32445. if (!this._instanceDataStorage.visibleInstances[renderId]) {
  32446. this._instanceDataStorage.visibleInstances[renderId] = new Array();
  32447. }
  32448. this._instanceDataStorage.visibleInstances[renderId].push(instance);
  32449. return this;
  32450. };
  32451. /**
  32452. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32453. * This means the mesh underlying bounding box and sphere are recomputed.
  32454. * @returns the current mesh
  32455. */
  32456. Mesh.prototype.refreshBoundingInfo = function () {
  32457. return this._refreshBoundingInfo(false);
  32458. };
  32459. /** @hidden */
  32460. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32461. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32462. return this;
  32463. }
  32464. var data = this._getPositionData(applySkeleton);
  32465. if (data) {
  32466. var bias = this.geometry ? this.geometry.boundingBias : null;
  32467. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  32468. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32469. }
  32470. if (this.subMeshes) {
  32471. for (var index = 0; index < this.subMeshes.length; index++) {
  32472. this.subMeshes[index].refreshBoundingInfo();
  32473. }
  32474. }
  32475. this._updateBoundingInfo();
  32476. return this;
  32477. };
  32478. Mesh.prototype._getPositionData = function (applySkeleton) {
  32479. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32480. if (data && applySkeleton && this.skeleton) {
  32481. data = BABYLON.Tools.Slice(data);
  32482. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32483. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32484. if (matricesWeightsData && matricesIndicesData) {
  32485. var needExtras = this.numBoneInfluencers > 4;
  32486. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32487. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32488. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32489. var tempVector = BABYLON.Tmp.Vector3[0];
  32490. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32491. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32492. var matWeightIdx = 0;
  32493. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32494. finalMatrix.reset();
  32495. var inf;
  32496. var weight;
  32497. for (inf = 0; inf < 4; inf++) {
  32498. weight = matricesWeightsData[matWeightIdx + inf];
  32499. if (weight > 0) {
  32500. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32501. finalMatrix.addToSelf(tempMatrix);
  32502. }
  32503. }
  32504. if (needExtras) {
  32505. for (inf = 0; inf < 4; inf++) {
  32506. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32507. if (weight > 0) {
  32508. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32509. finalMatrix.addToSelf(tempMatrix);
  32510. }
  32511. }
  32512. }
  32513. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32514. tempVector.toArray(data, index);
  32515. }
  32516. }
  32517. }
  32518. return data;
  32519. };
  32520. /** @hidden */
  32521. Mesh.prototype._createGlobalSubMesh = function (force) {
  32522. var totalVertices = this.getTotalVertices();
  32523. if (!totalVertices || !this.getIndices()) {
  32524. return null;
  32525. }
  32526. // Check if we need to recreate the submeshes
  32527. if (this.subMeshes && this.subMeshes.length > 0) {
  32528. var ib = this.getIndices();
  32529. if (!ib) {
  32530. return null;
  32531. }
  32532. var totalIndices = ib.length;
  32533. var needToRecreate = false;
  32534. if (force) {
  32535. needToRecreate = true;
  32536. }
  32537. else {
  32538. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32539. var submesh = _a[_i];
  32540. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32541. needToRecreate = true;
  32542. break;
  32543. }
  32544. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32545. needToRecreate = true;
  32546. break;
  32547. }
  32548. }
  32549. }
  32550. if (!needToRecreate) {
  32551. return this.subMeshes[0];
  32552. }
  32553. }
  32554. this.releaseSubMeshes();
  32555. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32556. };
  32557. /**
  32558. * This function will subdivide the mesh into multiple submeshes
  32559. * @param count defines the expected number of submeshes
  32560. */
  32561. Mesh.prototype.subdivide = function (count) {
  32562. if (count < 1) {
  32563. return;
  32564. }
  32565. var totalIndices = this.getTotalIndices();
  32566. var subdivisionSize = (totalIndices / count) | 0;
  32567. var offset = 0;
  32568. // Ensure that subdivisionSize is a multiple of 3
  32569. while (subdivisionSize % 3 !== 0) {
  32570. subdivisionSize++;
  32571. }
  32572. this.releaseSubMeshes();
  32573. for (var index = 0; index < count; index++) {
  32574. if (offset >= totalIndices) {
  32575. break;
  32576. }
  32577. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32578. offset += subdivisionSize;
  32579. }
  32580. this.synchronizeInstances();
  32581. };
  32582. /**
  32583. * Copy a FloatArray into a specific associated vertex buffer
  32584. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  32585. * - BABYLON.VertexBuffer.PositionKind
  32586. * - BABYLON.VertexBuffer.UVKind
  32587. * - BABYLON.VertexBuffer.UV2Kind
  32588. * - BABYLON.VertexBuffer.UV3Kind
  32589. * - BABYLON.VertexBuffer.UV4Kind
  32590. * - BABYLON.VertexBuffer.UV5Kind
  32591. * - BABYLON.VertexBuffer.UV6Kind
  32592. * - BABYLON.VertexBuffer.ColorKind
  32593. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32594. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32595. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32596. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32597. * @param data defines the data source
  32598. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  32599. * @param stride defines the data stride size (can be null)
  32600. * @returns the current mesh
  32601. */
  32602. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32603. if (updatable === void 0) { updatable = false; }
  32604. if (!this._geometry) {
  32605. var vertexData = new BABYLON.VertexData();
  32606. vertexData.set(data, kind);
  32607. var scene = this.getScene();
  32608. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32609. }
  32610. else {
  32611. this._geometry.setVerticesData(kind, data, updatable, stride);
  32612. }
  32613. return this;
  32614. };
  32615. /**
  32616. * Flags an associated vertex buffer as updatable
  32617. * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values :
  32618. * - BABYLON.VertexBuffer.PositionKind
  32619. * - BABYLON.VertexBuffer.UVKind
  32620. * - BABYLON.VertexBuffer.UV2Kind
  32621. * - BABYLON.VertexBuffer.UV3Kind
  32622. * - BABYLON.VertexBuffer.UV4Kind
  32623. * - BABYLON.VertexBuffer.UV5Kind
  32624. * - BABYLON.VertexBuffer.UV6Kind
  32625. * - BABYLON.VertexBuffer.ColorKind
  32626. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32627. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32628. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32629. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32630. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  32631. */
  32632. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32633. if (updatable === void 0) { updatable = true; }
  32634. var vb = this.getVertexBuffer(kind);
  32635. if (!vb || vb.isUpdatable() === updatable) {
  32636. return;
  32637. }
  32638. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32639. };
  32640. /**
  32641. * Sets the mesh global Vertex Buffer
  32642. * @param buffer defines the buffer to use
  32643. * @returns the current mesh
  32644. */
  32645. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32646. if (!this._geometry) {
  32647. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32648. }
  32649. this._geometry.setVerticesBuffer(buffer);
  32650. return this;
  32651. };
  32652. /**
  32653. * Update a specific associated vertex buffer
  32654. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  32655. * - BABYLON.VertexBuffer.PositionKind
  32656. * - BABYLON.VertexBuffer.UVKind
  32657. * - BABYLON.VertexBuffer.UV2Kind
  32658. * - BABYLON.VertexBuffer.UV3Kind
  32659. * - BABYLON.VertexBuffer.UV4Kind
  32660. * - BABYLON.VertexBuffer.UV5Kind
  32661. * - BABYLON.VertexBuffer.UV6Kind
  32662. * - BABYLON.VertexBuffer.ColorKind
  32663. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32664. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32665. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32666. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32667. * @param data defines the data source
  32668. * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
  32669. * @param makeItUnique defines if the geometry associated with the mesh must be cloned to make the change only for this mesh (and not all meshes associated with the same geometry)
  32670. * @returns the current mesh
  32671. */
  32672. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32673. if (!this._geometry) {
  32674. return this;
  32675. }
  32676. if (!makeItUnique) {
  32677. this._geometry.updateVerticesData(kind, data, updateExtends);
  32678. }
  32679. else {
  32680. this.makeGeometryUnique();
  32681. this.updateVerticesData(kind, data, updateExtends, false);
  32682. }
  32683. return this;
  32684. };
  32685. /**
  32686. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32687. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32688. * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything
  32689. * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update
  32690. * @returns the current mesh
  32691. */
  32692. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32693. if (computeNormals === void 0) { computeNormals = true; }
  32694. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32695. if (!positions) {
  32696. return this;
  32697. }
  32698. positionFunction(positions);
  32699. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32700. if (computeNormals) {
  32701. var indices = this.getIndices();
  32702. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32703. if (!normals) {
  32704. return this;
  32705. }
  32706. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32707. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32708. }
  32709. return this;
  32710. };
  32711. /**
  32712. * Creates a un-shared specific occurence of the geometry for the mesh.
  32713. * @returns the current mesh
  32714. */
  32715. Mesh.prototype.makeGeometryUnique = function () {
  32716. if (!this._geometry) {
  32717. return this;
  32718. }
  32719. var oldGeometry = this._geometry;
  32720. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32721. oldGeometry.releaseForMesh(this, true);
  32722. geometry.applyToMesh(this);
  32723. return this;
  32724. };
  32725. /**
  32726. * Set the index buffer of this mesh
  32727. * @param indices defines the source data
  32728. * @param totalVertices defines the total number of vertices referenced by this index data (can be null)
  32729. * @param updatable defines if the updated index buffer must be flagged as updatable (default is false)
  32730. * @returns the current mesh
  32731. */
  32732. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32733. if (totalVertices === void 0) { totalVertices = null; }
  32734. if (updatable === void 0) { updatable = false; }
  32735. if (!this._geometry) {
  32736. var vertexData = new BABYLON.VertexData();
  32737. vertexData.indices = indices;
  32738. var scene = this.getScene();
  32739. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32740. }
  32741. else {
  32742. this._geometry.setIndices(indices, totalVertices, updatable);
  32743. }
  32744. return this;
  32745. };
  32746. /**
  32747. * Update the current index buffer
  32748. * @param indices defines the source data
  32749. * @param offset defines the offset in the index buffer where to store the new data (can be null)
  32750. * @returns the current mesh
  32751. */
  32752. Mesh.prototype.updateIndices = function (indices, offset) {
  32753. if (!this._geometry) {
  32754. return this;
  32755. }
  32756. this._geometry.updateIndices(indices, offset);
  32757. return this;
  32758. };
  32759. /**
  32760. * Invert the geometry to move from a right handed system to a left handed one.
  32761. * @returns the current mesh
  32762. */
  32763. Mesh.prototype.toLeftHanded = function () {
  32764. if (!this._geometry) {
  32765. return this;
  32766. }
  32767. this._geometry.toLeftHanded();
  32768. return this;
  32769. };
  32770. /** @hidden */
  32771. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32772. if (!this._geometry) {
  32773. return this;
  32774. }
  32775. var engine = this.getScene().getEngine();
  32776. // Wireframe
  32777. var indexToBind;
  32778. if (this._unIndexed) {
  32779. indexToBind = null;
  32780. }
  32781. else {
  32782. switch (fillMode) {
  32783. case BABYLON.Material.PointFillMode:
  32784. indexToBind = null;
  32785. break;
  32786. case BABYLON.Material.WireFrameFillMode:
  32787. indexToBind = subMesh._getLinesIndexBuffer(this.getIndices(), engine);
  32788. break;
  32789. default:
  32790. case BABYLON.Material.TriangleFillMode:
  32791. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32792. break;
  32793. }
  32794. }
  32795. // VBOs
  32796. this._geometry._bind(effect, indexToBind);
  32797. return this;
  32798. };
  32799. /** @hidden */
  32800. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32801. if (alternate === void 0) { alternate = false; }
  32802. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32803. return this;
  32804. }
  32805. if (this._onBeforeDrawObservable) {
  32806. this._onBeforeDrawObservable.notifyObservers(this);
  32807. }
  32808. var scene = this.getScene();
  32809. var engine = scene.getEngine();
  32810. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32811. // or triangles as points
  32812. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32813. }
  32814. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32815. // Triangles as wireframe
  32816. engine.drawElementsType(fillMode, 0, subMesh._linesIndexCount, instancesCount);
  32817. }
  32818. else {
  32819. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32820. }
  32821. if (scene._isAlternateRenderingEnabled && !alternate) {
  32822. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32823. if (!effect || !scene.activeCamera) {
  32824. return this;
  32825. }
  32826. scene._switchToAlternateCameraConfiguration(true);
  32827. this._effectiveMaterial.bindView(effect);
  32828. this._effectiveMaterial.bindViewProjection(effect);
  32829. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32830. this._draw(subMesh, fillMode, instancesCount, true);
  32831. engine.setViewport(scene.activeCamera.viewport);
  32832. scene._switchToAlternateCameraConfiguration(false);
  32833. this._effectiveMaterial.bindView(effect);
  32834. this._effectiveMaterial.bindViewProjection(effect);
  32835. }
  32836. return this;
  32837. };
  32838. /**
  32839. * Registers for this mesh a javascript function called just before the rendering process
  32840. * @param func defines the function to call before rendering this mesh
  32841. * @returns the current mesh
  32842. */
  32843. Mesh.prototype.registerBeforeRender = function (func) {
  32844. this.onBeforeRenderObservable.add(func);
  32845. return this;
  32846. };
  32847. /**
  32848. * Disposes a previously registered javascript function called before the rendering
  32849. * @param func defines the function to remove
  32850. * @returns the current mesh
  32851. */
  32852. Mesh.prototype.unregisterBeforeRender = function (func) {
  32853. this.onBeforeRenderObservable.removeCallback(func);
  32854. return this;
  32855. };
  32856. /**
  32857. * Registers for this mesh a javascript function called just after the rendering is complete
  32858. * @param func defines the function to call after rendering this mesh
  32859. * @returns the current mesh
  32860. */
  32861. Mesh.prototype.registerAfterRender = function (func) {
  32862. this.onAfterRenderObservable.add(func);
  32863. return this;
  32864. };
  32865. /**
  32866. * Disposes a previously registered javascript function called after the rendering.
  32867. * @param func defines the function to remove
  32868. * @returns the current mesh
  32869. */
  32870. Mesh.prototype.unregisterAfterRender = function (func) {
  32871. this.onAfterRenderObservable.removeCallback(func);
  32872. return this;
  32873. };
  32874. /** @hidden */
  32875. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32876. var scene = this.getScene();
  32877. var batchCache = this._instanceDataStorage.batchCache;
  32878. batchCache.mustReturn = false;
  32879. batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32880. batchCache.visibleInstances[subMeshId] = null;
  32881. if (this._instanceDataStorage.visibleInstances) {
  32882. var visibleInstances = this._instanceDataStorage.visibleInstances;
  32883. var currentRenderId = scene.getRenderId();
  32884. var defaultRenderId = (scene._isInIntermediateRendering() ? visibleInstances.intermediateDefaultRenderId : visibleInstances.defaultRenderId);
  32885. batchCache.visibleInstances[subMeshId] = visibleInstances[currentRenderId];
  32886. var selfRenderId = this._renderId;
  32887. if (!batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32888. batchCache.visibleInstances[subMeshId] = visibleInstances[defaultRenderId];
  32889. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32890. selfRenderId = Math.max(visibleInstances.selfDefaultRenderId, currentRenderId);
  32891. }
  32892. var visibleInstancesForSubMesh = batchCache.visibleInstances[subMeshId];
  32893. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32894. if (this._instanceDataStorage.renderIdForInstances[subMeshId] === currentRenderId) {
  32895. batchCache.mustReturn = true;
  32896. return batchCache;
  32897. }
  32898. if (currentRenderId !== selfRenderId) {
  32899. batchCache.renderSelf[subMeshId] = false;
  32900. }
  32901. }
  32902. this._instanceDataStorage.renderIdForInstances[subMeshId] = currentRenderId;
  32903. }
  32904. return batchCache;
  32905. };
  32906. /** @hidden */
  32907. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32908. var visibleInstances = batch.visibleInstances[subMesh._id];
  32909. if (!visibleInstances) {
  32910. return this;
  32911. }
  32912. var matricesCount = visibleInstances.length + 1;
  32913. var bufferSize = matricesCount * 16 * 4;
  32914. var instanceStorage = this._instanceDataStorage;
  32915. var currentInstancesBufferSize = instanceStorage.instancesBufferSize;
  32916. var instancesBuffer = instanceStorage.instancesBuffer;
  32917. while (instanceStorage.instancesBufferSize < bufferSize) {
  32918. instanceStorage.instancesBufferSize *= 2;
  32919. }
  32920. if (!instanceStorage.instancesData || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  32921. instanceStorage.instancesData = new Float32Array(instanceStorage.instancesBufferSize / 4);
  32922. }
  32923. var offset = 0;
  32924. var instancesCount = 0;
  32925. var world = this.getWorldMatrix();
  32926. if (batch.renderSelf[subMesh._id]) {
  32927. world.copyToArray(instanceStorage.instancesData, offset);
  32928. offset += 16;
  32929. instancesCount++;
  32930. }
  32931. if (visibleInstances) {
  32932. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32933. var instance = visibleInstances[instanceIndex];
  32934. instance.getWorldMatrix().copyToArray(instanceStorage.instancesData, offset);
  32935. offset += 16;
  32936. instancesCount++;
  32937. }
  32938. }
  32939. if (!instancesBuffer || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  32940. if (instancesBuffer) {
  32941. instancesBuffer.dispose();
  32942. }
  32943. instancesBuffer = new BABYLON.Buffer(engine, instanceStorage.instancesData, true, 16, false, true);
  32944. instanceStorage.instancesBuffer = instancesBuffer;
  32945. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32946. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32947. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32948. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32949. }
  32950. else {
  32951. instancesBuffer.updateDirectly(instanceStorage.instancesData, 0, instancesCount);
  32952. }
  32953. this._bind(subMesh, effect, fillMode);
  32954. this._draw(subMesh, fillMode, instancesCount);
  32955. engine.unbindInstanceAttributes();
  32956. return this;
  32957. };
  32958. /** @hidden */
  32959. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32960. var scene = this.getScene();
  32961. var engine = scene.getEngine();
  32962. if (hardwareInstancedRendering) {
  32963. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32964. }
  32965. else {
  32966. if (batch.renderSelf[subMesh._id]) {
  32967. // Draw
  32968. if (onBeforeDraw) {
  32969. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32970. }
  32971. this._draw(subMesh, fillMode, this._instanceDataStorage.overridenInstanceCount);
  32972. }
  32973. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32974. if (visibleInstancesForSubMesh) {
  32975. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32976. var instance = visibleInstancesForSubMesh[instanceIndex];
  32977. // World
  32978. var world = instance.getWorldMatrix();
  32979. if (onBeforeDraw) {
  32980. onBeforeDraw(true, world, effectiveMaterial);
  32981. }
  32982. // Draw
  32983. this._draw(subMesh, fillMode);
  32984. }
  32985. }
  32986. }
  32987. return this;
  32988. };
  32989. /**
  32990. * 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
  32991. * @param subMesh defines the subMesh to render
  32992. * @param enableAlphaMode defines if alpha mode can be changed
  32993. * @returns the current mesh
  32994. */
  32995. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32996. if (this._checkOcclusionQuery()) {
  32997. return this;
  32998. }
  32999. var scene = this.getScene();
  33000. // Managing instances
  33001. var batch = this._getInstancesRenderList(subMesh._id);
  33002. if (batch.mustReturn) {
  33003. return this;
  33004. }
  33005. // Checking geometry state
  33006. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  33007. return this;
  33008. }
  33009. if (this._onBeforeRenderObservable) {
  33010. this._onBeforeRenderObservable.notifyObservers(this);
  33011. }
  33012. var engine = scene.getEngine();
  33013. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  33014. // Material
  33015. var material = subMesh.getMaterial();
  33016. if (!material) {
  33017. return this;
  33018. }
  33019. this._effectiveMaterial = material;
  33020. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  33021. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  33022. return this;
  33023. }
  33024. }
  33025. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  33026. return this;
  33027. }
  33028. // Alpha mode
  33029. if (enableAlphaMode) {
  33030. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  33031. }
  33032. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  33033. var step = _a[_i];
  33034. step.action(this, subMesh, batch);
  33035. }
  33036. var effect;
  33037. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  33038. effect = subMesh.effect;
  33039. }
  33040. else {
  33041. effect = this._effectiveMaterial.getEffect();
  33042. }
  33043. if (!effect) {
  33044. return this;
  33045. }
  33046. var sideOrientation = this.overrideMaterialSideOrientation;
  33047. if (sideOrientation == null) {
  33048. sideOrientation = this._effectiveMaterial.sideOrientation;
  33049. if (this._getWorldMatrixDeterminant() < 0) {
  33050. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  33051. }
  33052. }
  33053. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  33054. if (this._effectiveMaterial.forceDepthWrite) {
  33055. engine.setDepthWrite(true);
  33056. }
  33057. // Bind
  33058. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  33059. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  33060. this._bind(subMesh, effect, fillMode);
  33061. }
  33062. var world = this.getWorldMatrix();
  33063. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  33064. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  33065. }
  33066. else {
  33067. this._effectiveMaterial.bind(world, this);
  33068. }
  33069. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  33070. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  33071. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  33072. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  33073. }
  33074. // Draw
  33075. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  33076. // Unbind
  33077. this._effectiveMaterial.unbind();
  33078. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  33079. var step = _c[_b];
  33080. step.action(this, subMesh, batch);
  33081. }
  33082. if (this._onAfterRenderObservable) {
  33083. this._onAfterRenderObservable.notifyObservers(this);
  33084. }
  33085. return this;
  33086. };
  33087. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  33088. if (isInstance && effectiveMaterial) {
  33089. effectiveMaterial.bindOnlyWorldMatrix(world);
  33090. }
  33091. };
  33092. /**
  33093. * Normalize matrix weights so that all vertices have a total weight set to 1
  33094. */
  33095. Mesh.prototype.cleanMatrixWeights = function () {
  33096. var epsilon = 1e-3;
  33097. var noInfluenceBoneIndex = 0.0;
  33098. if (this.skeleton) {
  33099. noInfluenceBoneIndex = this.skeleton.bones.length;
  33100. }
  33101. else {
  33102. return;
  33103. }
  33104. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33105. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33106. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33107. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33108. var influencers = this.numBoneInfluencers;
  33109. var size = matricesWeights.length;
  33110. for (var i = 0; i < size; i += 4) {
  33111. var weight = 0.0;
  33112. var firstZeroWeight = -1;
  33113. for (var j = 0; j < 4; j++) {
  33114. var w = matricesWeights[i + j];
  33115. weight += w;
  33116. if (w < epsilon && firstZeroWeight < 0) {
  33117. firstZeroWeight = j;
  33118. }
  33119. }
  33120. if (matricesWeightsExtra) {
  33121. for (var j = 0; j < 4; j++) {
  33122. var w = matricesWeightsExtra[i + j];
  33123. weight += w;
  33124. if (w < epsilon && firstZeroWeight < 0) {
  33125. firstZeroWeight = j + 4;
  33126. }
  33127. }
  33128. }
  33129. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  33130. firstZeroWeight = influencers - 1;
  33131. }
  33132. if (weight > epsilon) {
  33133. var mweight = 1.0 / weight;
  33134. for (var j = 0; j < 4; j++) {
  33135. matricesWeights[i + j] *= mweight;
  33136. }
  33137. if (matricesWeightsExtra) {
  33138. for (var j = 0; j < 4; j++) {
  33139. matricesWeightsExtra[i + j] *= mweight;
  33140. }
  33141. }
  33142. }
  33143. else {
  33144. if (firstZeroWeight >= 4) {
  33145. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  33146. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  33147. }
  33148. else {
  33149. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  33150. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  33151. }
  33152. }
  33153. }
  33154. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  33155. if (matricesIndicesExtra) {
  33156. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  33157. }
  33158. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  33159. if (matricesWeightsExtra) {
  33160. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  33161. }
  33162. };
  33163. /** @hidden */
  33164. Mesh.prototype._checkDelayState = function () {
  33165. var scene = this.getScene();
  33166. if (this._geometry) {
  33167. this._geometry.load(scene);
  33168. }
  33169. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33170. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  33171. this._queueLoad(scene);
  33172. }
  33173. return this;
  33174. };
  33175. Mesh.prototype._queueLoad = function (scene) {
  33176. var _this = this;
  33177. scene._addPendingData(this);
  33178. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  33179. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  33180. if (data instanceof ArrayBuffer) {
  33181. _this._delayLoadingFunction(data, _this);
  33182. }
  33183. else {
  33184. _this._delayLoadingFunction(JSON.parse(data), _this);
  33185. }
  33186. _this.instances.forEach(function (instance) {
  33187. instance._syncSubMeshes();
  33188. });
  33189. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33190. scene._removePendingData(_this);
  33191. }, function () { }, scene.database, getBinaryData);
  33192. return this;
  33193. };
  33194. /**
  33195. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  33196. * A mesh is in the frustum if its bounding box intersects the frustum
  33197. * @param frustumPlanes defines the frustum to test
  33198. * @returns true if the mesh is in the frustum planes
  33199. */
  33200. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  33201. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33202. return false;
  33203. }
  33204. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  33205. return false;
  33206. }
  33207. this._checkDelayState();
  33208. return true;
  33209. };
  33210. /**
  33211. * Sets the mesh material by the material or multiMaterial `id` property
  33212. * @param id is a string identifying the material or the multiMaterial
  33213. * @returns the current mesh
  33214. */
  33215. Mesh.prototype.setMaterialByID = function (id) {
  33216. var materials = this.getScene().materials;
  33217. var index;
  33218. for (index = materials.length - 1; index > -1; index--) {
  33219. if (materials[index].id === id) {
  33220. this.material = materials[index];
  33221. return this;
  33222. }
  33223. }
  33224. // Multi
  33225. var multiMaterials = this.getScene().multiMaterials;
  33226. for (index = multiMaterials.length - 1; index > -1; index--) {
  33227. if (multiMaterials[index].id === id) {
  33228. this.material = multiMaterials[index];
  33229. return this;
  33230. }
  33231. }
  33232. return this;
  33233. };
  33234. /**
  33235. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  33236. * @returns an array of IAnimatable
  33237. */
  33238. Mesh.prototype.getAnimatables = function () {
  33239. var results = new Array();
  33240. if (this.material) {
  33241. results.push(this.material);
  33242. }
  33243. if (this.skeleton) {
  33244. results.push(this.skeleton);
  33245. }
  33246. return results;
  33247. };
  33248. /**
  33249. * Modifies the mesh geometry according to the passed transformation matrix.
  33250. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  33251. * The mesh normals are modified using the same transformation.
  33252. * Note that, under the hood, this method sets a new VertexBuffer each call.
  33253. * @param transform defines the transform matrix to use
  33254. * @see http://doc.babylonjs.com/resources/baking_transformations
  33255. * @returns the current mesh
  33256. */
  33257. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  33258. // Position
  33259. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33260. return this;
  33261. }
  33262. var submeshes = this.subMeshes.splice(0);
  33263. this._resetPointsArrayCache();
  33264. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33265. var temp = new Array();
  33266. var index;
  33267. for (index = 0; index < data.length; index += 3) {
  33268. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  33269. }
  33270. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  33271. // Normals
  33272. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33273. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33274. temp = [];
  33275. for (index = 0; index < data.length; index += 3) {
  33276. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  33277. }
  33278. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  33279. }
  33280. // flip faces?
  33281. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  33282. this.flipFaces();
  33283. }
  33284. // Restore submeshes
  33285. this.releaseSubMeshes();
  33286. this.subMeshes = submeshes;
  33287. return this;
  33288. };
  33289. /**
  33290. * Modifies the mesh geometry according to its own current World Matrix.
  33291. * The mesh World Matrix is then reset.
  33292. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  33293. * Note that, under the hood, this method sets a new VertexBuffer each call.
  33294. * @see http://doc.babylonjs.com/resources/baking_transformations
  33295. * @returns the current mesh
  33296. */
  33297. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  33298. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  33299. this.scaling.copyFromFloats(1, 1, 1);
  33300. this.position.copyFromFloats(0, 0, 0);
  33301. this.rotation.copyFromFloats(0, 0, 0);
  33302. //only if quaternion is already set
  33303. if (this.rotationQuaternion) {
  33304. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  33305. }
  33306. this._worldMatrix = BABYLON.Matrix.Identity();
  33307. return this;
  33308. };
  33309. Object.defineProperty(Mesh.prototype, "_positions", {
  33310. // Cache
  33311. /** @hidden */
  33312. get: function () {
  33313. if (this._geometry) {
  33314. return this._geometry._positions;
  33315. }
  33316. return null;
  33317. },
  33318. enumerable: true,
  33319. configurable: true
  33320. });
  33321. /** @hidden */
  33322. Mesh.prototype._resetPointsArrayCache = function () {
  33323. if (this._geometry) {
  33324. this._geometry._resetPointsArrayCache();
  33325. }
  33326. return this;
  33327. };
  33328. /** @hidden */
  33329. Mesh.prototype._generatePointsArray = function () {
  33330. if (this._geometry) {
  33331. return this._geometry._generatePointsArray();
  33332. }
  33333. return false;
  33334. };
  33335. /**
  33336. * Returns a new Mesh object generated from the current mesh properties.
  33337. * This method must not get confused with createInstance()
  33338. * @param name is a string, the name given to the new mesh
  33339. * @param newParent can be any Node object (default `null`)
  33340. * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`)
  33341. * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`)
  33342. * @returns a new mesh
  33343. */
  33344. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  33345. if (name === void 0) { name = ""; }
  33346. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  33347. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  33348. };
  33349. /**
  33350. * Releases resources associated with this mesh.
  33351. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  33352. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  33353. */
  33354. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  33355. var _this = this;
  33356. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  33357. this.morphTargetManager = null;
  33358. if (this._geometry) {
  33359. this._geometry.releaseForMesh(this, true);
  33360. }
  33361. if (this._onBeforeDrawObservable) {
  33362. this._onBeforeDrawObservable.clear();
  33363. }
  33364. if (this._onBeforeRenderObservable) {
  33365. this._onBeforeRenderObservable.clear();
  33366. }
  33367. if (this._onAfterRenderObservable) {
  33368. this._onAfterRenderObservable.clear();
  33369. }
  33370. // Sources
  33371. var meshes = this.getScene().meshes;
  33372. meshes.forEach(function (abstractMesh) {
  33373. var mesh = abstractMesh;
  33374. if (mesh._source && mesh._source === _this) {
  33375. mesh._source = null;
  33376. }
  33377. });
  33378. this._source = null;
  33379. // Instances
  33380. if (this._instanceDataStorage.instancesBuffer) {
  33381. this._instanceDataStorage.instancesBuffer.dispose();
  33382. this._instanceDataStorage.instancesBuffer = null;
  33383. }
  33384. while (this.instances.length) {
  33385. this.instances[0].dispose();
  33386. }
  33387. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  33388. };
  33389. /**
  33390. * Modifies the mesh geometry according to a displacement map.
  33391. * 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.
  33392. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33393. * @param url is a string, the URL from the image file is to be downloaded.
  33394. * @param minHeight is the lower limit of the displacement.
  33395. * @param maxHeight is the upper limit of the displacement.
  33396. * @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.
  33397. * @param uvOffset is an optional vector2 used to offset UV.
  33398. * @param uvScale is an optional vector2 used to scale UV.
  33399. * @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.
  33400. * @returns the Mesh.
  33401. */
  33402. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  33403. var _this = this;
  33404. if (forceUpdate === void 0) { forceUpdate = false; }
  33405. var scene = this.getScene();
  33406. var onload = function (img) {
  33407. // Getting height map data
  33408. var canvas = document.createElement("canvas");
  33409. var context = canvas.getContext("2d");
  33410. var heightMapWidth = img.width;
  33411. var heightMapHeight = img.height;
  33412. canvas.width = heightMapWidth;
  33413. canvas.height = heightMapHeight;
  33414. context.drawImage(img, 0, 0);
  33415. // Create VertexData from map data
  33416. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  33417. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  33418. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  33419. //execute success callback, if set
  33420. if (onSuccess) {
  33421. onSuccess(_this);
  33422. }
  33423. };
  33424. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  33425. return this;
  33426. };
  33427. /**
  33428. * Modifies the mesh geometry according to a displacementMap buffer.
  33429. * 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.
  33430. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33431. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  33432. * @param heightMapWidth is the width of the buffer image.
  33433. * @param heightMapHeight is the height of the buffer image.
  33434. * @param minHeight is the lower limit of the displacement.
  33435. * @param maxHeight is the upper limit of the displacement.
  33436. * @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.
  33437. * @param uvOffset is an optional vector2 used to offset UV.
  33438. * @param uvScale is an optional vector2 used to scale UV.
  33439. * @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.
  33440. * @returns the Mesh.
  33441. */
  33442. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  33443. if (forceUpdate === void 0) { forceUpdate = false; }
  33444. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  33445. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  33446. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33447. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  33448. return this;
  33449. }
  33450. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  33451. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33452. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33453. var position = BABYLON.Vector3.Zero();
  33454. var normal = BABYLON.Vector3.Zero();
  33455. var uv = BABYLON.Vector2.Zero();
  33456. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  33457. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  33458. for (var index = 0; index < positions.length; index += 3) {
  33459. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  33460. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  33461. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  33462. // Compute height
  33463. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  33464. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  33465. var pos = (u + v * heightMapWidth) * 4;
  33466. var r = buffer[pos] / 255.0;
  33467. var g = buffer[pos + 1] / 255.0;
  33468. var b = buffer[pos + 2] / 255.0;
  33469. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33470. normal.normalize();
  33471. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  33472. position = position.add(normal);
  33473. position.toArray(positions, index);
  33474. }
  33475. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  33476. if (forceUpdate) {
  33477. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33478. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33479. }
  33480. else {
  33481. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33482. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33483. }
  33484. return this;
  33485. };
  33486. /**
  33487. * Modify the mesh to get a flat shading rendering.
  33488. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  33489. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  33490. * @returns current mesh
  33491. */
  33492. Mesh.prototype.convertToFlatShadedMesh = function () {
  33493. var kinds = this.getVerticesDataKinds();
  33494. var vbs = {};
  33495. var data = {};
  33496. var newdata = {};
  33497. var updatableNormals = false;
  33498. var kindIndex;
  33499. var kind;
  33500. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33501. kind = kinds[kindIndex];
  33502. var vertexBuffer = this.getVertexBuffer(kind);
  33503. if (kind === BABYLON.VertexBuffer.NormalKind) {
  33504. updatableNormals = vertexBuffer.isUpdatable();
  33505. kinds.splice(kindIndex, 1);
  33506. kindIndex--;
  33507. continue;
  33508. }
  33509. vbs[kind] = vertexBuffer;
  33510. data[kind] = vbs[kind].getData();
  33511. newdata[kind] = [];
  33512. }
  33513. // Save previous submeshes
  33514. var previousSubmeshes = this.subMeshes.slice(0);
  33515. var indices = this.getIndices();
  33516. var totalIndices = this.getTotalIndices();
  33517. // Generating unique vertices per face
  33518. var index;
  33519. for (index = 0; index < totalIndices; index++) {
  33520. var vertexIndex = indices[index];
  33521. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33522. kind = kinds[kindIndex];
  33523. var stride = vbs[kind].getStrideSize();
  33524. for (var offset = 0; offset < stride; offset++) {
  33525. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33526. }
  33527. }
  33528. }
  33529. // Updating faces & normal
  33530. var normals = [];
  33531. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  33532. for (index = 0; index < totalIndices; index += 3) {
  33533. indices[index] = index;
  33534. indices[index + 1] = index + 1;
  33535. indices[index + 2] = index + 2;
  33536. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  33537. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  33538. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  33539. var p1p2 = p1.subtract(p2);
  33540. var p3p2 = p3.subtract(p2);
  33541. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33542. // Store same normals for every vertex
  33543. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33544. normals.push(normal.x);
  33545. normals.push(normal.y);
  33546. normals.push(normal.z);
  33547. }
  33548. }
  33549. this.setIndices(indices);
  33550. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33551. // Updating vertex buffers
  33552. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33553. kind = kinds[kindIndex];
  33554. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33555. }
  33556. // Updating submeshes
  33557. this.releaseSubMeshes();
  33558. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33559. var previousOne = previousSubmeshes[submeshIndex];
  33560. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33561. }
  33562. this.synchronizeInstances();
  33563. return this;
  33564. };
  33565. /**
  33566. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33567. * In other words, more vertices, no more indices and a single bigger VBO.
  33568. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33569. * @returns current mesh
  33570. */
  33571. Mesh.prototype.convertToUnIndexedMesh = function () {
  33572. var kinds = this.getVerticesDataKinds();
  33573. var vbs = {};
  33574. var data = {};
  33575. var newdata = {};
  33576. var kindIndex;
  33577. var kind;
  33578. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33579. kind = kinds[kindIndex];
  33580. var vertexBuffer = this.getVertexBuffer(kind);
  33581. vbs[kind] = vertexBuffer;
  33582. data[kind] = vbs[kind].getData();
  33583. newdata[kind] = [];
  33584. }
  33585. // Save previous submeshes
  33586. var previousSubmeshes = this.subMeshes.slice(0);
  33587. var indices = this.getIndices();
  33588. var totalIndices = this.getTotalIndices();
  33589. // Generating unique vertices per face
  33590. var index;
  33591. for (index = 0; index < totalIndices; index++) {
  33592. var vertexIndex = indices[index];
  33593. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33594. kind = kinds[kindIndex];
  33595. var stride = vbs[kind].getStrideSize();
  33596. for (var offset = 0; offset < stride; offset++) {
  33597. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33598. }
  33599. }
  33600. }
  33601. // Updating indices
  33602. for (index = 0; index < totalIndices; index += 3) {
  33603. indices[index] = index;
  33604. indices[index + 1] = index + 1;
  33605. indices[index + 2] = index + 2;
  33606. }
  33607. this.setIndices(indices);
  33608. // Updating vertex buffers
  33609. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33610. kind = kinds[kindIndex];
  33611. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33612. }
  33613. // Updating submeshes
  33614. this.releaseSubMeshes();
  33615. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33616. var previousOne = previousSubmeshes[submeshIndex];
  33617. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33618. }
  33619. this._unIndexed = true;
  33620. this.synchronizeInstances();
  33621. return this;
  33622. };
  33623. /**
  33624. * Inverses facet orientations.
  33625. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33626. * @param flipNormals will also inverts the normals
  33627. * @returns current mesh
  33628. */
  33629. Mesh.prototype.flipFaces = function (flipNormals) {
  33630. if (flipNormals === void 0) { flipNormals = false; }
  33631. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33632. var i;
  33633. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33634. for (i = 0; i < vertex_data.normals.length; i++) {
  33635. vertex_data.normals[i] *= -1;
  33636. }
  33637. }
  33638. if (vertex_data.indices) {
  33639. var temp;
  33640. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33641. // reassign indices
  33642. temp = vertex_data.indices[i + 1];
  33643. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33644. vertex_data.indices[i + 2] = temp;
  33645. }
  33646. }
  33647. vertex_data.applyToMesh(this);
  33648. return this;
  33649. };
  33650. // Instances
  33651. /**
  33652. * Creates a new InstancedMesh object from the mesh model.
  33653. * Warning : this method is not supported for Line mesh and LineSystem
  33654. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  33655. * @param name defines the name of the new instance
  33656. * @returns a new InstancedMesh
  33657. */
  33658. Mesh.prototype.createInstance = function (name) {
  33659. return new BABYLON.InstancedMesh(name, this);
  33660. };
  33661. /**
  33662. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33663. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33664. * @returns the current mesh
  33665. */
  33666. Mesh.prototype.synchronizeInstances = function () {
  33667. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33668. var instance = this.instances[instanceIndex];
  33669. instance._syncSubMeshes();
  33670. }
  33671. return this;
  33672. };
  33673. /**
  33674. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33675. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33676. * This should be used together with the simplification to avoid disappearing triangles.
  33677. * @param successCallback an optional success callback to be called after the optimization finished.
  33678. * @returns the current mesh
  33679. */
  33680. Mesh.prototype.optimizeIndices = function (successCallback) {
  33681. var _this = this;
  33682. var indices = this.getIndices();
  33683. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33684. if (!positions || !indices) {
  33685. return this;
  33686. }
  33687. var vectorPositions = new Array();
  33688. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33689. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33690. }
  33691. var dupes = new Array();
  33692. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33693. var realPos = vectorPositions.length - 1 - iteration;
  33694. var testedPosition = vectorPositions[realPos];
  33695. for (var j = 0; j < realPos; ++j) {
  33696. var againstPosition = vectorPositions[j];
  33697. if (testedPosition.equals(againstPosition)) {
  33698. dupes[realPos] = j;
  33699. break;
  33700. }
  33701. }
  33702. }, function () {
  33703. for (var i = 0; i < indices.length; ++i) {
  33704. indices[i] = dupes[indices[i]] || indices[i];
  33705. }
  33706. //indices are now reordered
  33707. var originalSubMeshes = _this.subMeshes.slice(0);
  33708. _this.setIndices(indices);
  33709. _this.subMeshes = originalSubMeshes;
  33710. if (successCallback) {
  33711. successCallback(_this);
  33712. }
  33713. });
  33714. return this;
  33715. };
  33716. /**
  33717. * Serialize current mesh
  33718. * @param serializationObject defines the object which will receive the serialization data
  33719. */
  33720. Mesh.prototype.serialize = function (serializationObject) {
  33721. serializationObject.name = this.name;
  33722. serializationObject.id = this.id;
  33723. serializationObject.type = this.getClassName();
  33724. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33725. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33726. }
  33727. serializationObject.position = this.position.asArray();
  33728. if (this.rotationQuaternion) {
  33729. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33730. }
  33731. else if (this.rotation) {
  33732. serializationObject.rotation = this.rotation.asArray();
  33733. }
  33734. serializationObject.scaling = this.scaling.asArray();
  33735. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33736. serializationObject.isEnabled = this.isEnabled(false);
  33737. serializationObject.isVisible = this.isVisible;
  33738. serializationObject.infiniteDistance = this.infiniteDistance;
  33739. serializationObject.pickable = this.isPickable;
  33740. serializationObject.receiveShadows = this.receiveShadows;
  33741. serializationObject.billboardMode = this.billboardMode;
  33742. serializationObject.visibility = this.visibility;
  33743. serializationObject.checkCollisions = this.checkCollisions;
  33744. serializationObject.isBlocker = this.isBlocker;
  33745. // Parent
  33746. if (this.parent) {
  33747. serializationObject.parentId = this.parent.id;
  33748. }
  33749. // Geometry
  33750. serializationObject.isUnIndexed = this.isUnIndexed;
  33751. var geometry = this._geometry;
  33752. if (geometry) {
  33753. var geometryId = geometry.id;
  33754. serializationObject.geometryId = geometryId;
  33755. // SubMeshes
  33756. serializationObject.subMeshes = [];
  33757. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33758. var subMesh = this.subMeshes[subIndex];
  33759. serializationObject.subMeshes.push({
  33760. materialIndex: subMesh.materialIndex,
  33761. verticesStart: subMesh.verticesStart,
  33762. verticesCount: subMesh.verticesCount,
  33763. indexStart: subMesh.indexStart,
  33764. indexCount: subMesh.indexCount
  33765. });
  33766. }
  33767. }
  33768. // Material
  33769. if (this.material) {
  33770. serializationObject.materialId = this.material.id;
  33771. }
  33772. else {
  33773. this.material = null;
  33774. }
  33775. // Morph targets
  33776. if (this.morphTargetManager) {
  33777. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33778. }
  33779. // Skeleton
  33780. if (this.skeleton) {
  33781. serializationObject.skeletonId = this.skeleton.id;
  33782. }
  33783. // Physics
  33784. //TODO implement correct serialization for physics impostors.
  33785. var impostor = this.getPhysicsImpostor();
  33786. if (impostor) {
  33787. serializationObject.physicsMass = impostor.getParam("mass");
  33788. serializationObject.physicsFriction = impostor.getParam("friction");
  33789. serializationObject.physicsRestitution = impostor.getParam("mass");
  33790. serializationObject.physicsImpostor = impostor.type;
  33791. }
  33792. // Metadata
  33793. if (this.metadata) {
  33794. serializationObject.metadata = this.metadata;
  33795. }
  33796. // Instances
  33797. serializationObject.instances = [];
  33798. for (var index = 0; index < this.instances.length; index++) {
  33799. var instance = this.instances[index];
  33800. if (instance.doNotSerialize) {
  33801. continue;
  33802. }
  33803. var serializationInstance = {
  33804. name: instance.name,
  33805. id: instance.id,
  33806. position: instance.position.asArray(),
  33807. scaling: instance.scaling.asArray()
  33808. };
  33809. if (instance.parent) {
  33810. serializationInstance.parentId = instance.parent.id;
  33811. }
  33812. if (instance.rotationQuaternion) {
  33813. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33814. }
  33815. else if (instance.rotation) {
  33816. serializationInstance.rotation = instance.rotation.asArray();
  33817. }
  33818. serializationObject.instances.push(serializationInstance);
  33819. // Animations
  33820. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33821. serializationInstance.ranges = instance.serializeAnimationRanges();
  33822. }
  33823. //
  33824. // Animations
  33825. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33826. serializationObject.ranges = this.serializeAnimationRanges();
  33827. // Layer mask
  33828. serializationObject.layerMask = this.layerMask;
  33829. // Alpha
  33830. serializationObject.alphaIndex = this.alphaIndex;
  33831. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33832. // Overlay
  33833. serializationObject.overlayAlpha = this.overlayAlpha;
  33834. serializationObject.overlayColor = this.overlayColor.asArray();
  33835. serializationObject.renderOverlay = this.renderOverlay;
  33836. // Fog
  33837. serializationObject.applyFog = this.applyFog;
  33838. // Action Manager
  33839. if (this.actionManager) {
  33840. serializationObject.actions = this.actionManager.serialize(this.name);
  33841. }
  33842. };
  33843. /** @hidden */
  33844. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33845. if (!this.geometry) {
  33846. return;
  33847. }
  33848. this._markSubMeshesAsAttributesDirty();
  33849. var morphTargetManager = this._morphTargetManager;
  33850. if (morphTargetManager && morphTargetManager.vertexCount) {
  33851. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33852. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33853. this.morphTargetManager = null;
  33854. return;
  33855. }
  33856. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33857. var morphTarget = morphTargetManager.getActiveTarget(index);
  33858. var positions = morphTarget.getPositions();
  33859. if (!positions) {
  33860. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33861. return;
  33862. }
  33863. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33864. var normals = morphTarget.getNormals();
  33865. if (normals) {
  33866. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33867. }
  33868. var tangents = morphTarget.getTangents();
  33869. if (tangents) {
  33870. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33871. }
  33872. }
  33873. }
  33874. else {
  33875. var index = 0;
  33876. // Positions
  33877. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33878. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33879. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33880. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33881. }
  33882. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33883. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33884. }
  33885. index++;
  33886. }
  33887. }
  33888. };
  33889. // Statics
  33890. /**
  33891. * Returns a new Mesh object parsed from the source provided.
  33892. * @param parsedMesh is the source
  33893. * @param scene defines the hosting scene
  33894. * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with
  33895. * @returns a new Mesh
  33896. */
  33897. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33898. var mesh;
  33899. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33900. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33901. }
  33902. else {
  33903. mesh = new Mesh(parsedMesh.name, scene);
  33904. }
  33905. mesh.id = parsedMesh.id;
  33906. if (BABYLON.Tags) {
  33907. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33908. }
  33909. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33910. if (parsedMesh.metadata !== undefined) {
  33911. mesh.metadata = parsedMesh.metadata;
  33912. }
  33913. if (parsedMesh.rotationQuaternion) {
  33914. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33915. }
  33916. else if (parsedMesh.rotation) {
  33917. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33918. }
  33919. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33920. if (parsedMesh.localMatrix) {
  33921. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33922. }
  33923. else if (parsedMesh.pivotMatrix) {
  33924. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33925. }
  33926. mesh.setEnabled(parsedMesh.isEnabled);
  33927. mesh.isVisible = parsedMesh.isVisible;
  33928. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33929. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33930. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33931. if (parsedMesh.applyFog !== undefined) {
  33932. mesh.applyFog = parsedMesh.applyFog;
  33933. }
  33934. if (parsedMesh.pickable !== undefined) {
  33935. mesh.isPickable = parsedMesh.pickable;
  33936. }
  33937. if (parsedMesh.alphaIndex !== undefined) {
  33938. mesh.alphaIndex = parsedMesh.alphaIndex;
  33939. }
  33940. mesh.receiveShadows = parsedMesh.receiveShadows;
  33941. mesh.billboardMode = parsedMesh.billboardMode;
  33942. if (parsedMesh.visibility !== undefined) {
  33943. mesh.visibility = parsedMesh.visibility;
  33944. }
  33945. mesh.checkCollisions = parsedMesh.checkCollisions;
  33946. if (parsedMesh.isBlocker !== undefined) {
  33947. mesh.isBlocker = parsedMesh.isBlocker;
  33948. }
  33949. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33950. // freezeWorldMatrix
  33951. if (parsedMesh.freezeWorldMatrix) {
  33952. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33953. }
  33954. // Parent
  33955. if (parsedMesh.parentId) {
  33956. mesh._waitingParentId = parsedMesh.parentId;
  33957. }
  33958. // Actions
  33959. if (parsedMesh.actions !== undefined) {
  33960. mesh._waitingActions = parsedMesh.actions;
  33961. }
  33962. // Overlay
  33963. if (parsedMesh.overlayAlpha !== undefined) {
  33964. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33965. }
  33966. if (parsedMesh.overlayColor !== undefined) {
  33967. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33968. }
  33969. if (parsedMesh.renderOverlay !== undefined) {
  33970. mesh.renderOverlay = parsedMesh.renderOverlay;
  33971. }
  33972. // Geometry
  33973. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33974. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33975. if (parsedMesh.delayLoadingFile) {
  33976. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33977. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33978. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33979. if (parsedMesh._binaryInfo) {
  33980. mesh._binaryInfo = parsedMesh._binaryInfo;
  33981. }
  33982. mesh._delayInfo = [];
  33983. if (parsedMesh.hasUVs) {
  33984. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33985. }
  33986. if (parsedMesh.hasUVs2) {
  33987. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33988. }
  33989. if (parsedMesh.hasUVs3) {
  33990. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33991. }
  33992. if (parsedMesh.hasUVs4) {
  33993. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33994. }
  33995. if (parsedMesh.hasUVs5) {
  33996. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33997. }
  33998. if (parsedMesh.hasUVs6) {
  33999. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  34000. }
  34001. if (parsedMesh.hasColors) {
  34002. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  34003. }
  34004. if (parsedMesh.hasMatricesIndices) {
  34005. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34006. }
  34007. if (parsedMesh.hasMatricesWeights) {
  34008. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34009. }
  34010. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  34011. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  34012. mesh._checkDelayState();
  34013. }
  34014. }
  34015. else {
  34016. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  34017. }
  34018. // Material
  34019. if (parsedMesh.materialId) {
  34020. mesh.setMaterialByID(parsedMesh.materialId);
  34021. }
  34022. else {
  34023. mesh.material = null;
  34024. }
  34025. // Morph targets
  34026. if (parsedMesh.morphTargetManagerId > -1) {
  34027. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  34028. }
  34029. // Skeleton
  34030. if (parsedMesh.skeletonId > -1) {
  34031. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  34032. if (parsedMesh.numBoneInfluencers) {
  34033. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  34034. }
  34035. }
  34036. // Animations
  34037. if (parsedMesh.animations) {
  34038. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  34039. var parsedAnimation = parsedMesh.animations[animationIndex];
  34040. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  34041. }
  34042. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  34043. }
  34044. if (parsedMesh.autoAnimate) {
  34045. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  34046. }
  34047. // Layer Mask
  34048. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  34049. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  34050. }
  34051. else {
  34052. mesh.layerMask = 0x0FFFFFFF;
  34053. }
  34054. // Physics
  34055. if (parsedMesh.physicsImpostor) {
  34056. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  34057. mass: parsedMesh.physicsMass,
  34058. friction: parsedMesh.physicsFriction,
  34059. restitution: parsedMesh.physicsRestitution
  34060. }, scene);
  34061. }
  34062. // Instances
  34063. if (parsedMesh.instances) {
  34064. for (var index = 0; index < parsedMesh.instances.length; index++) {
  34065. var parsedInstance = parsedMesh.instances[index];
  34066. var instance = mesh.createInstance(parsedInstance.name);
  34067. if (parsedInstance.id) {
  34068. instance.id = parsedInstance.id;
  34069. }
  34070. if (BABYLON.Tags) {
  34071. if (parsedInstance.tags) {
  34072. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  34073. }
  34074. else {
  34075. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  34076. }
  34077. }
  34078. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  34079. if (parsedInstance.parentId) {
  34080. instance._waitingParentId = parsedInstance.parentId;
  34081. }
  34082. if (parsedInstance.rotationQuaternion) {
  34083. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  34084. }
  34085. else if (parsedInstance.rotation) {
  34086. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  34087. }
  34088. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  34089. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  34090. instance.checkCollisions = parsedInstance.checkCollisions;
  34091. }
  34092. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  34093. instance.isPickable = parsedInstance.pickable;
  34094. }
  34095. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  34096. instance.showBoundingBox = parsedInstance.showBoundingBox;
  34097. }
  34098. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  34099. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  34100. }
  34101. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  34102. instance.alphaIndex = parsedInstance.alphaIndex;
  34103. }
  34104. // Physics
  34105. if (parsedInstance.physicsImpostor) {
  34106. instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
  34107. mass: parsedInstance.physicsMass,
  34108. friction: parsedInstance.physicsFriction,
  34109. restitution: parsedInstance.physicsRestitution
  34110. }, scene);
  34111. }
  34112. // Animation
  34113. if (parsedInstance.animations) {
  34114. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  34115. parsedAnimation = parsedInstance.animations[animationIndex];
  34116. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  34117. }
  34118. BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
  34119. if (parsedInstance.autoAnimate) {
  34120. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  34121. }
  34122. }
  34123. }
  34124. }
  34125. return mesh;
  34126. };
  34127. /**
  34128. * Creates a ribbon mesh. Please consider using the same method from the MeshBuilder class instead
  34129. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34130. * @param name defines the name of the mesh to create
  34131. * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  34132. * @param closeArray creates a seam between the first and the last paths of the path array (default is false)
  34133. * @param closePath creates a seam between the first and the last points of each path of the path array
  34134. * @param offset is taken in account only if the `pathArray` is containing a single path
  34135. * @param scene defines the hosting scene
  34136. * @param updatable defines if the mesh must be flagged as updatable
  34137. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34138. * @param instance defines an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#ribbon)
  34139. * @returns a new Mesh
  34140. */
  34141. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  34142. if (closeArray === void 0) { closeArray = false; }
  34143. if (updatable === void 0) { updatable = false; }
  34144. return BABYLON.MeshBuilder.CreateRibbon(name, {
  34145. pathArray: pathArray,
  34146. closeArray: closeArray,
  34147. closePath: closePath,
  34148. offset: offset,
  34149. updatable: updatable,
  34150. sideOrientation: sideOrientation,
  34151. instance: instance
  34152. }, scene);
  34153. };
  34154. /**
  34155. * Creates a plane polygonal mesh. By default, this is a disc. Please consider using the same method from the MeshBuilder class instead
  34156. * @param name defines the name of the mesh to create
  34157. * @param radius sets the radius size (float) of the polygon (default 0.5)
  34158. * @param 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
  34159. * @param scene defines the hosting scene
  34160. * @param updatable defines if the mesh must be flagged as updatable
  34161. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34162. * @returns a new Mesh
  34163. */
  34164. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  34165. if (scene === void 0) { scene = null; }
  34166. var options = {
  34167. radius: radius,
  34168. tessellation: tessellation,
  34169. sideOrientation: sideOrientation,
  34170. updatable: updatable
  34171. };
  34172. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  34173. };
  34174. /**
  34175. * Creates a box mesh. Please consider using the same method from the MeshBuilder class instead
  34176. * @param name defines the name of the mesh to create
  34177. * @param size sets the size (float) of each box side (default 1)
  34178. * @param scene defines the hosting scene
  34179. * @param updatable defines if the mesh must be flagged as updatable
  34180. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34181. * @returns a new Mesh
  34182. */
  34183. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  34184. if (scene === void 0) { scene = null; }
  34185. var options = {
  34186. size: size,
  34187. sideOrientation: sideOrientation,
  34188. updatable: updatable
  34189. };
  34190. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  34191. };
  34192. /**
  34193. * Creates a sphere mesh. Please consider using the same method from the MeshBuilder class instead
  34194. * @param name defines the name of the mesh to create
  34195. * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
  34196. * @param diameter sets the diameter size (float) of the sphere (default 1)
  34197. * @param scene defines the hosting scene
  34198. * @param updatable defines if the mesh must be flagged as updatable
  34199. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34200. * @returns a new Mesh
  34201. */
  34202. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  34203. var options = {
  34204. segments: segments,
  34205. diameterX: diameter,
  34206. diameterY: diameter,
  34207. diameterZ: diameter,
  34208. sideOrientation: sideOrientation,
  34209. updatable: updatable
  34210. };
  34211. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  34212. };
  34213. /**
  34214. * Creates a cylinder or a cone mesh. Please consider using the same method from the MeshBuilder class instead
  34215. * @param name defines the name of the mesh to create
  34216. * @param height sets the height size (float) of the cylinder/cone (float, default 2)
  34217. * @param diameterTop set the top cap diameter (floats, default 1)
  34218. * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero
  34219. * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance
  34220. * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1)
  34221. * @param scene defines the hosting scene
  34222. * @param updatable defines if the mesh must be flagged as updatable
  34223. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34224. * @returns a new Mesh
  34225. */
  34226. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  34227. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  34228. if (scene !== undefined) {
  34229. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  34230. updatable = scene;
  34231. }
  34232. scene = subdivisions;
  34233. subdivisions = 1;
  34234. }
  34235. var options = {
  34236. height: height,
  34237. diameterTop: diameterTop,
  34238. diameterBottom: diameterBottom,
  34239. tessellation: tessellation,
  34240. subdivisions: subdivisions,
  34241. sideOrientation: sideOrientation,
  34242. updatable: updatable
  34243. };
  34244. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  34245. };
  34246. // Torus (Code from SharpDX.org)
  34247. /**
  34248. * Creates a torus mesh. Please consider using the same method from the MeshBuilder class instead
  34249. * @param name defines the name of the mesh to create
  34250. * @param diameter sets the diameter size (float) of the torus (default 1)
  34251. * @param thickness sets the diameter size of the tube of the torus (float, default 0.5)
  34252. * @param tessellation sets the number of torus sides (postive integer, default 16)
  34253. * @param scene defines the hosting scene
  34254. * @param updatable defines if the mesh must be flagged as updatable
  34255. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34256. * @returns a new Mesh
  34257. */
  34258. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  34259. var options = {
  34260. diameter: diameter,
  34261. thickness: thickness,
  34262. tessellation: tessellation,
  34263. sideOrientation: sideOrientation,
  34264. updatable: updatable
  34265. };
  34266. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  34267. };
  34268. /**
  34269. * Creates a torus knot mesh. Please consider using the same method from the MeshBuilder class instead
  34270. * @param name defines the name of the mesh to create
  34271. * @param radius sets the global radius size (float) of the torus knot (default 2)
  34272. * @param tube sets the diameter size of the tube of the torus (float, default 0.5)
  34273. * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32)
  34274. * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32)
  34275. * @param p the number of windings on X axis (positive integers, default 2)
  34276. * @param q the number of windings on Y axis (positive integers, default 3)
  34277. * @param scene defines the hosting scene
  34278. * @param updatable defines if the mesh must be flagged as updatable
  34279. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34280. * @returns a new Mesh
  34281. */
  34282. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  34283. var options = {
  34284. radius: radius,
  34285. tube: tube,
  34286. radialSegments: radialSegments,
  34287. tubularSegments: tubularSegments,
  34288. p: p,
  34289. q: q,
  34290. sideOrientation: sideOrientation,
  34291. updatable: updatable
  34292. };
  34293. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  34294. };
  34295. /**
  34296. * Creates a line mesh. Please consider using the same method from the MeshBuilder class instead.
  34297. * @param name defines the name of the mesh to create
  34298. * @param points is an array successive Vector3
  34299. * @param scene defines the hosting scene
  34300. * @param updatable defines if the mesh must be flagged as updatable
  34301. * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines).
  34302. * @returns a new Mesh
  34303. */
  34304. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  34305. if (scene === void 0) { scene = null; }
  34306. if (updatable === void 0) { updatable = false; }
  34307. if (instance === void 0) { instance = null; }
  34308. var options = {
  34309. points: points,
  34310. updatable: updatable,
  34311. instance: instance
  34312. };
  34313. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  34314. };
  34315. /**
  34316. * Creates a dashed line mesh. Please consider using the same method from the MeshBuilder class instead
  34317. * @param name defines the name of the mesh to create
  34318. * @param points is an array successive Vector3
  34319. * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3)
  34320. * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  34321. * @param dashNb is the intended total number of dashes (positive integer, default 200)
  34322. * @param scene defines the hosting scene
  34323. * @param updatable defines if the mesh must be flagged as updatable
  34324. * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines)
  34325. * @returns a new Mesh
  34326. */
  34327. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  34328. if (scene === void 0) { scene = null; }
  34329. var options = {
  34330. points: points,
  34331. dashSize: dashSize,
  34332. gapSize: gapSize,
  34333. dashNb: dashNb,
  34334. updatable: updatable,
  34335. instance: instance
  34336. };
  34337. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  34338. };
  34339. /**
  34340. * Creates a polygon mesh.
  34341. * Please consider using the same method from the MeshBuilder class instead.
  34342. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  34343. * 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.
  34344. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34345. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34346. * Remember you can only change the shape positions, not their number when updating a polygon.
  34347. */
  34348. /**
  34349. * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead
  34350. * @see http://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  34351. * @param name defines the name of the mesh to create
  34352. * @param 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
  34353. * @param scene defines the hosting scene
  34354. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  34355. * @param updatable defines if the mesh must be flagged as updatable
  34356. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34357. * @returns a new Mesh
  34358. */
  34359. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  34360. var options = {
  34361. shape: shape,
  34362. holes: holes,
  34363. updatable: updatable,
  34364. sideOrientation: sideOrientation
  34365. };
  34366. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  34367. };
  34368. /**
  34369. * Creates an extruded polygon mesh, with depth in the Y direction. Please consider using the same method from the MeshBuilder class instead.
  34370. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-non-regular-polygon
  34371. * @param name defines the name of the mesh to create
  34372. * @param 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
  34373. * @param depth defines the height of extrusion
  34374. * @param scene defines the hosting scene
  34375. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  34376. * @param updatable defines if the mesh must be flagged as updatable
  34377. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34378. * @returns a new Mesh
  34379. */
  34380. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  34381. var options = {
  34382. shape: shape,
  34383. holes: holes,
  34384. depth: depth,
  34385. updatable: updatable,
  34386. sideOrientation: sideOrientation
  34387. };
  34388. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  34389. };
  34390. /**
  34391. * Creates an extruded shape mesh.
  34392. * The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters. Please consider using the same method from the MeshBuilder class instead
  34393. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34394. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34395. * @param name defines the name of the mesh to create
  34396. * @param 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
  34397. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  34398. * @param scale is the value to scale the shape
  34399. * @param rotation 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
  34400. * @param 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
  34401. * @param scene defines the hosting scene
  34402. * @param updatable defines if the mesh must be flagged as updatable
  34403. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34404. * @param 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/how_to/How_to_dynamically_morph_a_mesh#extruded-shape)
  34405. * @returns a new Mesh
  34406. */
  34407. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  34408. if (scene === void 0) { scene = null; }
  34409. var options = {
  34410. shape: shape,
  34411. path: path,
  34412. scale: scale,
  34413. rotation: rotation,
  34414. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34415. sideOrientation: sideOrientation,
  34416. instance: instance,
  34417. updatable: updatable
  34418. };
  34419. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  34420. };
  34421. /**
  34422. * Creates an custom extruded shape mesh.
  34423. * The custom extrusion is a parametric shape.
  34424. * It has no predefined shape. Its final shape will depend on the input parameters.
  34425. * Please consider using the same method from the MeshBuilder class instead
  34426. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34427. * @param name defines the name of the mesh to create
  34428. * @param 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
  34429. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  34430. * @param scaleFunction is a custom Javascript function called on each path point
  34431. * @param rotationFunction is a custom Javascript function called on each path point
  34432. * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  34433. * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray`
  34434. * @param 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
  34435. * @param scene defines the hosting scene
  34436. * @param updatable defines if the mesh must be flagged as updatable
  34437. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34438. * @param 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/how_to/how_to_dynamically_morph_a_mesh#extruded-shape)
  34439. * @returns a new Mesh
  34440. */
  34441. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  34442. var options = {
  34443. shape: shape,
  34444. path: path,
  34445. scaleFunction: scaleFunction,
  34446. rotationFunction: rotationFunction,
  34447. ribbonCloseArray: ribbonCloseArray,
  34448. ribbonClosePath: ribbonClosePath,
  34449. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34450. sideOrientation: sideOrientation,
  34451. instance: instance,
  34452. updatable: updatable
  34453. };
  34454. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  34455. };
  34456. /**
  34457. * Creates lathe mesh.
  34458. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  34459. * Please consider using the same method from the MeshBuilder class instead
  34460. * @param name defines the name of the mesh to create
  34461. * @param 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
  34462. * @param radius is the radius value of the lathe
  34463. * @param tessellation is the side number of the lathe.
  34464. * @param scene defines the hosting scene
  34465. * @param updatable defines if the mesh must be flagged as updatable
  34466. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34467. * @returns a new Mesh
  34468. */
  34469. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  34470. var options = {
  34471. shape: shape,
  34472. radius: radius,
  34473. tessellation: tessellation,
  34474. sideOrientation: sideOrientation,
  34475. updatable: updatable
  34476. };
  34477. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  34478. };
  34479. /**
  34480. * Creates a plane mesh. Please consider using the same method from the MeshBuilder class instead
  34481. * @param name defines the name of the mesh to create
  34482. * @param size sets the size (float) of both sides of the plane at once (default 1)
  34483. * @param scene defines the hosting scene
  34484. * @param updatable defines if the mesh must be flagged as updatable
  34485. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34486. * @returns a new Mesh
  34487. */
  34488. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  34489. var options = {
  34490. size: size,
  34491. width: size,
  34492. height: size,
  34493. sideOrientation: sideOrientation,
  34494. updatable: updatable
  34495. };
  34496. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  34497. };
  34498. /**
  34499. * Creates a ground mesh.
  34500. * Please consider using the same method from the MeshBuilder class instead
  34501. * @param name defines the name of the mesh to create
  34502. * @param width set the width of the ground
  34503. * @param height set the height of the ground
  34504. * @param subdivisions sets the number of subdivisions per side
  34505. * @param scene defines the hosting scene
  34506. * @param updatable defines if the mesh must be flagged as updatable
  34507. * @returns a new Mesh
  34508. */
  34509. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  34510. var options = {
  34511. width: width,
  34512. height: height,
  34513. subdivisions: subdivisions,
  34514. updatable: updatable
  34515. };
  34516. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  34517. };
  34518. /**
  34519. * Creates a tiled ground mesh.
  34520. * Please consider using the same method from the MeshBuilder class instead
  34521. * @param name defines the name of the mesh to create
  34522. * @param xmin set the ground minimum X coordinate
  34523. * @param zmin set the ground minimum Y coordinate
  34524. * @param xmax set the ground maximum X coordinate
  34525. * @param zmax set the ground maximum Z coordinate
  34526. * @param subdivisions is an 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
  34527. * @param precision is an 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
  34528. * @param scene defines the hosting scene
  34529. * @param updatable defines if the mesh must be flagged as updatable
  34530. * @returns a new Mesh
  34531. */
  34532. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  34533. var options = {
  34534. xmin: xmin,
  34535. zmin: zmin,
  34536. xmax: xmax,
  34537. zmax: zmax,
  34538. subdivisions: subdivisions,
  34539. precision: precision,
  34540. updatable: updatable
  34541. };
  34542. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  34543. };
  34544. /**
  34545. * Creates a ground mesh from a height map.
  34546. * Please consider using the same method from the MeshBuilder class instead
  34547. * @see http://doc.babylonjs.com/babylon101/height_map
  34548. * @param name defines the name of the mesh to create
  34549. * @param url sets the URL of the height map image resource
  34550. * @param width set the ground width size
  34551. * @param height set the ground height size
  34552. * @param subdivisions sets the number of subdivision per side
  34553. * @param minHeight is the minimum altitude on the ground
  34554. * @param maxHeight is the maximum altitude on the ground
  34555. * @param scene defines the hosting scene
  34556. * @param updatable defines if the mesh must be flagged as updatable
  34557. * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time)
  34558. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  34559. * @returns a new Mesh
  34560. */
  34561. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
  34562. var options = {
  34563. width: width,
  34564. height: height,
  34565. subdivisions: subdivisions,
  34566. minHeight: minHeight,
  34567. maxHeight: maxHeight,
  34568. updatable: updatable,
  34569. onReady: onReady,
  34570. alphaFilter: alphaFilter
  34571. };
  34572. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34573. };
  34574. /**
  34575. * Creates a tube mesh.
  34576. * The tube is a parametric shape.
  34577. * It has no predefined shape. Its final shape will depend on the input parameters.
  34578. * Please consider using the same method from the MeshBuilder class instead
  34579. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34580. * @param name defines the name of the mesh to create
  34581. * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube
  34582. * @param radius sets the tube radius size
  34583. * @param tessellation is the number of sides on the tubular surface
  34584. * @param radiusFunction is a custom function. If it is not null, it overwrittes the parameter `radius`. 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
  34585. * @param 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
  34586. * @param scene defines the hosting scene
  34587. * @param updatable defines if the mesh must be flagged as updatable
  34588. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34589. * @param instance is an instance of an existing Tube object to be updated with the passed `pathArray` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#tube)
  34590. * @returns a new Mesh
  34591. */
  34592. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34593. var options = {
  34594. path: path,
  34595. radius: radius,
  34596. tessellation: tessellation,
  34597. radiusFunction: radiusFunction,
  34598. arc: 1,
  34599. cap: cap,
  34600. updatable: updatable,
  34601. sideOrientation: sideOrientation,
  34602. instance: instance
  34603. };
  34604. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34605. };
  34606. /**
  34607. * Creates a polyhedron mesh.
  34608. * Please consider using the same method from the MeshBuilder class instead.
  34609. * * 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
  34610. * * The parameter `size` (positive float, default 1) sets the polygon size
  34611. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  34612. * * 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`
  34613. * * 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
  34614. * * 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)`)
  34615. * * 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
  34616. * * 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
  34617. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34618. * * 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
  34619. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  34620. * @param name defines the name of the mesh to create
  34621. * @param options defines the options used to create the mesh
  34622. * @param scene defines the hosting scene
  34623. * @returns a new Mesh
  34624. */
  34625. Mesh.CreatePolyhedron = function (name, options, scene) {
  34626. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34627. };
  34628. /**
  34629. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  34630. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  34631. * * 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`)
  34632. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  34633. * * 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
  34634. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34635. * * 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
  34636. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  34637. * @param name defines the name of the mesh
  34638. * @param options defines the options used to create the mesh
  34639. * @param scene defines the hosting scene
  34640. * @returns a new Mesh
  34641. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  34642. */
  34643. Mesh.CreateIcoSphere = function (name, options, scene) {
  34644. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34645. };
  34646. /**
  34647. * Creates a decal mesh.
  34648. * Please consider using the same method from the MeshBuilder class instead.
  34649. * A decal is a mesh usually applied as a model onto the surface of another mesh
  34650. * @param name defines the name of the mesh
  34651. * @param sourceMesh defines the mesh receiving the decal
  34652. * @param position sets the position of the decal in world coordinates
  34653. * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates
  34654. * @param size sets the decal scaling
  34655. * @param angle sets the angle to rotate the decal
  34656. * @returns a new Mesh
  34657. */
  34658. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34659. var options = {
  34660. position: position,
  34661. normal: normal,
  34662. size: size,
  34663. angle: angle
  34664. };
  34665. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34666. };
  34667. // Skeletons
  34668. /**
  34669. * Prepare internal position array for software CPU skinning
  34670. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh
  34671. */
  34672. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34673. if (!this._sourcePositions) {
  34674. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34675. if (!source) {
  34676. return this._sourcePositions;
  34677. }
  34678. this._sourcePositions = new Float32Array(source);
  34679. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34680. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34681. }
  34682. }
  34683. return this._sourcePositions;
  34684. };
  34685. /**
  34686. * Prepare internal normal array for software CPU skinning
  34687. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34688. */
  34689. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34690. if (!this._sourceNormals) {
  34691. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34692. if (!source) {
  34693. return this._sourceNormals;
  34694. }
  34695. this._sourceNormals = new Float32Array(source);
  34696. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34697. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34698. }
  34699. }
  34700. return this._sourceNormals;
  34701. };
  34702. /**
  34703. * Updates the vertex buffer by applying transformation from the bones
  34704. * @param skeleton defines the skeleton to apply to current mesh
  34705. * @returns the current mesh
  34706. */
  34707. Mesh.prototype.applySkeleton = function (skeleton) {
  34708. if (!this.geometry) {
  34709. return this;
  34710. }
  34711. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  34712. return this;
  34713. }
  34714. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  34715. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34716. return this;
  34717. }
  34718. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34719. return this;
  34720. }
  34721. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34722. return this;
  34723. }
  34724. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34725. return this;
  34726. }
  34727. if (!this._sourcePositions) {
  34728. var submeshes = this.subMeshes.slice();
  34729. this.setPositionsForCPUSkinning();
  34730. this.subMeshes = submeshes;
  34731. }
  34732. if (!this._sourceNormals) {
  34733. this.setNormalsForCPUSkinning();
  34734. }
  34735. // positionsData checks for not being Float32Array will only pass at most once
  34736. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34737. if (!positionsData) {
  34738. return this;
  34739. }
  34740. if (!(positionsData instanceof Float32Array)) {
  34741. positionsData = new Float32Array(positionsData);
  34742. }
  34743. // normalsData checks for not being Float32Array will only pass at most once
  34744. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34745. if (!normalsData) {
  34746. return this;
  34747. }
  34748. if (!(normalsData instanceof Float32Array)) {
  34749. normalsData = new Float32Array(normalsData);
  34750. }
  34751. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34752. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34753. if (!matricesWeightsData || !matricesIndicesData) {
  34754. return this;
  34755. }
  34756. var needExtras = this.numBoneInfluencers > 4;
  34757. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34758. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34759. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34760. var tempVector3 = BABYLON.Vector3.Zero();
  34761. var finalMatrix = new BABYLON.Matrix();
  34762. var tempMatrix = new BABYLON.Matrix();
  34763. var matWeightIdx = 0;
  34764. var inf;
  34765. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34766. var weight;
  34767. for (inf = 0; inf < 4; inf++) {
  34768. weight = matricesWeightsData[matWeightIdx + inf];
  34769. if (weight > 0) {
  34770. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34771. finalMatrix.addToSelf(tempMatrix);
  34772. }
  34773. }
  34774. if (needExtras) {
  34775. for (inf = 0; inf < 4; inf++) {
  34776. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34777. if (weight > 0) {
  34778. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34779. finalMatrix.addToSelf(tempMatrix);
  34780. }
  34781. }
  34782. }
  34783. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34784. tempVector3.toArray(positionsData, index);
  34785. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34786. tempVector3.toArray(normalsData, index);
  34787. finalMatrix.reset();
  34788. }
  34789. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34790. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34791. return this;
  34792. };
  34793. // Tools
  34794. /**
  34795. * Returns an object containing a min and max Vector3 which are the minimum and maximum vectors of each mesh bounding box from the passed array, in the world coordinates
  34796. * @param meshes defines the list of meshes to scan
  34797. * @returns an object `{min:` Vector3`, max:` Vector3`}`
  34798. */
  34799. Mesh.MinMax = function (meshes) {
  34800. var minVector = null;
  34801. var maxVector = null;
  34802. meshes.forEach(function (mesh, index, array) {
  34803. var boundingInfo = mesh.getBoundingInfo();
  34804. var boundingBox = boundingInfo.boundingBox;
  34805. if (!minVector || !maxVector) {
  34806. minVector = boundingBox.minimumWorld;
  34807. maxVector = boundingBox.maximumWorld;
  34808. }
  34809. else {
  34810. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34811. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34812. }
  34813. });
  34814. if (!minVector || !maxVector) {
  34815. return {
  34816. min: BABYLON.Vector3.Zero(),
  34817. max: BABYLON.Vector3.Zero()
  34818. };
  34819. }
  34820. return {
  34821. min: minVector,
  34822. max: maxVector
  34823. };
  34824. };
  34825. /**
  34826. * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array
  34827. * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object
  34828. * @returns a vector3
  34829. */
  34830. Mesh.Center = function (meshesOrMinMaxVector) {
  34831. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34832. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34833. };
  34834. /**
  34835. * Merge the array of meshes into a single mesh for performance reasons.
  34836. * @param meshes defines he vertices source. They should all be of the same material. Entries can empty
  34837. * @param disposeSource when true (default), dispose of the vertices from the source meshes
  34838. * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true
  34839. * @param meshSubclass when set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34840. * @param subdivideWithSubMeshes when true (false default), subdivide mesh to his subMesh array with meshes source.
  34841. * @returns a new mesh
  34842. */
  34843. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34844. if (disposeSource === void 0) { disposeSource = true; }
  34845. var index;
  34846. if (!allow32BitsIndices) {
  34847. var totalVertices = 0;
  34848. // Counting vertices
  34849. for (index = 0; index < meshes.length; index++) {
  34850. if (meshes[index]) {
  34851. totalVertices += meshes[index].getTotalVertices();
  34852. if (totalVertices > 65536) {
  34853. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34854. return null;
  34855. }
  34856. }
  34857. }
  34858. }
  34859. // Merge
  34860. var vertexData = null;
  34861. var otherVertexData;
  34862. var indiceArray = new Array();
  34863. var source = null;
  34864. for (index = 0; index < meshes.length; index++) {
  34865. if (meshes[index]) {
  34866. var wm = meshes[index].computeWorldMatrix(true);
  34867. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34868. otherVertexData.transform(wm);
  34869. if (vertexData) {
  34870. vertexData.merge(otherVertexData, allow32BitsIndices);
  34871. }
  34872. else {
  34873. vertexData = otherVertexData;
  34874. source = meshes[index];
  34875. }
  34876. if (subdivideWithSubMeshes) {
  34877. indiceArray.push(meshes[index].getTotalIndices());
  34878. }
  34879. }
  34880. }
  34881. source = source;
  34882. if (!meshSubclass) {
  34883. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34884. }
  34885. vertexData.applyToMesh(meshSubclass);
  34886. // Setting properties
  34887. meshSubclass.material = source.material;
  34888. meshSubclass.checkCollisions = source.checkCollisions;
  34889. // Cleaning
  34890. if (disposeSource) {
  34891. for (index = 0; index < meshes.length; index++) {
  34892. if (meshes[index]) {
  34893. meshes[index].dispose();
  34894. }
  34895. }
  34896. }
  34897. // Subdivide
  34898. if (subdivideWithSubMeshes) {
  34899. //-- removal of global submesh
  34900. meshSubclass.releaseSubMeshes();
  34901. index = 0;
  34902. var offset = 0;
  34903. //-- apply subdivision according to index table
  34904. while (index < indiceArray.length) {
  34905. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34906. offset += indiceArray[index];
  34907. index++;
  34908. }
  34909. }
  34910. return meshSubclass;
  34911. };
  34912. // Consts
  34913. /**
  34914. * Mesh side orientation : usually the external or front surface
  34915. */
  34916. Mesh.FRONTSIDE = 0;
  34917. /**
  34918. * Mesh side orientation : usually the internal or back surface
  34919. */
  34920. Mesh.BACKSIDE = 1;
  34921. /**
  34922. * Mesh side orientation : both internal and external or front and back surfaces
  34923. */
  34924. Mesh.DOUBLESIDE = 2;
  34925. /**
  34926. * Mesh side orientation : by default, `FRONTSIDE`
  34927. */
  34928. Mesh.DEFAULTSIDE = 0;
  34929. /**
  34930. * Mesh cap setting : no cap
  34931. */
  34932. Mesh.NO_CAP = 0;
  34933. /**
  34934. * Mesh cap setting : one cap at the beginning of the mesh
  34935. */
  34936. Mesh.CAP_START = 1;
  34937. /**
  34938. * Mesh cap setting : one cap at the end of the mesh
  34939. */
  34940. Mesh.CAP_END = 2;
  34941. /**
  34942. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  34943. */
  34944. Mesh.CAP_ALL = 3;
  34945. return Mesh;
  34946. }(BABYLON.AbstractMesh));
  34947. BABYLON.Mesh = Mesh;
  34948. })(BABYLON || (BABYLON = {}));
  34949. //# sourceMappingURL=babylon.mesh.js.map
  34950. var BABYLON;
  34951. (function (BABYLON) {
  34952. /**
  34953. * Base class for submeshes
  34954. */
  34955. var BaseSubMesh = /** @class */ (function () {
  34956. function BaseSubMesh() {
  34957. }
  34958. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34959. /**
  34960. * Gets associated effect
  34961. */
  34962. get: function () {
  34963. return this._materialEffect;
  34964. },
  34965. enumerable: true,
  34966. configurable: true
  34967. });
  34968. /**
  34969. * Sets associated effect (effect used to render this submesh)
  34970. * @param effect defines the effect to associate with
  34971. * @param defines defines the set of defines used to compile this effect
  34972. */
  34973. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34974. if (defines === void 0) { defines = null; }
  34975. if (this._materialEffect === effect) {
  34976. if (!effect) {
  34977. this._materialDefines = null;
  34978. }
  34979. return;
  34980. }
  34981. this._materialDefines = defines;
  34982. this._materialEffect = effect;
  34983. };
  34984. return BaseSubMesh;
  34985. }());
  34986. BABYLON.BaseSubMesh = BaseSubMesh;
  34987. /**
  34988. * Defines a subdivision inside a mesh
  34989. */
  34990. var SubMesh = /** @class */ (function (_super) {
  34991. __extends(SubMesh, _super);
  34992. /**
  34993. * Creates a new submesh
  34994. * @param materialIndex defines the material index to use
  34995. * @param verticesStart defines vertex index start
  34996. * @param verticesCount defines vertices count
  34997. * @param indexStart defines index start
  34998. * @param indexCount defines indices count
  34999. * @param mesh defines the parent mesh
  35000. * @param renderingMesh defines an optional rendering mesh
  35001. * @param createBoundingBox defines if bounding box should be created for this submesh
  35002. */
  35003. function SubMesh(
  35004. /** the material index to use */
  35005. materialIndex,
  35006. /** vertex index start */
  35007. verticesStart,
  35008. /** vertices count */
  35009. verticesCount,
  35010. /** index start */
  35011. indexStart,
  35012. /** indices count */
  35013. indexCount, mesh, renderingMesh, createBoundingBox) {
  35014. if (createBoundingBox === void 0) { createBoundingBox = true; }
  35015. var _this = _super.call(this) || this;
  35016. _this.materialIndex = materialIndex;
  35017. _this.verticesStart = verticesStart;
  35018. _this.verticesCount = verticesCount;
  35019. _this.indexStart = indexStart;
  35020. _this.indexCount = indexCount;
  35021. /** @hidden */
  35022. _this._renderId = 0;
  35023. _this._mesh = mesh;
  35024. _this._renderingMesh = renderingMesh || mesh;
  35025. mesh.subMeshes.push(_this);
  35026. _this._trianglePlanes = [];
  35027. _this._id = mesh.subMeshes.length - 1;
  35028. if (createBoundingBox) {
  35029. _this.refreshBoundingInfo();
  35030. mesh.computeWorldMatrix(true);
  35031. }
  35032. return _this;
  35033. }
  35034. /**
  35035. * Add a new submesh to a mesh
  35036. * @param materialIndex defines the material index to use
  35037. * @param verticesStart defines vertex index start
  35038. * @param verticesCount defines vertices count
  35039. * @param indexStart defines index start
  35040. * @param indexCount defines indices count
  35041. * @param mesh defines the parent mesh
  35042. * @param renderingMesh defines an optional rendering mesh
  35043. * @param createBoundingBox defines if bounding box should be created for this submesh
  35044. * @returns the new submesh
  35045. */
  35046. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  35047. if (createBoundingBox === void 0) { createBoundingBox = true; }
  35048. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  35049. };
  35050. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  35051. /**
  35052. * Returns true if this submesh covers the entire parent mesh
  35053. * @ignorenaming
  35054. */
  35055. get: function () {
  35056. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  35057. },
  35058. enumerable: true,
  35059. configurable: true
  35060. });
  35061. /**
  35062. * Returns the submesh BoudingInfo object
  35063. * @returns current bounding info (or mesh's one if the submesh is global)
  35064. */
  35065. SubMesh.prototype.getBoundingInfo = function () {
  35066. if (this.IsGlobal) {
  35067. return this._mesh.getBoundingInfo();
  35068. }
  35069. return this._boundingInfo;
  35070. };
  35071. /**
  35072. * Sets the submesh BoundingInfo
  35073. * @param boundingInfo defines the new bounding info to use
  35074. * @returns the SubMesh
  35075. */
  35076. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  35077. this._boundingInfo = boundingInfo;
  35078. return this;
  35079. };
  35080. /**
  35081. * Returns the mesh of the current submesh
  35082. * @return the parent mesh
  35083. */
  35084. SubMesh.prototype.getMesh = function () {
  35085. return this._mesh;
  35086. };
  35087. /**
  35088. * Returns the rendering mesh of the submesh
  35089. * @returns the rendering mesh (could be different from parent mesh)
  35090. */
  35091. SubMesh.prototype.getRenderingMesh = function () {
  35092. return this._renderingMesh;
  35093. };
  35094. /**
  35095. * Returns the submesh material
  35096. * @returns null or the current material
  35097. */
  35098. SubMesh.prototype.getMaterial = function () {
  35099. var rootMaterial = this._renderingMesh.material;
  35100. if (rootMaterial === null || rootMaterial === undefined) {
  35101. return this._mesh.getScene().defaultMaterial;
  35102. }
  35103. else if (rootMaterial.getSubMaterial) {
  35104. var multiMaterial = rootMaterial;
  35105. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  35106. if (this._currentMaterial !== effectiveMaterial) {
  35107. this._currentMaterial = effectiveMaterial;
  35108. this._materialDefines = null;
  35109. }
  35110. return effectiveMaterial;
  35111. }
  35112. return rootMaterial;
  35113. };
  35114. // Methods
  35115. /**
  35116. * Sets a new updated BoundingInfo object to the submesh
  35117. * @returns the SubMesh
  35118. */
  35119. SubMesh.prototype.refreshBoundingInfo = function () {
  35120. this._lastColliderWorldVertices = null;
  35121. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  35122. return this;
  35123. }
  35124. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35125. if (!data) {
  35126. this._boundingInfo = this._mesh.getBoundingInfo();
  35127. return this;
  35128. }
  35129. var indices = this._renderingMesh.getIndices();
  35130. var extend;
  35131. //is this the only submesh?
  35132. if (this.indexStart === 0 && this.indexCount === indices.length) {
  35133. var boundingInfo = this._renderingMesh.getBoundingInfo();
  35134. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  35135. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  35136. }
  35137. else {
  35138. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  35139. }
  35140. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  35141. return this;
  35142. };
  35143. /** @hidden */
  35144. SubMesh.prototype._checkCollision = function (collider) {
  35145. var boundingInfo = this.getBoundingInfo();
  35146. return boundingInfo._checkCollision(collider);
  35147. };
  35148. /**
  35149. * Updates the submesh BoundingInfo
  35150. * @param world defines the world matrix to use to update the bounding info
  35151. * @returns the submesh
  35152. */
  35153. SubMesh.prototype.updateBoundingInfo = function (world) {
  35154. var boundingInfo = this.getBoundingInfo();
  35155. if (!boundingInfo) {
  35156. this.refreshBoundingInfo();
  35157. boundingInfo = this.getBoundingInfo();
  35158. }
  35159. boundingInfo.update(world);
  35160. return this;
  35161. };
  35162. /**
  35163. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  35164. * @param frustumPlanes defines the frustum planes
  35165. * @returns true if the submesh is intersecting with the frustum
  35166. */
  35167. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  35168. var boundingInfo = this.getBoundingInfo();
  35169. if (!boundingInfo) {
  35170. return false;
  35171. }
  35172. return boundingInfo.isInFrustum(frustumPlanes, this._mesh.cullingStrategy);
  35173. };
  35174. /**
  35175. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes
  35176. * @param frustumPlanes defines the frustum planes
  35177. * @returns true if the submesh is inside the frustum
  35178. */
  35179. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  35180. var boundingInfo = this.getBoundingInfo();
  35181. if (!boundingInfo) {
  35182. return false;
  35183. }
  35184. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  35185. };
  35186. /**
  35187. * Renders the submesh
  35188. * @param enableAlphaMode defines if alpha needs to be used
  35189. * @returns the submesh
  35190. */
  35191. SubMesh.prototype.render = function (enableAlphaMode) {
  35192. this._renderingMesh.render(this, enableAlphaMode);
  35193. return this;
  35194. };
  35195. /**
  35196. * @hidden
  35197. */
  35198. SubMesh.prototype._getLinesIndexBuffer = function (indices, engine) {
  35199. if (!this._linesIndexBuffer) {
  35200. var linesIndices = [];
  35201. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  35202. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  35203. }
  35204. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  35205. this._linesIndexCount = linesIndices.length;
  35206. }
  35207. return this._linesIndexBuffer;
  35208. };
  35209. /**
  35210. * Checks if the submesh intersects with a ray
  35211. * @param ray defines the ray to test
  35212. * @returns true is the passed ray intersects the submesh bounding box
  35213. */
  35214. SubMesh.prototype.canIntersects = function (ray) {
  35215. var boundingInfo = this.getBoundingInfo();
  35216. if (!boundingInfo) {
  35217. return false;
  35218. }
  35219. return ray.intersectsBox(boundingInfo.boundingBox);
  35220. };
  35221. /**
  35222. * Intersects current submesh with a ray
  35223. * @param ray defines the ray to test
  35224. * @param positions defines mesh's positions array
  35225. * @param indices defines mesh's indices array
  35226. * @param fastCheck defines if only bounding info should be used
  35227. * @returns intersection info or null if no intersection
  35228. */
  35229. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  35230. var intersectInfo = null;
  35231. var material = this.getMaterial();
  35232. if (!material) {
  35233. return null;
  35234. }
  35235. switch (material.fillMode) {
  35236. case BABYLON.Material.PointListDrawMode:
  35237. case BABYLON.Material.LineListDrawMode:
  35238. case BABYLON.Material.LineLoopDrawMode:
  35239. case BABYLON.Material.LineStripDrawMode:
  35240. case BABYLON.Material.TriangleFanDrawMode:
  35241. case BABYLON.Material.TriangleStripDrawMode:
  35242. return null;
  35243. }
  35244. // LineMesh first as it's also a Mesh...
  35245. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  35246. var lineMesh = this._mesh;
  35247. // Line test
  35248. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  35249. var p0 = positions[indices[index]];
  35250. var p1 = positions[indices[index + 1]];
  35251. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  35252. if (length < 0) {
  35253. continue;
  35254. }
  35255. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  35256. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  35257. if (fastCheck) {
  35258. break;
  35259. }
  35260. }
  35261. }
  35262. }
  35263. else {
  35264. // Triangles test
  35265. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  35266. var p0 = positions[indices[index]];
  35267. var p1 = positions[indices[index + 1]];
  35268. var p2 = positions[indices[index + 2]];
  35269. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  35270. if (currentIntersectInfo) {
  35271. if (currentIntersectInfo.distance < 0) {
  35272. continue;
  35273. }
  35274. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  35275. intersectInfo = currentIntersectInfo;
  35276. intersectInfo.faceId = index / 3;
  35277. if (fastCheck) {
  35278. break;
  35279. }
  35280. }
  35281. }
  35282. }
  35283. }
  35284. return intersectInfo;
  35285. };
  35286. /** @hidden */
  35287. SubMesh.prototype._rebuild = function () {
  35288. if (this._linesIndexBuffer) {
  35289. this._linesIndexBuffer = null;
  35290. }
  35291. };
  35292. // Clone
  35293. /**
  35294. * Creates a new submesh from the passed mesh
  35295. * @param newMesh defines the new hosting mesh
  35296. * @param newRenderingMesh defines an optional rendering mesh
  35297. * @returns the new submesh
  35298. */
  35299. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  35300. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  35301. if (!this.IsGlobal) {
  35302. var boundingInfo = this.getBoundingInfo();
  35303. if (!boundingInfo) {
  35304. return result;
  35305. }
  35306. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  35307. }
  35308. return result;
  35309. };
  35310. // Dispose
  35311. /**
  35312. * Release associated resources
  35313. */
  35314. SubMesh.prototype.dispose = function () {
  35315. if (this._linesIndexBuffer) {
  35316. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  35317. this._linesIndexBuffer = null;
  35318. }
  35319. // Remove from mesh
  35320. var index = this._mesh.subMeshes.indexOf(this);
  35321. this._mesh.subMeshes.splice(index, 1);
  35322. };
  35323. // Statics
  35324. /**
  35325. * Creates a new submesh from indices data
  35326. * @param materialIndex the index of the main mesh material
  35327. * @param startIndex the index where to start the copy in the mesh indices array
  35328. * @param indexCount the number of indices to copy then from the startIndex
  35329. * @param mesh the main mesh to create the submesh from
  35330. * @param renderingMesh the optional rendering mesh
  35331. * @returns a new submesh
  35332. */
  35333. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  35334. var minVertexIndex = Number.MAX_VALUE;
  35335. var maxVertexIndex = -Number.MAX_VALUE;
  35336. renderingMesh = (renderingMesh || mesh);
  35337. var indices = renderingMesh.getIndices();
  35338. for (var index = startIndex; index < startIndex + indexCount; index++) {
  35339. var vertexIndex = indices[index];
  35340. if (vertexIndex < minVertexIndex)
  35341. minVertexIndex = vertexIndex;
  35342. if (vertexIndex > maxVertexIndex)
  35343. maxVertexIndex = vertexIndex;
  35344. }
  35345. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  35346. };
  35347. return SubMesh;
  35348. }(BaseSubMesh));
  35349. BABYLON.SubMesh = SubMesh;
  35350. })(BABYLON || (BABYLON = {}));
  35351. //# sourceMappingURL=babylon.subMesh.js.map
  35352. var __assign = (this && this.__assign) || function () {
  35353. __assign = Object.assign || function(t) {
  35354. for (var s, i = 1, n = arguments.length; i < n; i++) {
  35355. s = arguments[i];
  35356. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  35357. t[p] = s[p];
  35358. }
  35359. return t;
  35360. };
  35361. return __assign.apply(this, arguments);
  35362. };
  35363. var BABYLON;
  35364. (function (BABYLON) {
  35365. /**
  35366. * Manages the defines for the Material
  35367. */
  35368. var MaterialDefines = /** @class */ (function () {
  35369. function MaterialDefines() {
  35370. this._isDirty = true;
  35371. /** @hidden */
  35372. this._areLightsDirty = true;
  35373. /** @hidden */
  35374. this._areAttributesDirty = true;
  35375. /** @hidden */
  35376. this._areTexturesDirty = true;
  35377. /** @hidden */
  35378. this._areFresnelDirty = true;
  35379. /** @hidden */
  35380. this._areMiscDirty = true;
  35381. /** @hidden */
  35382. this._areImageProcessingDirty = true;
  35383. /** @hidden */
  35384. this._normals = false;
  35385. /** @hidden */
  35386. this._uvs = false;
  35387. /** @hidden */
  35388. this._needNormals = false;
  35389. /** @hidden */
  35390. this._needUVs = false;
  35391. }
  35392. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  35393. /**
  35394. * Specifies if the material needs to be re-calculated
  35395. */
  35396. get: function () {
  35397. return this._isDirty;
  35398. },
  35399. enumerable: true,
  35400. configurable: true
  35401. });
  35402. /**
  35403. * Marks the material to indicate that it has been re-calculated
  35404. */
  35405. MaterialDefines.prototype.markAsProcessed = function () {
  35406. this._isDirty = false;
  35407. this._areAttributesDirty = false;
  35408. this._areTexturesDirty = false;
  35409. this._areFresnelDirty = false;
  35410. this._areLightsDirty = false;
  35411. this._areMiscDirty = false;
  35412. this._areImageProcessingDirty = false;
  35413. };
  35414. /**
  35415. * Marks the material to indicate that it needs to be re-calculated
  35416. */
  35417. MaterialDefines.prototype.markAsUnprocessed = function () {
  35418. this._isDirty = true;
  35419. };
  35420. /**
  35421. * Marks the material to indicate all of its defines need to be re-calculated
  35422. */
  35423. MaterialDefines.prototype.markAllAsDirty = function () {
  35424. this._areTexturesDirty = true;
  35425. this._areAttributesDirty = true;
  35426. this._areLightsDirty = true;
  35427. this._areFresnelDirty = true;
  35428. this._areMiscDirty = true;
  35429. this._areImageProcessingDirty = true;
  35430. this._isDirty = true;
  35431. };
  35432. /**
  35433. * Marks the material to indicate that image processing needs to be re-calculated
  35434. */
  35435. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  35436. this._areImageProcessingDirty = true;
  35437. this._isDirty = true;
  35438. };
  35439. /**
  35440. * Marks the material to indicate the lights need to be re-calculated
  35441. */
  35442. MaterialDefines.prototype.markAsLightDirty = function () {
  35443. this._areLightsDirty = true;
  35444. this._isDirty = true;
  35445. };
  35446. /**
  35447. * Marks the attribute state as changed
  35448. */
  35449. MaterialDefines.prototype.markAsAttributesDirty = function () {
  35450. this._areAttributesDirty = true;
  35451. this._isDirty = true;
  35452. };
  35453. /**
  35454. * Marks the texture state as changed
  35455. */
  35456. MaterialDefines.prototype.markAsTexturesDirty = function () {
  35457. this._areTexturesDirty = true;
  35458. this._isDirty = true;
  35459. };
  35460. /**
  35461. * Marks the fresnel state as changed
  35462. */
  35463. MaterialDefines.prototype.markAsFresnelDirty = function () {
  35464. this._areFresnelDirty = true;
  35465. this._isDirty = true;
  35466. };
  35467. /**
  35468. * Marks the misc state as changed
  35469. */
  35470. MaterialDefines.prototype.markAsMiscDirty = function () {
  35471. this._areMiscDirty = true;
  35472. this._isDirty = true;
  35473. };
  35474. /**
  35475. * Rebuilds the material defines
  35476. */
  35477. MaterialDefines.prototype.rebuild = function () {
  35478. if (this._keys) {
  35479. delete this._keys;
  35480. }
  35481. this._keys = [];
  35482. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  35483. var key = _a[_i];
  35484. if (key[0] === "_") {
  35485. continue;
  35486. }
  35487. this._keys.push(key);
  35488. }
  35489. };
  35490. /**
  35491. * Specifies if two material defines are equal
  35492. * @param other - A material define instance to compare to
  35493. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  35494. */
  35495. MaterialDefines.prototype.isEqual = function (other) {
  35496. if (this._keys.length !== other._keys.length) {
  35497. return false;
  35498. }
  35499. for (var index = 0; index < this._keys.length; index++) {
  35500. var prop = this._keys[index];
  35501. if (this[prop] !== other[prop]) {
  35502. return false;
  35503. }
  35504. }
  35505. return true;
  35506. };
  35507. /**
  35508. * Clones this instance's defines to another instance
  35509. * @param other - material defines to clone values to
  35510. */
  35511. MaterialDefines.prototype.cloneTo = function (other) {
  35512. if (this._keys.length !== other._keys.length) {
  35513. other._keys = this._keys.slice(0);
  35514. }
  35515. for (var index = 0; index < this._keys.length; index++) {
  35516. var prop = this._keys[index];
  35517. other[prop] = this[prop];
  35518. }
  35519. };
  35520. /**
  35521. * Resets the material define values
  35522. */
  35523. MaterialDefines.prototype.reset = function () {
  35524. for (var index = 0; index < this._keys.length; index++) {
  35525. var prop = this._keys[index];
  35526. var type = typeof this[prop];
  35527. switch (type) {
  35528. case "number":
  35529. this[prop] = 0;
  35530. break;
  35531. case "string":
  35532. this[prop] = "";
  35533. break;
  35534. default:
  35535. this[prop] = false;
  35536. break;
  35537. }
  35538. }
  35539. };
  35540. /**
  35541. * Converts the material define values to a string
  35542. * @returns - String of material define information
  35543. */
  35544. MaterialDefines.prototype.toString = function () {
  35545. var result = "";
  35546. for (var index = 0; index < this._keys.length; index++) {
  35547. var prop = this._keys[index];
  35548. var value = this[prop];
  35549. var type = typeof value;
  35550. switch (type) {
  35551. case "number":
  35552. case "string":
  35553. result += "#define " + prop + " " + value + "\n";
  35554. break;
  35555. default:
  35556. if (value) {
  35557. result += "#define " + prop + "\n";
  35558. }
  35559. break;
  35560. }
  35561. }
  35562. return result;
  35563. };
  35564. return MaterialDefines;
  35565. }());
  35566. BABYLON.MaterialDefines = MaterialDefines;
  35567. /**
  35568. * Base class for the main features of a material in Babylon.js
  35569. */
  35570. var Material = /** @class */ (function () {
  35571. /**
  35572. * Creates a material instance
  35573. * @param name defines the name of the material
  35574. * @param scene defines the scene to reference
  35575. * @param doNotAdd specifies if the material should be added to the scene
  35576. */
  35577. function Material(name, scene, doNotAdd) {
  35578. /**
  35579. * Specifies if the ready state should be checked on each call
  35580. */
  35581. this.checkReadyOnEveryCall = false;
  35582. /**
  35583. * Specifies if the ready state should be checked once
  35584. */
  35585. this.checkReadyOnlyOnce = false;
  35586. /**
  35587. * The state of the material
  35588. */
  35589. this.state = "";
  35590. /**
  35591. * The alpha value of the material
  35592. */
  35593. this._alpha = 1.0;
  35594. /**
  35595. * Specifies if back face culling is enabled
  35596. */
  35597. this._backFaceCulling = true;
  35598. /**
  35599. * Specifies if the material should be serialized
  35600. */
  35601. this.doNotSerialize = false;
  35602. /**
  35603. * Specifies if the effect should be stored on sub meshes
  35604. */
  35605. this.storeEffectOnSubMeshes = false;
  35606. /**
  35607. * An event triggered when the material is disposed
  35608. */
  35609. this.onDisposeObservable = new BABYLON.Observable();
  35610. /**
  35611. * Stores the value of the alpha mode
  35612. */
  35613. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  35614. /**
  35615. * Stores the state of the need depth pre-pass value
  35616. */
  35617. this._needDepthPrePass = false;
  35618. /**
  35619. * Specifies if depth writing should be disabled
  35620. */
  35621. this.disableDepthWrite = false;
  35622. /**
  35623. * Specifies if depth writing should be forced
  35624. */
  35625. this.forceDepthWrite = false;
  35626. /**
  35627. * Specifies if there should be a separate pass for culling
  35628. */
  35629. this.separateCullingPass = false;
  35630. /**
  35631. * Stores the state specifing if fog should be enabled
  35632. */
  35633. this._fogEnabled = true;
  35634. /**
  35635. * Stores the size of points
  35636. */
  35637. this.pointSize = 1.0;
  35638. /**
  35639. * Stores the z offset value
  35640. */
  35641. this.zOffset = 0;
  35642. /**
  35643. * @hidden
  35644. * Specifies if the material was previously ready
  35645. */
  35646. this._wasPreviouslyReady = false;
  35647. /**
  35648. * Stores the fill mode state
  35649. */
  35650. this._fillMode = Material.TriangleFillMode;
  35651. this.name = name;
  35652. this.id = name || BABYLON.Tools.RandomId();
  35653. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35654. this.uniqueId = this._scene.getUniqueId();
  35655. if (this._scene.useRightHandedSystem) {
  35656. this.sideOrientation = Material.ClockWiseSideOrientation;
  35657. }
  35658. else {
  35659. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  35660. }
  35661. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  35662. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  35663. if (!doNotAdd) {
  35664. this._scene.materials.push(this);
  35665. this._scene.onNewMaterialAddedObservable.notifyObservers(this);
  35666. }
  35667. }
  35668. Object.defineProperty(Material, "TriangleFillMode", {
  35669. /**
  35670. * Returns the triangle fill mode
  35671. */
  35672. get: function () {
  35673. return Material._TriangleFillMode;
  35674. },
  35675. enumerable: true,
  35676. configurable: true
  35677. });
  35678. Object.defineProperty(Material, "WireFrameFillMode", {
  35679. /**
  35680. * Returns the wireframe mode
  35681. */
  35682. get: function () {
  35683. return Material._WireFrameFillMode;
  35684. },
  35685. enumerable: true,
  35686. configurable: true
  35687. });
  35688. Object.defineProperty(Material, "PointFillMode", {
  35689. /**
  35690. * Returns the point fill mode
  35691. */
  35692. get: function () {
  35693. return Material._PointFillMode;
  35694. },
  35695. enumerable: true,
  35696. configurable: true
  35697. });
  35698. Object.defineProperty(Material, "PointListDrawMode", {
  35699. /**
  35700. * Returns the point list draw mode
  35701. */
  35702. get: function () {
  35703. return Material._PointListDrawMode;
  35704. },
  35705. enumerable: true,
  35706. configurable: true
  35707. });
  35708. Object.defineProperty(Material, "LineListDrawMode", {
  35709. /**
  35710. * Returns the line list draw mode
  35711. */
  35712. get: function () {
  35713. return Material._LineListDrawMode;
  35714. },
  35715. enumerable: true,
  35716. configurable: true
  35717. });
  35718. Object.defineProperty(Material, "LineLoopDrawMode", {
  35719. /**
  35720. * Returns the line loop draw mode
  35721. */
  35722. get: function () {
  35723. return Material._LineLoopDrawMode;
  35724. },
  35725. enumerable: true,
  35726. configurable: true
  35727. });
  35728. Object.defineProperty(Material, "LineStripDrawMode", {
  35729. /**
  35730. * Returns the line strip draw mode
  35731. */
  35732. get: function () {
  35733. return Material._LineStripDrawMode;
  35734. },
  35735. enumerable: true,
  35736. configurable: true
  35737. });
  35738. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35739. /**
  35740. * Returns the triangle strip draw mode
  35741. */
  35742. get: function () {
  35743. return Material._TriangleStripDrawMode;
  35744. },
  35745. enumerable: true,
  35746. configurable: true
  35747. });
  35748. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35749. /**
  35750. * Returns the triangle fan draw mode
  35751. */
  35752. get: function () {
  35753. return Material._TriangleFanDrawMode;
  35754. },
  35755. enumerable: true,
  35756. configurable: true
  35757. });
  35758. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35759. /**
  35760. * Returns the clock-wise side orientation
  35761. */
  35762. get: function () {
  35763. return Material._ClockWiseSideOrientation;
  35764. },
  35765. enumerable: true,
  35766. configurable: true
  35767. });
  35768. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35769. /**
  35770. * Returns the counter clock-wise side orientation
  35771. */
  35772. get: function () {
  35773. return Material._CounterClockWiseSideOrientation;
  35774. },
  35775. enumerable: true,
  35776. configurable: true
  35777. });
  35778. Object.defineProperty(Material.prototype, "alpha", {
  35779. /**
  35780. * Gets the alpha value of the material
  35781. */
  35782. get: function () {
  35783. return this._alpha;
  35784. },
  35785. /**
  35786. * Sets the alpha value of the material
  35787. */
  35788. set: function (value) {
  35789. if (this._alpha === value) {
  35790. return;
  35791. }
  35792. this._alpha = value;
  35793. this.markAsDirty(Material.MiscDirtyFlag);
  35794. },
  35795. enumerable: true,
  35796. configurable: true
  35797. });
  35798. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35799. /**
  35800. * Gets the back-face culling state
  35801. */
  35802. get: function () {
  35803. return this._backFaceCulling;
  35804. },
  35805. /**
  35806. * Sets the back-face culling state
  35807. */
  35808. set: function (value) {
  35809. if (this._backFaceCulling === value) {
  35810. return;
  35811. }
  35812. this._backFaceCulling = value;
  35813. this.markAsDirty(Material.TextureDirtyFlag);
  35814. },
  35815. enumerable: true,
  35816. configurable: true
  35817. });
  35818. Object.defineProperty(Material.prototype, "hasRenderTargetTextures", {
  35819. /**
  35820. * Gets a boolean indicating that current material needs to register RTT
  35821. */
  35822. get: function () {
  35823. return false;
  35824. },
  35825. enumerable: true,
  35826. configurable: true
  35827. });
  35828. Object.defineProperty(Material.prototype, "onDispose", {
  35829. /**
  35830. * Called during a dispose event
  35831. */
  35832. set: function (callback) {
  35833. if (this._onDisposeObserver) {
  35834. this.onDisposeObservable.remove(this._onDisposeObserver);
  35835. }
  35836. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35837. },
  35838. enumerable: true,
  35839. configurable: true
  35840. });
  35841. Object.defineProperty(Material.prototype, "onBindObservable", {
  35842. /**
  35843. * An event triggered when the material is bound
  35844. */
  35845. get: function () {
  35846. if (!this._onBindObservable) {
  35847. this._onBindObservable = new BABYLON.Observable();
  35848. }
  35849. return this._onBindObservable;
  35850. },
  35851. enumerable: true,
  35852. configurable: true
  35853. });
  35854. Object.defineProperty(Material.prototype, "onBind", {
  35855. /**
  35856. * Called during a bind event
  35857. */
  35858. set: function (callback) {
  35859. if (this._onBindObserver) {
  35860. this.onBindObservable.remove(this._onBindObserver);
  35861. }
  35862. this._onBindObserver = this.onBindObservable.add(callback);
  35863. },
  35864. enumerable: true,
  35865. configurable: true
  35866. });
  35867. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  35868. /**
  35869. * An event triggered when the material is unbound
  35870. */
  35871. get: function () {
  35872. if (!this._onUnBindObservable) {
  35873. this._onUnBindObservable = new BABYLON.Observable();
  35874. }
  35875. return this._onUnBindObservable;
  35876. },
  35877. enumerable: true,
  35878. configurable: true
  35879. });
  35880. Object.defineProperty(Material.prototype, "alphaMode", {
  35881. /**
  35882. * Gets the value of the alpha mode
  35883. */
  35884. get: function () {
  35885. return this._alphaMode;
  35886. },
  35887. /**
  35888. * Sets the value of the alpha mode.
  35889. *
  35890. * | Value | Type | Description |
  35891. * | --- | --- | --- |
  35892. * | 0 | ALPHA_DISABLE | |
  35893. * | 1 | ALPHA_ADD | |
  35894. * | 2 | ALPHA_COMBINE | |
  35895. * | 3 | ALPHA_SUBTRACT | |
  35896. * | 4 | ALPHA_MULTIPLY | |
  35897. * | 5 | ALPHA_MAXIMIZED | |
  35898. * | 6 | ALPHA_ONEONE | |
  35899. * | 7 | ALPHA_PREMULTIPLIED | |
  35900. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35901. * | 9 | ALPHA_INTERPOLATE | |
  35902. * | 10 | ALPHA_SCREENMODE | |
  35903. *
  35904. */
  35905. set: function (value) {
  35906. if (this._alphaMode === value) {
  35907. return;
  35908. }
  35909. this._alphaMode = value;
  35910. this.markAsDirty(Material.TextureDirtyFlag);
  35911. },
  35912. enumerable: true,
  35913. configurable: true
  35914. });
  35915. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35916. /**
  35917. * Gets the depth pre-pass value
  35918. */
  35919. get: function () {
  35920. return this._needDepthPrePass;
  35921. },
  35922. /**
  35923. * Sets the need depth pre-pass value
  35924. */
  35925. set: function (value) {
  35926. if (this._needDepthPrePass === value) {
  35927. return;
  35928. }
  35929. this._needDepthPrePass = value;
  35930. if (this._needDepthPrePass) {
  35931. this.checkReadyOnEveryCall = true;
  35932. }
  35933. },
  35934. enumerable: true,
  35935. configurable: true
  35936. });
  35937. Object.defineProperty(Material.prototype, "fogEnabled", {
  35938. /**
  35939. * Gets the value of the fog enabled state
  35940. */
  35941. get: function () {
  35942. return this._fogEnabled;
  35943. },
  35944. /**
  35945. * Sets the state for enabling fog
  35946. */
  35947. set: function (value) {
  35948. if (this._fogEnabled === value) {
  35949. return;
  35950. }
  35951. this._fogEnabled = value;
  35952. this.markAsDirty(Material.MiscDirtyFlag);
  35953. },
  35954. enumerable: true,
  35955. configurable: true
  35956. });
  35957. Object.defineProperty(Material.prototype, "wireframe", {
  35958. /**
  35959. * Gets a value specifying if wireframe mode is enabled
  35960. */
  35961. get: function () {
  35962. switch (this._fillMode) {
  35963. case Material.WireFrameFillMode:
  35964. case Material.LineListDrawMode:
  35965. case Material.LineLoopDrawMode:
  35966. case Material.LineStripDrawMode:
  35967. return true;
  35968. }
  35969. return this._scene.forceWireframe;
  35970. },
  35971. /**
  35972. * Sets the state of wireframe mode
  35973. */
  35974. set: function (value) {
  35975. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35976. },
  35977. enumerable: true,
  35978. configurable: true
  35979. });
  35980. Object.defineProperty(Material.prototype, "pointsCloud", {
  35981. /**
  35982. * Gets the value specifying if point clouds are enabled
  35983. */
  35984. get: function () {
  35985. switch (this._fillMode) {
  35986. case Material.PointFillMode:
  35987. case Material.PointListDrawMode:
  35988. return true;
  35989. }
  35990. return this._scene.forcePointsCloud;
  35991. },
  35992. /**
  35993. * Sets the state of point cloud mode
  35994. */
  35995. set: function (value) {
  35996. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35997. },
  35998. enumerable: true,
  35999. configurable: true
  36000. });
  36001. Object.defineProperty(Material.prototype, "fillMode", {
  36002. /**
  36003. * Gets the material fill mode
  36004. */
  36005. get: function () {
  36006. return this._fillMode;
  36007. },
  36008. /**
  36009. * Sets the material fill mode
  36010. */
  36011. set: function (value) {
  36012. if (this._fillMode === value) {
  36013. return;
  36014. }
  36015. this._fillMode = value;
  36016. this.markAsDirty(Material.MiscDirtyFlag);
  36017. },
  36018. enumerable: true,
  36019. configurable: true
  36020. });
  36021. /**
  36022. * Returns a string representation of the current material
  36023. * @param fullDetails defines a boolean indicating which levels of logging is desired
  36024. * @returns a string with material information
  36025. */
  36026. Material.prototype.toString = function (fullDetails) {
  36027. var ret = "Name: " + this.name;
  36028. if (fullDetails) {
  36029. }
  36030. return ret;
  36031. };
  36032. /**
  36033. * Gets the class name of the material
  36034. * @returns a string with the class name of the material
  36035. */
  36036. Material.prototype.getClassName = function () {
  36037. return "Material";
  36038. };
  36039. Object.defineProperty(Material.prototype, "isFrozen", {
  36040. /**
  36041. * Specifies if updates for the material been locked
  36042. */
  36043. get: function () {
  36044. return this.checkReadyOnlyOnce;
  36045. },
  36046. enumerable: true,
  36047. configurable: true
  36048. });
  36049. /**
  36050. * Locks updates for the material
  36051. */
  36052. Material.prototype.freeze = function () {
  36053. this.checkReadyOnlyOnce = true;
  36054. };
  36055. /**
  36056. * Unlocks updates for the material
  36057. */
  36058. Material.prototype.unfreeze = function () {
  36059. this.checkReadyOnlyOnce = false;
  36060. };
  36061. /**
  36062. * Specifies if the material is ready to be used
  36063. * @param mesh defines the mesh to check
  36064. * @param useInstances specifies if instances should be used
  36065. * @returns a boolean indicating if the material is ready to be used
  36066. */
  36067. Material.prototype.isReady = function (mesh, useInstances) {
  36068. return true;
  36069. };
  36070. /**
  36071. * Specifies that the submesh is ready to be used
  36072. * @param mesh defines the mesh to check
  36073. * @param subMesh defines which submesh to check
  36074. * @param useInstances specifies that instances should be used
  36075. * @returns a boolean indicating that the submesh is ready or not
  36076. */
  36077. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36078. return false;
  36079. };
  36080. /**
  36081. * Returns the material effect
  36082. * @returns the effect associated with the material
  36083. */
  36084. Material.prototype.getEffect = function () {
  36085. return this._effect;
  36086. };
  36087. /**
  36088. * Returns the current scene
  36089. * @returns a Scene
  36090. */
  36091. Material.prototype.getScene = function () {
  36092. return this._scene;
  36093. };
  36094. /**
  36095. * Specifies if the material will require alpha blending
  36096. * @returns a boolean specifying if alpha blending is needed
  36097. */
  36098. Material.prototype.needAlphaBlending = function () {
  36099. return (this.alpha < 1.0);
  36100. };
  36101. /**
  36102. * Specifies if the mesh will require alpha blending
  36103. * @param mesh defines the mesh to check
  36104. * @returns a boolean specifying if alpha blending is needed for the mesh
  36105. */
  36106. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  36107. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  36108. };
  36109. /**
  36110. * Specifies if this material should be rendered in alpha test mode
  36111. * @returns a boolean specifying if an alpha test is needed.
  36112. */
  36113. Material.prototype.needAlphaTesting = function () {
  36114. return false;
  36115. };
  36116. /**
  36117. * Gets the texture used for the alpha test
  36118. * @returns the texture to use for alpha testing
  36119. */
  36120. Material.prototype.getAlphaTestTexture = function () {
  36121. return null;
  36122. };
  36123. /**
  36124. * Marks the material to indicate that it needs to be re-calculated
  36125. */
  36126. Material.prototype.markDirty = function () {
  36127. this._wasPreviouslyReady = false;
  36128. };
  36129. /** @hidden */
  36130. Material.prototype._preBind = function (effect, overrideOrientation) {
  36131. if (overrideOrientation === void 0) { overrideOrientation = null; }
  36132. var engine = this._scene.getEngine();
  36133. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  36134. var reverse = orientation === Material.ClockWiseSideOrientation;
  36135. engine.enableEffect(effect ? effect : this._effect);
  36136. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  36137. return reverse;
  36138. };
  36139. /**
  36140. * Binds the material to the mesh
  36141. * @param world defines the world transformation matrix
  36142. * @param mesh defines the mesh to bind the material to
  36143. */
  36144. Material.prototype.bind = function (world, mesh) {
  36145. };
  36146. /**
  36147. * Binds the submesh to the material
  36148. * @param world defines the world transformation matrix
  36149. * @param mesh defines the mesh containing the submesh
  36150. * @param subMesh defines the submesh to bind the material to
  36151. */
  36152. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  36153. };
  36154. /**
  36155. * Binds the world matrix to the material
  36156. * @param world defines the world transformation matrix
  36157. */
  36158. Material.prototype.bindOnlyWorldMatrix = function (world) {
  36159. };
  36160. /**
  36161. * Binds the scene's uniform buffer to the effect.
  36162. * @param effect defines the effect to bind to the scene uniform buffer
  36163. * @param sceneUbo defines the uniform buffer storing scene data
  36164. */
  36165. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  36166. sceneUbo.bindToEffect(effect, "Scene");
  36167. };
  36168. /**
  36169. * Binds the view matrix to the effect
  36170. * @param effect defines the effect to bind the view matrix to
  36171. */
  36172. Material.prototype.bindView = function (effect) {
  36173. if (!this._useUBO) {
  36174. effect.setMatrix("view", this.getScene().getViewMatrix());
  36175. }
  36176. else {
  36177. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  36178. }
  36179. };
  36180. /**
  36181. * Binds the view projection matrix to the effect
  36182. * @param effect defines the effect to bind the view projection matrix to
  36183. */
  36184. Material.prototype.bindViewProjection = function (effect) {
  36185. if (!this._useUBO) {
  36186. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  36187. }
  36188. else {
  36189. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  36190. }
  36191. };
  36192. /**
  36193. * Specifies if material alpha testing should be turned on for the mesh
  36194. * @param mesh defines the mesh to check
  36195. */
  36196. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  36197. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  36198. };
  36199. /**
  36200. * Processes to execute after binding the material to a mesh
  36201. * @param mesh defines the rendered mesh
  36202. */
  36203. Material.prototype._afterBind = function (mesh) {
  36204. this._scene._cachedMaterial = this;
  36205. if (mesh) {
  36206. this._scene._cachedVisibility = mesh.visibility;
  36207. }
  36208. else {
  36209. this._scene._cachedVisibility = 1;
  36210. }
  36211. if (this._onBindObservable && mesh) {
  36212. this._onBindObservable.notifyObservers(mesh);
  36213. }
  36214. if (this.disableDepthWrite) {
  36215. var engine = this._scene.getEngine();
  36216. this._cachedDepthWriteState = engine.getDepthWrite();
  36217. engine.setDepthWrite(false);
  36218. }
  36219. };
  36220. /**
  36221. * Unbinds the material from the mesh
  36222. */
  36223. Material.prototype.unbind = function () {
  36224. if (this._onUnBindObservable) {
  36225. this._onUnBindObservable.notifyObservers(this);
  36226. }
  36227. if (this.disableDepthWrite) {
  36228. var engine = this._scene.getEngine();
  36229. engine.setDepthWrite(this._cachedDepthWriteState);
  36230. }
  36231. };
  36232. /**
  36233. * Gets the active textures from the material
  36234. * @returns an array of textures
  36235. */
  36236. Material.prototype.getActiveTextures = function () {
  36237. return [];
  36238. };
  36239. /**
  36240. * Specifies if the material uses a texture
  36241. * @param texture defines the texture to check against the material
  36242. * @returns a boolean specifying if the material uses the texture
  36243. */
  36244. Material.prototype.hasTexture = function (texture) {
  36245. return false;
  36246. };
  36247. /**
  36248. * Makes a duplicate of the material, and gives it a new name
  36249. * @param name defines the new name for the duplicated material
  36250. * @returns the cloned material
  36251. */
  36252. Material.prototype.clone = function (name) {
  36253. return null;
  36254. };
  36255. /**
  36256. * Gets the meshes bound to the material
  36257. * @returns an array of meshes bound to the material
  36258. */
  36259. Material.prototype.getBindedMeshes = function () {
  36260. var result = new Array();
  36261. for (var index = 0; index < this._scene.meshes.length; index++) {
  36262. var mesh = this._scene.meshes[index];
  36263. if (mesh.material === this) {
  36264. result.push(mesh);
  36265. }
  36266. }
  36267. return result;
  36268. };
  36269. /**
  36270. * Force shader compilation
  36271. * @param mesh defines the mesh associated with this material
  36272. * @param onCompiled defines a function to execute once the material is compiled
  36273. * @param options defines the options to configure the compilation
  36274. */
  36275. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  36276. var _this = this;
  36277. var localOptions = __assign({ clipPlane: false }, options);
  36278. var subMesh = new BABYLON.BaseSubMesh();
  36279. var scene = this.getScene();
  36280. var checkReady = function () {
  36281. if (!_this._scene || !_this._scene.getEngine()) {
  36282. return;
  36283. }
  36284. if (subMesh._materialDefines) {
  36285. subMesh._materialDefines._renderId = -1;
  36286. }
  36287. var clipPlaneState = scene.clipPlane;
  36288. if (localOptions.clipPlane) {
  36289. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  36290. }
  36291. if (_this.storeEffectOnSubMeshes) {
  36292. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  36293. if (onCompiled) {
  36294. onCompiled(_this);
  36295. }
  36296. }
  36297. else {
  36298. setTimeout(checkReady, 16);
  36299. }
  36300. }
  36301. else {
  36302. if (_this.isReady(mesh)) {
  36303. if (onCompiled) {
  36304. onCompiled(_this);
  36305. }
  36306. }
  36307. else {
  36308. setTimeout(checkReady, 16);
  36309. }
  36310. }
  36311. if (localOptions.clipPlane) {
  36312. scene.clipPlane = clipPlaneState;
  36313. }
  36314. };
  36315. checkReady();
  36316. };
  36317. /**
  36318. * Force shader compilation
  36319. * @param mesh defines the mesh that will use this material
  36320. * @param options defines additional options for compiling the shaders
  36321. * @returns a promise that resolves when the compilation completes
  36322. */
  36323. Material.prototype.forceCompilationAsync = function (mesh, options) {
  36324. var _this = this;
  36325. return new Promise(function (resolve) {
  36326. _this.forceCompilation(mesh, function () {
  36327. resolve();
  36328. }, options);
  36329. });
  36330. };
  36331. /**
  36332. * Marks a define in the material to indicate that it needs to be re-computed
  36333. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  36334. */
  36335. Material.prototype.markAsDirty = function (flag) {
  36336. if (flag & Material.TextureDirtyFlag) {
  36337. this._markAllSubMeshesAsTexturesDirty();
  36338. }
  36339. if (flag & Material.LightDirtyFlag) {
  36340. this._markAllSubMeshesAsLightsDirty();
  36341. }
  36342. if (flag & Material.FresnelDirtyFlag) {
  36343. this._markAllSubMeshesAsFresnelDirty();
  36344. }
  36345. if (flag & Material.AttributesDirtyFlag) {
  36346. this._markAllSubMeshesAsAttributesDirty();
  36347. }
  36348. if (flag & Material.MiscDirtyFlag) {
  36349. this._markAllSubMeshesAsMiscDirty();
  36350. }
  36351. this.getScene().resetCachedMaterial();
  36352. };
  36353. /**
  36354. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  36355. * @param func defines a function which checks material defines against the submeshes
  36356. */
  36357. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  36358. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  36359. var mesh = _a[_i];
  36360. if (!mesh.subMeshes) {
  36361. continue;
  36362. }
  36363. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  36364. var subMesh = _c[_b];
  36365. if (subMesh.getMaterial() !== this) {
  36366. continue;
  36367. }
  36368. if (!subMesh._materialDefines) {
  36369. continue;
  36370. }
  36371. func(subMesh._materialDefines);
  36372. }
  36373. }
  36374. };
  36375. /**
  36376. * Indicates that image processing needs to be re-calculated for all submeshes
  36377. */
  36378. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  36379. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  36380. };
  36381. /**
  36382. * Indicates that textures need to be re-calculated for all submeshes
  36383. */
  36384. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  36385. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  36386. };
  36387. /**
  36388. * Indicates that fresnel needs to be re-calculated for all submeshes
  36389. */
  36390. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  36391. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  36392. };
  36393. /**
  36394. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  36395. */
  36396. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  36397. this._markAllSubMeshesAsDirty(function (defines) {
  36398. defines.markAsFresnelDirty();
  36399. defines.markAsMiscDirty();
  36400. });
  36401. };
  36402. /**
  36403. * Indicates that lights need to be re-calculated for all submeshes
  36404. */
  36405. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  36406. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  36407. };
  36408. /**
  36409. * Indicates that attributes need to be re-calculated for all submeshes
  36410. */
  36411. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  36412. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  36413. };
  36414. /**
  36415. * Indicates that misc needs to be re-calculated for all submeshes
  36416. */
  36417. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  36418. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  36419. };
  36420. /**
  36421. * Indicates that textures and misc need to be re-calculated for all submeshes
  36422. */
  36423. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  36424. this._markAllSubMeshesAsDirty(function (defines) {
  36425. defines.markAsTexturesDirty();
  36426. defines.markAsMiscDirty();
  36427. });
  36428. };
  36429. /**
  36430. * Disposes the material
  36431. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  36432. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  36433. */
  36434. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36435. // Animations
  36436. this.getScene().stopAnimation(this);
  36437. this.getScene().freeProcessedMaterials();
  36438. // Remove from scene
  36439. var index = this._scene.materials.indexOf(this);
  36440. if (index >= 0) {
  36441. this._scene.materials.splice(index, 1);
  36442. }
  36443. this._scene.onMaterialRemovedObservable.notifyObservers(this);
  36444. // Remove from meshes
  36445. for (index = 0; index < this._scene.meshes.length; index++) {
  36446. var mesh = this._scene.meshes[index];
  36447. if (mesh.material === this) {
  36448. mesh.material = null;
  36449. if (mesh.geometry) {
  36450. var geometry = (mesh.geometry);
  36451. if (this.storeEffectOnSubMeshes) {
  36452. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  36453. var subMesh = _a[_i];
  36454. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  36455. if (forceDisposeEffect && subMesh._materialEffect) {
  36456. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  36457. }
  36458. }
  36459. }
  36460. else {
  36461. geometry._releaseVertexArrayObject(this._effect);
  36462. }
  36463. }
  36464. }
  36465. }
  36466. this._uniformBuffer.dispose();
  36467. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  36468. if (forceDisposeEffect && this._effect) {
  36469. if (!this.storeEffectOnSubMeshes) {
  36470. this._scene.getEngine()._releaseEffect(this._effect);
  36471. }
  36472. this._effect = null;
  36473. }
  36474. // Callback
  36475. this.onDisposeObservable.notifyObservers(this);
  36476. this.onDisposeObservable.clear();
  36477. if (this._onBindObservable) {
  36478. this._onBindObservable.clear();
  36479. }
  36480. if (this._onUnBindObservable) {
  36481. this._onUnBindObservable.clear();
  36482. }
  36483. };
  36484. /**
  36485. * Serializes this material
  36486. * @returns the serialized material object
  36487. */
  36488. Material.prototype.serialize = function () {
  36489. return BABYLON.SerializationHelper.Serialize(this);
  36490. };
  36491. /**
  36492. * Creates a MultiMaterial from parsed MultiMaterial data.
  36493. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  36494. * @param scene defines the hosting scene
  36495. * @returns a new MultiMaterial
  36496. */
  36497. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  36498. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  36499. multiMaterial.id = parsedMultiMaterial.id;
  36500. if (BABYLON.Tags) {
  36501. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  36502. }
  36503. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  36504. var subMatId = parsedMultiMaterial.materials[matIndex];
  36505. if (subMatId) {
  36506. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  36507. }
  36508. else {
  36509. multiMaterial.subMaterials.push(null);
  36510. }
  36511. }
  36512. return multiMaterial;
  36513. };
  36514. /**
  36515. * Creates a material from parsed material data
  36516. * @param parsedMaterial defines parsed material data
  36517. * @param scene defines the hosting scene
  36518. * @param rootUrl defines the root URL to use to load textures
  36519. * @returns a new material
  36520. */
  36521. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  36522. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  36523. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  36524. }
  36525. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  36526. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  36527. if (!BABYLON.LegacyPBRMaterial) {
  36528. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  36529. return;
  36530. }
  36531. }
  36532. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  36533. return materialType.Parse(parsedMaterial, scene, rootUrl);
  36534. };
  36535. // Triangle views
  36536. Material._TriangleFillMode = 0;
  36537. Material._WireFrameFillMode = 1;
  36538. Material._PointFillMode = 2;
  36539. // Draw modes
  36540. Material._PointListDrawMode = 3;
  36541. Material._LineListDrawMode = 4;
  36542. Material._LineLoopDrawMode = 5;
  36543. Material._LineStripDrawMode = 6;
  36544. Material._TriangleStripDrawMode = 7;
  36545. Material._TriangleFanDrawMode = 8;
  36546. /**
  36547. * Stores the clock-wise side orientation
  36548. */
  36549. Material._ClockWiseSideOrientation = 0;
  36550. /**
  36551. * Stores the counter clock-wise side orientation
  36552. */
  36553. Material._CounterClockWiseSideOrientation = 1;
  36554. /**
  36555. * The dirty texture flag value
  36556. */
  36557. Material.TextureDirtyFlag = 1;
  36558. /**
  36559. * The dirty light flag value
  36560. */
  36561. Material.LightDirtyFlag = 2;
  36562. /**
  36563. * The dirty fresnel flag value
  36564. */
  36565. Material.FresnelDirtyFlag = 4;
  36566. /**
  36567. * The dirty attribute flag value
  36568. */
  36569. Material.AttributesDirtyFlag = 8;
  36570. /**
  36571. * The dirty misc flag value
  36572. */
  36573. Material.MiscDirtyFlag = 16;
  36574. /**
  36575. * The all dirty flag value
  36576. */
  36577. Material.AllDirtyFlag = 31;
  36578. __decorate([
  36579. BABYLON.serialize()
  36580. ], Material.prototype, "id", void 0);
  36581. __decorate([
  36582. BABYLON.serialize()
  36583. ], Material.prototype, "uniqueId", void 0);
  36584. __decorate([
  36585. BABYLON.serialize()
  36586. ], Material.prototype, "name", void 0);
  36587. __decorate([
  36588. BABYLON.serialize()
  36589. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  36590. __decorate([
  36591. BABYLON.serialize()
  36592. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  36593. __decorate([
  36594. BABYLON.serialize()
  36595. ], Material.prototype, "state", void 0);
  36596. __decorate([
  36597. BABYLON.serialize("alpha")
  36598. ], Material.prototype, "_alpha", void 0);
  36599. __decorate([
  36600. BABYLON.serialize("backFaceCulling")
  36601. ], Material.prototype, "_backFaceCulling", void 0);
  36602. __decorate([
  36603. BABYLON.serialize()
  36604. ], Material.prototype, "sideOrientation", void 0);
  36605. __decorate([
  36606. BABYLON.serialize("alphaMode")
  36607. ], Material.prototype, "_alphaMode", void 0);
  36608. __decorate([
  36609. BABYLON.serialize()
  36610. ], Material.prototype, "_needDepthPrePass", void 0);
  36611. __decorate([
  36612. BABYLON.serialize()
  36613. ], Material.prototype, "disableDepthWrite", void 0);
  36614. __decorate([
  36615. BABYLON.serialize()
  36616. ], Material.prototype, "forceDepthWrite", void 0);
  36617. __decorate([
  36618. BABYLON.serialize()
  36619. ], Material.prototype, "separateCullingPass", void 0);
  36620. __decorate([
  36621. BABYLON.serialize("fogEnabled")
  36622. ], Material.prototype, "_fogEnabled", void 0);
  36623. __decorate([
  36624. BABYLON.serialize()
  36625. ], Material.prototype, "pointSize", void 0);
  36626. __decorate([
  36627. BABYLON.serialize()
  36628. ], Material.prototype, "zOffset", void 0);
  36629. __decorate([
  36630. BABYLON.serialize()
  36631. ], Material.prototype, "wireframe", null);
  36632. __decorate([
  36633. BABYLON.serialize()
  36634. ], Material.prototype, "pointsCloud", null);
  36635. __decorate([
  36636. BABYLON.serialize()
  36637. ], Material.prototype, "fillMode", null);
  36638. return Material;
  36639. }());
  36640. BABYLON.Material = Material;
  36641. })(BABYLON || (BABYLON = {}));
  36642. //# sourceMappingURL=babylon.material.js.map
  36643. var BABYLON;
  36644. (function (BABYLON) {
  36645. /**
  36646. * Uniform buffer objects.
  36647. *
  36648. * Handles blocks of uniform on the GPU.
  36649. *
  36650. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36651. *
  36652. * For more information, please refer to :
  36653. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36654. */
  36655. var UniformBuffer = /** @class */ (function () {
  36656. /**
  36657. * Instantiates a new Uniform buffer objects.
  36658. *
  36659. * Handles blocks of uniform on the GPU.
  36660. *
  36661. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36662. *
  36663. * For more information, please refer to :
  36664. * @see https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36665. * @param engine Define the engine the buffer is associated with
  36666. * @param data Define the data contained in the buffer
  36667. * @param dynamic Define if the buffer is updatable
  36668. */
  36669. function UniformBuffer(engine, data, dynamic) {
  36670. this._engine = engine;
  36671. this._noUBO = !engine.supportsUniformBuffers;
  36672. this._dynamic = dynamic;
  36673. this._data = data || [];
  36674. this._uniformLocations = {};
  36675. this._uniformSizes = {};
  36676. this._uniformLocationPointer = 0;
  36677. this._needSync = false;
  36678. if (this._noUBO) {
  36679. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  36680. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  36681. this.updateFloat = this._updateFloatForEffect;
  36682. this.updateFloat2 = this._updateFloat2ForEffect;
  36683. this.updateFloat3 = this._updateFloat3ForEffect;
  36684. this.updateFloat4 = this._updateFloat4ForEffect;
  36685. this.updateMatrix = this._updateMatrixForEffect;
  36686. this.updateVector3 = this._updateVector3ForEffect;
  36687. this.updateVector4 = this._updateVector4ForEffect;
  36688. this.updateColor3 = this._updateColor3ForEffect;
  36689. this.updateColor4 = this._updateColor4ForEffect;
  36690. }
  36691. else {
  36692. this._engine._uniformBuffers.push(this);
  36693. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36694. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36695. this.updateFloat = this._updateFloatForUniform;
  36696. this.updateFloat2 = this._updateFloat2ForUniform;
  36697. this.updateFloat3 = this._updateFloat3ForUniform;
  36698. this.updateFloat4 = this._updateFloat4ForUniform;
  36699. this.updateMatrix = this._updateMatrixForUniform;
  36700. this.updateVector3 = this._updateVector3ForUniform;
  36701. this.updateVector4 = this._updateVector4ForUniform;
  36702. this.updateColor3 = this._updateColor3ForUniform;
  36703. this.updateColor4 = this._updateColor4ForUniform;
  36704. }
  36705. }
  36706. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36707. /**
  36708. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36709. * or just falling back on setUniformXXX calls.
  36710. */
  36711. get: function () {
  36712. return !this._noUBO;
  36713. },
  36714. enumerable: true,
  36715. configurable: true
  36716. });
  36717. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36718. /**
  36719. * Indicates if the WebGL underlying uniform buffer is in sync
  36720. * with the javascript cache data.
  36721. */
  36722. get: function () {
  36723. return !this._needSync;
  36724. },
  36725. enumerable: true,
  36726. configurable: true
  36727. });
  36728. /**
  36729. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36730. * Also, a dynamic UniformBuffer will disable cache verification and always
  36731. * update the underlying WebGL uniform buffer to the GPU.
  36732. * @returns if Dynamic, otherwise false
  36733. */
  36734. UniformBuffer.prototype.isDynamic = function () {
  36735. return this._dynamic !== undefined;
  36736. };
  36737. /**
  36738. * The data cache on JS side.
  36739. * @returns the underlying data as a float array
  36740. */
  36741. UniformBuffer.prototype.getData = function () {
  36742. return this._bufferData;
  36743. };
  36744. /**
  36745. * The underlying WebGL Uniform buffer.
  36746. * @returns the webgl buffer
  36747. */
  36748. UniformBuffer.prototype.getBuffer = function () {
  36749. return this._buffer;
  36750. };
  36751. /**
  36752. * std140 layout specifies how to align data within an UBO structure.
  36753. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36754. * for specs.
  36755. */
  36756. UniformBuffer.prototype._fillAlignment = function (size) {
  36757. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36758. // and 4x4 matrices
  36759. // TODO : change if other types are used
  36760. var alignment;
  36761. if (size <= 2) {
  36762. alignment = size;
  36763. }
  36764. else {
  36765. alignment = 4;
  36766. }
  36767. if ((this._uniformLocationPointer % alignment) !== 0) {
  36768. var oldPointer = this._uniformLocationPointer;
  36769. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36770. var diff = this._uniformLocationPointer - oldPointer;
  36771. for (var i = 0; i < diff; i++) {
  36772. this._data.push(0);
  36773. }
  36774. }
  36775. };
  36776. /**
  36777. * Adds an uniform in the buffer.
  36778. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36779. * for the layout to be correct !
  36780. * @param name Name of the uniform, as used in the uniform block in the shader.
  36781. * @param size Data size, or data directly.
  36782. */
  36783. UniformBuffer.prototype.addUniform = function (name, size) {
  36784. if (this._noUBO) {
  36785. return;
  36786. }
  36787. if (this._uniformLocations[name] !== undefined) {
  36788. // Already existing uniform
  36789. return;
  36790. }
  36791. // This function must be called in the order of the shader layout !
  36792. // size can be the size of the uniform, or data directly
  36793. var data;
  36794. if (size instanceof Array) {
  36795. data = size;
  36796. size = data.length;
  36797. }
  36798. else {
  36799. size = size;
  36800. data = [];
  36801. // Fill with zeros
  36802. for (var i = 0; i < size; i++) {
  36803. data.push(0);
  36804. }
  36805. }
  36806. this._fillAlignment(size);
  36807. this._uniformSizes[name] = size;
  36808. this._uniformLocations[name] = this._uniformLocationPointer;
  36809. this._uniformLocationPointer += size;
  36810. for (var i = 0; i < size; i++) {
  36811. this._data.push(data[i]);
  36812. }
  36813. this._needSync = true;
  36814. };
  36815. /**
  36816. * Adds a Matrix 4x4 to the uniform buffer.
  36817. * @param name Name of the uniform, as used in the uniform block in the shader.
  36818. * @param mat A 4x4 matrix.
  36819. */
  36820. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36821. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36822. };
  36823. /**
  36824. * Adds a vec2 to the uniform buffer.
  36825. * @param name Name of the uniform, as used in the uniform block in the shader.
  36826. * @param x Define the x component value of the vec2
  36827. * @param y Define the y component value of the vec2
  36828. */
  36829. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36830. var temp = [x, y];
  36831. this.addUniform(name, temp);
  36832. };
  36833. /**
  36834. * Adds a vec3 to the uniform buffer.
  36835. * @param name Name of the uniform, as used in the uniform block in the shader.
  36836. * @param x Define the x component value of the vec3
  36837. * @param y Define the y component value of the vec3
  36838. * @param z Define the z component value of the vec3
  36839. */
  36840. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36841. var temp = [x, y, z];
  36842. this.addUniform(name, temp);
  36843. };
  36844. /**
  36845. * Adds a vec3 to the uniform buffer.
  36846. * @param name Name of the uniform, as used in the uniform block in the shader.
  36847. * @param color Define the vec3 from a Color
  36848. */
  36849. UniformBuffer.prototype.addColor3 = function (name, color) {
  36850. var temp = new Array();
  36851. color.toArray(temp);
  36852. this.addUniform(name, temp);
  36853. };
  36854. /**
  36855. * Adds a vec4 to the uniform buffer.
  36856. * @param name Name of the uniform, as used in the uniform block in the shader.
  36857. * @param color Define the rgb components from a Color
  36858. * @param alpha Define the a component of the vec4
  36859. */
  36860. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36861. var temp = new Array();
  36862. color.toArray(temp);
  36863. temp.push(alpha);
  36864. this.addUniform(name, temp);
  36865. };
  36866. /**
  36867. * Adds a vec3 to the uniform buffer.
  36868. * @param name Name of the uniform, as used in the uniform block in the shader.
  36869. * @param vector Define the vec3 components from a Vector
  36870. */
  36871. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36872. var temp = new Array();
  36873. vector.toArray(temp);
  36874. this.addUniform(name, temp);
  36875. };
  36876. /**
  36877. * Adds a Matrix 3x3 to the uniform buffer.
  36878. * @param name Name of the uniform, as used in the uniform block in the shader.
  36879. */
  36880. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36881. this.addUniform(name, 12);
  36882. };
  36883. /**
  36884. * Adds a Matrix 2x2 to the uniform buffer.
  36885. * @param name Name of the uniform, as used in the uniform block in the shader.
  36886. */
  36887. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36888. this.addUniform(name, 8);
  36889. };
  36890. /**
  36891. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36892. */
  36893. UniformBuffer.prototype.create = function () {
  36894. if (this._noUBO) {
  36895. return;
  36896. }
  36897. if (this._buffer) {
  36898. return; // nothing to do
  36899. }
  36900. // See spec, alignment must be filled as a vec4
  36901. this._fillAlignment(4);
  36902. this._bufferData = new Float32Array(this._data);
  36903. this._rebuild();
  36904. this._needSync = true;
  36905. };
  36906. /** @hidden */
  36907. UniformBuffer.prototype._rebuild = function () {
  36908. if (this._noUBO) {
  36909. return;
  36910. }
  36911. if (this._dynamic) {
  36912. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36913. }
  36914. else {
  36915. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36916. }
  36917. };
  36918. /**
  36919. * Updates the WebGL Uniform Buffer on the GPU.
  36920. * If the `dynamic` flag is set to true, no cache comparison is done.
  36921. * Otherwise, the buffer will be updated only if the cache differs.
  36922. */
  36923. UniformBuffer.prototype.update = function () {
  36924. if (!this._buffer) {
  36925. this.create();
  36926. return;
  36927. }
  36928. if (!this._dynamic && !this._needSync) {
  36929. return;
  36930. }
  36931. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36932. this._needSync = false;
  36933. };
  36934. /**
  36935. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36936. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  36937. * @param data Define the flattened data
  36938. * @param size Define the size of the data.
  36939. */
  36940. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36941. var location = this._uniformLocations[uniformName];
  36942. if (location === undefined) {
  36943. if (this._buffer) {
  36944. // Cannot add an uniform if the buffer is already created
  36945. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36946. return;
  36947. }
  36948. this.addUniform(uniformName, size);
  36949. location = this._uniformLocations[uniformName];
  36950. }
  36951. if (!this._buffer) {
  36952. this.create();
  36953. }
  36954. if (!this._dynamic) {
  36955. // Cache for static uniform buffers
  36956. var changed = false;
  36957. for (var i = 0; i < size; i++) {
  36958. if (this._bufferData[location + i] !== data[i]) {
  36959. changed = true;
  36960. this._bufferData[location + i] = data[i];
  36961. }
  36962. }
  36963. this._needSync = this._needSync || changed;
  36964. }
  36965. else {
  36966. // No cache for dynamic
  36967. for (var i = 0; i < size; i++) {
  36968. this._bufferData[location + i] = data[i];
  36969. }
  36970. }
  36971. };
  36972. // Update methods
  36973. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36974. // To match std140, matrix must be realigned
  36975. for (var i = 0; i < 3; i++) {
  36976. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36977. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36978. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36979. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36980. }
  36981. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36982. };
  36983. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36984. this._currentEffect.setMatrix3x3(name, matrix);
  36985. };
  36986. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36987. this._currentEffect.setMatrix2x2(name, matrix);
  36988. };
  36989. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36990. // To match std140, matrix must be realigned
  36991. for (var i = 0; i < 2; i++) {
  36992. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36993. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36994. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36995. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36996. }
  36997. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36998. };
  36999. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  37000. this._currentEffect.setFloat(name, x);
  37001. };
  37002. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  37003. UniformBuffer._tempBuffer[0] = x;
  37004. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  37005. };
  37006. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  37007. if (suffix === void 0) { suffix = ""; }
  37008. this._currentEffect.setFloat2(name + suffix, x, y);
  37009. };
  37010. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  37011. if (suffix === void 0) { suffix = ""; }
  37012. UniformBuffer._tempBuffer[0] = x;
  37013. UniformBuffer._tempBuffer[1] = y;
  37014. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  37015. };
  37016. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  37017. if (suffix === void 0) { suffix = ""; }
  37018. this._currentEffect.setFloat3(name + suffix, x, y, z);
  37019. };
  37020. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  37021. if (suffix === void 0) { suffix = ""; }
  37022. UniformBuffer._tempBuffer[0] = x;
  37023. UniformBuffer._tempBuffer[1] = y;
  37024. UniformBuffer._tempBuffer[2] = z;
  37025. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37026. };
  37027. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  37028. if (suffix === void 0) { suffix = ""; }
  37029. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  37030. };
  37031. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  37032. if (suffix === void 0) { suffix = ""; }
  37033. UniformBuffer._tempBuffer[0] = x;
  37034. UniformBuffer._tempBuffer[1] = y;
  37035. UniformBuffer._tempBuffer[2] = z;
  37036. UniformBuffer._tempBuffer[3] = w;
  37037. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37038. };
  37039. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  37040. this._currentEffect.setMatrix(name, mat);
  37041. };
  37042. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  37043. this.updateUniform(name, mat.toArray(), 16);
  37044. };
  37045. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  37046. this._currentEffect.setVector3(name, vector);
  37047. };
  37048. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  37049. vector.toArray(UniformBuffer._tempBuffer);
  37050. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37051. };
  37052. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  37053. this._currentEffect.setVector4(name, vector);
  37054. };
  37055. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  37056. vector.toArray(UniformBuffer._tempBuffer);
  37057. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37058. };
  37059. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  37060. if (suffix === void 0) { suffix = ""; }
  37061. this._currentEffect.setColor3(name + suffix, color);
  37062. };
  37063. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  37064. if (suffix === void 0) { suffix = ""; }
  37065. color.toArray(UniformBuffer._tempBuffer);
  37066. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37067. };
  37068. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  37069. if (suffix === void 0) { suffix = ""; }
  37070. this._currentEffect.setColor4(name + suffix, color, alpha);
  37071. };
  37072. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  37073. if (suffix === void 0) { suffix = ""; }
  37074. color.toArray(UniformBuffer._tempBuffer);
  37075. UniformBuffer._tempBuffer[3] = alpha;
  37076. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37077. };
  37078. /**
  37079. * Sets a sampler uniform on the effect.
  37080. * @param name Define the name of the sampler.
  37081. * @param texture Define the texture to set in the sampler
  37082. */
  37083. UniformBuffer.prototype.setTexture = function (name, texture) {
  37084. this._currentEffect.setTexture(name, texture);
  37085. };
  37086. /**
  37087. * Directly updates the value of the uniform in the cache AND on the GPU.
  37088. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  37089. * @param data Define the flattened data
  37090. */
  37091. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  37092. this.updateUniform(uniformName, data, data.length);
  37093. this.update();
  37094. };
  37095. /**
  37096. * Binds this uniform buffer to an effect.
  37097. * @param effect Define the effect to bind the buffer to
  37098. * @param name Name of the uniform block in the shader.
  37099. */
  37100. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  37101. this._currentEffect = effect;
  37102. if (this._noUBO || !this._buffer) {
  37103. return;
  37104. }
  37105. effect.bindUniformBuffer(this._buffer, name);
  37106. };
  37107. /**
  37108. * Disposes the uniform buffer.
  37109. */
  37110. UniformBuffer.prototype.dispose = function () {
  37111. if (this._noUBO) {
  37112. return;
  37113. }
  37114. var index = this._engine._uniformBuffers.indexOf(this);
  37115. if (index !== -1) {
  37116. this._engine._uniformBuffers.splice(index, 1);
  37117. }
  37118. if (!this._buffer) {
  37119. return;
  37120. }
  37121. if (this._engine._releaseBuffer(this._buffer)) {
  37122. this._buffer = null;
  37123. }
  37124. };
  37125. // Pool for avoiding memory leaks
  37126. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  37127. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  37128. return UniformBuffer;
  37129. }());
  37130. BABYLON.UniformBuffer = UniformBuffer;
  37131. })(BABYLON || (BABYLON = {}));
  37132. //# sourceMappingURL=babylon.uniformBuffer.js.map
  37133. var BABYLON;
  37134. (function (BABYLON) {
  37135. /**
  37136. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  37137. */
  37138. var VertexData = /** @class */ (function () {
  37139. function VertexData() {
  37140. }
  37141. /**
  37142. * Uses the passed data array to set the set the values for the specified kind of data
  37143. * @param data a linear array of floating numbers
  37144. * @param kind the type of data that is being set, eg positions, colors etc
  37145. */
  37146. VertexData.prototype.set = function (data, kind) {
  37147. switch (kind) {
  37148. case BABYLON.VertexBuffer.PositionKind:
  37149. this.positions = data;
  37150. break;
  37151. case BABYLON.VertexBuffer.NormalKind:
  37152. this.normals = data;
  37153. break;
  37154. case BABYLON.VertexBuffer.TangentKind:
  37155. this.tangents = data;
  37156. break;
  37157. case BABYLON.VertexBuffer.UVKind:
  37158. this.uvs = data;
  37159. break;
  37160. case BABYLON.VertexBuffer.UV2Kind:
  37161. this.uvs2 = data;
  37162. break;
  37163. case BABYLON.VertexBuffer.UV3Kind:
  37164. this.uvs3 = data;
  37165. break;
  37166. case BABYLON.VertexBuffer.UV4Kind:
  37167. this.uvs4 = data;
  37168. break;
  37169. case BABYLON.VertexBuffer.UV5Kind:
  37170. this.uvs5 = data;
  37171. break;
  37172. case BABYLON.VertexBuffer.UV6Kind:
  37173. this.uvs6 = data;
  37174. break;
  37175. case BABYLON.VertexBuffer.ColorKind:
  37176. this.colors = data;
  37177. break;
  37178. case BABYLON.VertexBuffer.MatricesIndicesKind:
  37179. this.matricesIndices = data;
  37180. break;
  37181. case BABYLON.VertexBuffer.MatricesWeightsKind:
  37182. this.matricesWeights = data;
  37183. break;
  37184. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  37185. this.matricesIndicesExtra = data;
  37186. break;
  37187. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  37188. this.matricesWeightsExtra = data;
  37189. break;
  37190. }
  37191. };
  37192. /**
  37193. * Associates the vertexData to the passed Mesh.
  37194. * Sets it as updatable or not (default `false`)
  37195. * @param mesh the mesh the vertexData is applied to
  37196. * @param updatable when used and having the value true allows new data to update the vertexData
  37197. * @returns the VertexData
  37198. */
  37199. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  37200. this._applyTo(mesh, updatable);
  37201. return this;
  37202. };
  37203. /**
  37204. * Associates the vertexData to the passed Geometry.
  37205. * Sets it as updatable or not (default `false`)
  37206. * @param geometry the geometry the vertexData is applied to
  37207. * @param updatable when used and having the value true allows new data to update the vertexData
  37208. * @returns VertexData
  37209. */
  37210. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  37211. this._applyTo(geometry, updatable);
  37212. return this;
  37213. };
  37214. /**
  37215. * Updates the associated mesh
  37216. * @param mesh the mesh to be updated
  37217. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  37218. * @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
  37219. * @returns VertexData
  37220. */
  37221. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  37222. this._update(mesh);
  37223. return this;
  37224. };
  37225. /**
  37226. * Updates the associated geometry
  37227. * @param geometry the geometry to be updated
  37228. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  37229. * @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
  37230. * @returns VertexData.
  37231. */
  37232. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  37233. this._update(geometry);
  37234. return this;
  37235. };
  37236. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  37237. if (updatable === void 0) { updatable = false; }
  37238. if (this.positions) {
  37239. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  37240. }
  37241. if (this.normals) {
  37242. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  37243. }
  37244. if (this.tangents) {
  37245. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  37246. }
  37247. if (this.uvs) {
  37248. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  37249. }
  37250. if (this.uvs2) {
  37251. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  37252. }
  37253. if (this.uvs3) {
  37254. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  37255. }
  37256. if (this.uvs4) {
  37257. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  37258. }
  37259. if (this.uvs5) {
  37260. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  37261. }
  37262. if (this.uvs6) {
  37263. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  37264. }
  37265. if (this.colors) {
  37266. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  37267. }
  37268. if (this.matricesIndices) {
  37269. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  37270. }
  37271. if (this.matricesWeights) {
  37272. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  37273. }
  37274. if (this.matricesIndicesExtra) {
  37275. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  37276. }
  37277. if (this.matricesWeightsExtra) {
  37278. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  37279. }
  37280. if (this.indices) {
  37281. meshOrGeometry.setIndices(this.indices, null, updatable);
  37282. }
  37283. else {
  37284. meshOrGeometry.setIndices([], null);
  37285. }
  37286. return this;
  37287. };
  37288. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  37289. if (this.positions) {
  37290. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  37291. }
  37292. if (this.normals) {
  37293. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  37294. }
  37295. if (this.tangents) {
  37296. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  37297. }
  37298. if (this.uvs) {
  37299. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  37300. }
  37301. if (this.uvs2) {
  37302. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  37303. }
  37304. if (this.uvs3) {
  37305. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  37306. }
  37307. if (this.uvs4) {
  37308. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  37309. }
  37310. if (this.uvs5) {
  37311. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  37312. }
  37313. if (this.uvs6) {
  37314. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  37315. }
  37316. if (this.colors) {
  37317. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  37318. }
  37319. if (this.matricesIndices) {
  37320. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  37321. }
  37322. if (this.matricesWeights) {
  37323. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  37324. }
  37325. if (this.matricesIndicesExtra) {
  37326. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  37327. }
  37328. if (this.matricesWeightsExtra) {
  37329. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  37330. }
  37331. if (this.indices) {
  37332. meshOrGeometry.setIndices(this.indices, null);
  37333. }
  37334. return this;
  37335. };
  37336. /**
  37337. * Transforms each position and each normal of the vertexData according to the passed Matrix
  37338. * @param matrix the transforming matrix
  37339. * @returns the VertexData
  37340. */
  37341. VertexData.prototype.transform = function (matrix) {
  37342. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  37343. var transformed = BABYLON.Vector3.Zero();
  37344. var index;
  37345. if (this.positions) {
  37346. var position = BABYLON.Vector3.Zero();
  37347. for (index = 0; index < this.positions.length; index += 3) {
  37348. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  37349. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  37350. this.positions[index] = transformed.x;
  37351. this.positions[index + 1] = transformed.y;
  37352. this.positions[index + 2] = transformed.z;
  37353. }
  37354. }
  37355. if (this.normals) {
  37356. var normal = BABYLON.Vector3.Zero();
  37357. for (index = 0; index < this.normals.length; index += 3) {
  37358. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  37359. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  37360. this.normals[index] = transformed.x;
  37361. this.normals[index + 1] = transformed.y;
  37362. this.normals[index + 2] = transformed.z;
  37363. }
  37364. }
  37365. if (this.tangents) {
  37366. var tangent = BABYLON.Vector4.Zero();
  37367. var tangentTransformed = BABYLON.Vector4.Zero();
  37368. for (index = 0; index < this.tangents.length; index += 4) {
  37369. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  37370. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  37371. this.tangents[index] = tangentTransformed.x;
  37372. this.tangents[index + 1] = tangentTransformed.y;
  37373. this.tangents[index + 2] = tangentTransformed.z;
  37374. this.tangents[index + 3] = tangentTransformed.w;
  37375. }
  37376. }
  37377. if (flip && this.indices) {
  37378. for (index = 0; index < this.indices.length; index += 3) {
  37379. var tmp = this.indices[index + 1];
  37380. this.indices[index + 1] = this.indices[index + 2];
  37381. this.indices[index + 2] = tmp;
  37382. }
  37383. }
  37384. return this;
  37385. };
  37386. /**
  37387. * Merges the passed VertexData into the current one
  37388. * @param other the VertexData to be merged into the current one
  37389. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  37390. * @returns the modified VertexData
  37391. */
  37392. VertexData.prototype.merge = function (other, use32BitsIndices) {
  37393. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  37394. this._validate();
  37395. other._validate();
  37396. if (!this.normals !== !other.normals ||
  37397. !this.tangents !== !other.tangents ||
  37398. !this.uvs !== !other.uvs ||
  37399. !this.uvs2 !== !other.uvs2 ||
  37400. !this.uvs3 !== !other.uvs3 ||
  37401. !this.uvs4 !== !other.uvs4 ||
  37402. !this.uvs5 !== !other.uvs5 ||
  37403. !this.uvs6 !== !other.uvs6 ||
  37404. !this.colors !== !other.colors ||
  37405. !this.matricesIndices !== !other.matricesIndices ||
  37406. !this.matricesWeights !== !other.matricesWeights ||
  37407. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  37408. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  37409. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  37410. }
  37411. if (other.indices) {
  37412. if (!this.indices) {
  37413. this.indices = [];
  37414. }
  37415. var offset = this.positions ? this.positions.length / 3 : 0;
  37416. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  37417. if (isSrcTypedArray) {
  37418. var len = this.indices.length + other.indices.length;
  37419. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  37420. temp.set(this.indices);
  37421. var decal = this.indices.length;
  37422. for (var index = 0; index < other.indices.length; index++) {
  37423. temp[decal + index] = other.indices[index] + offset;
  37424. }
  37425. this.indices = temp;
  37426. }
  37427. else {
  37428. for (var index = 0; index < other.indices.length; index++) {
  37429. this.indices.push(other.indices[index] + offset);
  37430. }
  37431. }
  37432. }
  37433. this.positions = this._mergeElement(this.positions, other.positions);
  37434. this.normals = this._mergeElement(this.normals, other.normals);
  37435. this.tangents = this._mergeElement(this.tangents, other.tangents);
  37436. this.uvs = this._mergeElement(this.uvs, other.uvs);
  37437. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  37438. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  37439. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  37440. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  37441. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  37442. this.colors = this._mergeElement(this.colors, other.colors);
  37443. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  37444. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  37445. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  37446. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  37447. return this;
  37448. };
  37449. VertexData.prototype._mergeElement = function (source, other) {
  37450. if (!source) {
  37451. return other;
  37452. }
  37453. if (!other) {
  37454. return source;
  37455. }
  37456. var len = other.length + source.length;
  37457. var isSrcTypedArray = source instanceof Float32Array;
  37458. var isOthTypedArray = other instanceof Float32Array;
  37459. // use non-loop method when the source is Float32Array
  37460. if (isSrcTypedArray) {
  37461. var ret32 = new Float32Array(len);
  37462. ret32.set(source);
  37463. ret32.set(other, source.length);
  37464. return ret32;
  37465. // source is number[], when other is also use concat
  37466. }
  37467. else if (!isOthTypedArray) {
  37468. return source.concat(other);
  37469. // source is a number[], but other is a Float32Array, loop required
  37470. }
  37471. else {
  37472. var ret = source.slice(0); // copy source to a separate array
  37473. for (var i = 0, len = other.length; i < len; i++) {
  37474. ret.push(other[i]);
  37475. }
  37476. return ret;
  37477. }
  37478. };
  37479. VertexData.prototype._validate = function () {
  37480. if (!this.positions) {
  37481. throw new Error("Positions are required");
  37482. }
  37483. var getElementCount = function (kind, values) {
  37484. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  37485. if ((values.length % stride) !== 0) {
  37486. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  37487. }
  37488. return values.length / stride;
  37489. };
  37490. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  37491. var validateElementCount = function (kind, values) {
  37492. var elementCount = getElementCount(kind, values);
  37493. if (elementCount !== positionsElementCount) {
  37494. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  37495. }
  37496. };
  37497. if (this.normals)
  37498. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  37499. if (this.tangents)
  37500. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  37501. if (this.uvs)
  37502. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  37503. if (this.uvs2)
  37504. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  37505. if (this.uvs3)
  37506. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  37507. if (this.uvs4)
  37508. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  37509. if (this.uvs5)
  37510. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  37511. if (this.uvs6)
  37512. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  37513. if (this.colors)
  37514. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  37515. if (this.matricesIndices)
  37516. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  37517. if (this.matricesWeights)
  37518. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  37519. if (this.matricesIndicesExtra)
  37520. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  37521. if (this.matricesWeightsExtra)
  37522. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  37523. };
  37524. /**
  37525. * Serializes the VertexData
  37526. * @returns a serialized object
  37527. */
  37528. VertexData.prototype.serialize = function () {
  37529. var serializationObject = this.serialize();
  37530. if (this.positions) {
  37531. serializationObject.positions = this.positions;
  37532. }
  37533. if (this.normals) {
  37534. serializationObject.normals = this.normals;
  37535. }
  37536. if (this.tangents) {
  37537. serializationObject.tangents = this.tangents;
  37538. }
  37539. if (this.uvs) {
  37540. serializationObject.uvs = this.uvs;
  37541. }
  37542. if (this.uvs2) {
  37543. serializationObject.uvs2 = this.uvs2;
  37544. }
  37545. if (this.uvs3) {
  37546. serializationObject.uvs3 = this.uvs3;
  37547. }
  37548. if (this.uvs4) {
  37549. serializationObject.uvs4 = this.uvs4;
  37550. }
  37551. if (this.uvs5) {
  37552. serializationObject.uvs5 = this.uvs5;
  37553. }
  37554. if (this.uvs6) {
  37555. serializationObject.uvs6 = this.uvs6;
  37556. }
  37557. if (this.colors) {
  37558. serializationObject.colors = this.colors;
  37559. }
  37560. if (this.matricesIndices) {
  37561. serializationObject.matricesIndices = this.matricesIndices;
  37562. serializationObject.matricesIndices._isExpanded = true;
  37563. }
  37564. if (this.matricesWeights) {
  37565. serializationObject.matricesWeights = this.matricesWeights;
  37566. }
  37567. if (this.matricesIndicesExtra) {
  37568. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  37569. serializationObject.matricesIndicesExtra._isExpanded = true;
  37570. }
  37571. if (this.matricesWeightsExtra) {
  37572. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  37573. }
  37574. serializationObject.indices = this.indices;
  37575. return serializationObject;
  37576. };
  37577. // Statics
  37578. /**
  37579. * Extracts the vertexData from a mesh
  37580. * @param mesh the mesh from which to extract the VertexData
  37581. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  37582. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37583. * @returns the object VertexData associated to the passed mesh
  37584. */
  37585. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  37586. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  37587. };
  37588. /**
  37589. * Extracts the vertexData from the geometry
  37590. * @param geometry the geometry from which to extract the VertexData
  37591. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  37592. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37593. * @returns the object VertexData associated to the passed mesh
  37594. */
  37595. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  37596. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  37597. };
  37598. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  37599. var result = new VertexData();
  37600. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  37601. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  37602. }
  37603. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37604. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  37605. }
  37606. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37607. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  37608. }
  37609. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37610. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  37611. }
  37612. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37613. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  37614. }
  37615. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  37616. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  37617. }
  37618. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  37619. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  37620. }
  37621. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  37622. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  37623. }
  37624. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37625. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  37626. }
  37627. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37628. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  37629. }
  37630. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37631. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  37632. }
  37633. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37634. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  37635. }
  37636. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  37637. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  37638. }
  37639. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  37640. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  37641. }
  37642. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  37643. return result;
  37644. };
  37645. /**
  37646. * Creates the VertexData for a Ribbon
  37647. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  37648. * * pathArray array of paths, each of which an array of successive Vector3
  37649. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  37650. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  37651. * * 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
  37652. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37653. * * 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)
  37654. * * 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)
  37655. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  37656. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  37657. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  37658. * @returns the VertexData of the ribbon
  37659. */
  37660. VertexData.CreateRibbon = function (options) {
  37661. var pathArray = options.pathArray;
  37662. var closeArray = options.closeArray || false;
  37663. var closePath = options.closePath || false;
  37664. var invertUV = options.invertUV || false;
  37665. var defaultOffset = Math.floor(pathArray[0].length / 2);
  37666. var offset = options.offset || defaultOffset;
  37667. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37668. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37669. var customUV = options.uvs;
  37670. var customColors = options.colors;
  37671. var positions = [];
  37672. var indices = [];
  37673. var normals = [];
  37674. var uvs = [];
  37675. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37676. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37677. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37678. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37679. var minlg; // minimal length among all paths from pathArray
  37680. var lg = []; // array of path lengths : nb of vertex per path
  37681. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37682. var p; // path iterator
  37683. var i; // point iterator
  37684. var j; // point iterator
  37685. // if single path in pathArray
  37686. if (pathArray.length < 2) {
  37687. var ar1 = [];
  37688. var ar2 = [];
  37689. for (i = 0; i < pathArray[0].length - offset; i++) {
  37690. ar1.push(pathArray[0][i]);
  37691. ar2.push(pathArray[0][i + offset]);
  37692. }
  37693. pathArray = [ar1, ar2];
  37694. }
  37695. // positions and horizontal distances (u)
  37696. var idc = 0;
  37697. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37698. var path;
  37699. var l;
  37700. minlg = pathArray[0].length;
  37701. var vectlg;
  37702. var dist;
  37703. for (p = 0; p < pathArray.length; p++) {
  37704. uTotalDistance[p] = 0;
  37705. us[p] = [0];
  37706. path = pathArray[p];
  37707. l = path.length;
  37708. minlg = (minlg < l) ? minlg : l;
  37709. j = 0;
  37710. while (j < l) {
  37711. positions.push(path[j].x, path[j].y, path[j].z);
  37712. if (j > 0) {
  37713. vectlg = path[j].subtract(path[j - 1]).length();
  37714. dist = vectlg + uTotalDistance[p];
  37715. us[p].push(dist);
  37716. uTotalDistance[p] = dist;
  37717. }
  37718. j++;
  37719. }
  37720. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37721. j--;
  37722. positions.push(path[0].x, path[0].y, path[0].z);
  37723. vectlg = path[j].subtract(path[0]).length();
  37724. dist = vectlg + uTotalDistance[p];
  37725. us[p].push(dist);
  37726. uTotalDistance[p] = dist;
  37727. }
  37728. lg[p] = l + closePathCorr;
  37729. idx[p] = idc;
  37730. idc += (l + closePathCorr);
  37731. }
  37732. // vertical distances (v)
  37733. var path1;
  37734. var path2;
  37735. var vertex1 = null;
  37736. var vertex2 = null;
  37737. for (i = 0; i < minlg + closePathCorr; i++) {
  37738. vTotalDistance[i] = 0;
  37739. vs[i] = [0];
  37740. for (p = 0; p < pathArray.length - 1; p++) {
  37741. path1 = pathArray[p];
  37742. path2 = pathArray[p + 1];
  37743. if (i === minlg) { // closePath
  37744. vertex1 = path1[0];
  37745. vertex2 = path2[0];
  37746. }
  37747. else {
  37748. vertex1 = path1[i];
  37749. vertex2 = path2[i];
  37750. }
  37751. vectlg = vertex2.subtract(vertex1).length();
  37752. dist = vectlg + vTotalDistance[i];
  37753. vs[i].push(dist);
  37754. vTotalDistance[i] = dist;
  37755. }
  37756. if (closeArray && vertex2 && vertex1) {
  37757. path1 = pathArray[p];
  37758. path2 = pathArray[0];
  37759. if (i === minlg) { // closePath
  37760. vertex2 = path2[0];
  37761. }
  37762. vectlg = vertex2.subtract(vertex1).length();
  37763. dist = vectlg + vTotalDistance[i];
  37764. vTotalDistance[i] = dist;
  37765. }
  37766. }
  37767. // uvs
  37768. var u;
  37769. var v;
  37770. if (customUV) {
  37771. for (p = 0; p < customUV.length; p++) {
  37772. uvs.push(customUV[p].x, customUV[p].y);
  37773. }
  37774. }
  37775. else {
  37776. for (p = 0; p < pathArray.length; p++) {
  37777. for (i = 0; i < minlg + closePathCorr; i++) {
  37778. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37779. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37780. if (invertUV) {
  37781. uvs.push(v, u);
  37782. }
  37783. else {
  37784. uvs.push(u, v);
  37785. }
  37786. }
  37787. }
  37788. }
  37789. // indices
  37790. p = 0; // path index
  37791. var pi = 0; // positions array index
  37792. var l1 = lg[p] - 1; // path1 length
  37793. var l2 = lg[p + 1] - 1; // path2 length
  37794. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37795. var shft = idx[1] - idx[0]; // shift
  37796. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37797. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37798. // 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
  37799. indices.push(pi, pi + shft, pi + 1);
  37800. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37801. pi += 1;
  37802. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37803. p++;
  37804. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37805. shft = idx[0] - idx[p];
  37806. l1 = lg[p] - 1;
  37807. l2 = lg[0] - 1;
  37808. }
  37809. else {
  37810. shft = idx[p + 1] - idx[p];
  37811. l1 = lg[p] - 1;
  37812. l2 = lg[p + 1] - 1;
  37813. }
  37814. pi = idx[p];
  37815. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37816. }
  37817. }
  37818. // normals
  37819. VertexData.ComputeNormals(positions, indices, normals);
  37820. if (closePath) { // update both the first and last vertex normals to their average value
  37821. var indexFirst = 0;
  37822. var indexLast = 0;
  37823. for (p = 0; p < pathArray.length; p++) {
  37824. indexFirst = idx[p] * 3;
  37825. if (p + 1 < pathArray.length) {
  37826. indexLast = (idx[p + 1] - 1) * 3;
  37827. }
  37828. else {
  37829. indexLast = normals.length - 3;
  37830. }
  37831. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37832. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37833. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37834. normals[indexLast] = normals[indexFirst];
  37835. normals[indexLast + 1] = normals[indexFirst + 1];
  37836. normals[indexLast + 2] = normals[indexFirst + 2];
  37837. }
  37838. }
  37839. // sides
  37840. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37841. // Colors
  37842. var colors = null;
  37843. if (customColors) {
  37844. colors = new Float32Array(customColors.length * 4);
  37845. for (var c = 0; c < customColors.length; c++) {
  37846. colors[c * 4] = customColors[c].r;
  37847. colors[c * 4 + 1] = customColors[c].g;
  37848. colors[c * 4 + 2] = customColors[c].b;
  37849. colors[c * 4 + 3] = customColors[c].a;
  37850. }
  37851. }
  37852. // Result
  37853. var vertexData = new VertexData();
  37854. var positions32 = new Float32Array(positions);
  37855. var normals32 = new Float32Array(normals);
  37856. var uvs32 = new Float32Array(uvs);
  37857. vertexData.indices = indices;
  37858. vertexData.positions = positions32;
  37859. vertexData.normals = normals32;
  37860. vertexData.uvs = uvs32;
  37861. if (colors) {
  37862. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37863. }
  37864. if (closePath) {
  37865. vertexData._idx = idx;
  37866. }
  37867. return vertexData;
  37868. };
  37869. /**
  37870. * Creates the VertexData for a box
  37871. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37872. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37873. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37874. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37875. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37876. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37877. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37878. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37879. * * 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)
  37880. * * 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)
  37881. * @returns the VertexData of the box
  37882. */
  37883. VertexData.CreateBox = function (options) {
  37884. var normalsSource = [
  37885. new BABYLON.Vector3(0, 0, 1),
  37886. new BABYLON.Vector3(0, 0, -1),
  37887. new BABYLON.Vector3(1, 0, 0),
  37888. new BABYLON.Vector3(-1, 0, 0),
  37889. new BABYLON.Vector3(0, 1, 0),
  37890. new BABYLON.Vector3(0, -1, 0)
  37891. ];
  37892. var indices = [];
  37893. var positions = [];
  37894. var normals = [];
  37895. var uvs = [];
  37896. var width = options.width || options.size || 1;
  37897. var height = options.height || options.size || 1;
  37898. var depth = options.depth || options.size || 1;
  37899. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37900. var faceUV = options.faceUV || new Array(6);
  37901. var faceColors = options.faceColors;
  37902. var colors = [];
  37903. // default face colors and UV if undefined
  37904. for (var f = 0; f < 6; f++) {
  37905. if (faceUV[f] === undefined) {
  37906. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37907. }
  37908. if (faceColors && faceColors[f] === undefined) {
  37909. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37910. }
  37911. }
  37912. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37913. // Create each face in turn.
  37914. for (var index = 0; index < normalsSource.length; index++) {
  37915. var normal = normalsSource[index];
  37916. // Get two vectors perpendicular to the face normal and to each other.
  37917. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37918. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37919. // Six indices (two triangles) per face.
  37920. var verticesLength = positions.length / 3;
  37921. indices.push(verticesLength);
  37922. indices.push(verticesLength + 1);
  37923. indices.push(verticesLength + 2);
  37924. indices.push(verticesLength);
  37925. indices.push(verticesLength + 2);
  37926. indices.push(verticesLength + 3);
  37927. // Four vertices per face.
  37928. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37929. positions.push(vertex.x, vertex.y, vertex.z);
  37930. normals.push(normal.x, normal.y, normal.z);
  37931. uvs.push(faceUV[index].z, faceUV[index].w);
  37932. if (faceColors) {
  37933. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37934. }
  37935. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37936. positions.push(vertex.x, vertex.y, vertex.z);
  37937. normals.push(normal.x, normal.y, normal.z);
  37938. uvs.push(faceUV[index].x, faceUV[index].w);
  37939. if (faceColors) {
  37940. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37941. }
  37942. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37943. positions.push(vertex.x, vertex.y, vertex.z);
  37944. normals.push(normal.x, normal.y, normal.z);
  37945. uvs.push(faceUV[index].x, faceUV[index].y);
  37946. if (faceColors) {
  37947. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37948. }
  37949. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37950. positions.push(vertex.x, vertex.y, vertex.z);
  37951. normals.push(normal.x, normal.y, normal.z);
  37952. uvs.push(faceUV[index].z, faceUV[index].y);
  37953. if (faceColors) {
  37954. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37955. }
  37956. }
  37957. // sides
  37958. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37959. // Result
  37960. var vertexData = new VertexData();
  37961. vertexData.indices = indices;
  37962. vertexData.positions = positions;
  37963. vertexData.normals = normals;
  37964. vertexData.uvs = uvs;
  37965. if (faceColors) {
  37966. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37967. vertexData.colors = totalColors;
  37968. }
  37969. return vertexData;
  37970. };
  37971. /**
  37972. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37973. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37974. * * segments sets the number of horizontal strips optional, default 32
  37975. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37976. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37977. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37978. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37979. * * 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
  37980. * * 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
  37981. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37982. * * 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)
  37983. * * 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)
  37984. * @returns the VertexData of the ellipsoid
  37985. */
  37986. VertexData.CreateSphere = function (options) {
  37987. var segments = options.segments || 32;
  37988. var diameterX = options.diameterX || options.diameter || 1;
  37989. var diameterY = options.diameterY || options.diameter || 1;
  37990. var diameterZ = options.diameterZ || options.diameter || 1;
  37991. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37992. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37993. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37994. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37995. var totalZRotationSteps = 2 + segments;
  37996. var totalYRotationSteps = 2 * totalZRotationSteps;
  37997. var indices = [];
  37998. var positions = [];
  37999. var normals = [];
  38000. var uvs = [];
  38001. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  38002. var normalizedZ = zRotationStep / totalZRotationSteps;
  38003. var angleZ = normalizedZ * Math.PI * slice;
  38004. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  38005. var normalizedY = yRotationStep / totalYRotationSteps;
  38006. var angleY = normalizedY * Math.PI * 2 * arc;
  38007. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  38008. var rotationY = BABYLON.Matrix.RotationY(angleY);
  38009. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  38010. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  38011. var vertex = complete.multiply(radius);
  38012. var normal = complete.divide(radius).normalize();
  38013. positions.push(vertex.x, vertex.y, vertex.z);
  38014. normals.push(normal.x, normal.y, normal.z);
  38015. uvs.push(normalizedY, normalizedZ);
  38016. }
  38017. if (zRotationStep > 0) {
  38018. var verticesCount = positions.length / 3;
  38019. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  38020. indices.push((firstIndex));
  38021. indices.push((firstIndex + 1));
  38022. indices.push(firstIndex + totalYRotationSteps + 1);
  38023. indices.push((firstIndex + totalYRotationSteps + 1));
  38024. indices.push((firstIndex + 1));
  38025. indices.push((firstIndex + totalYRotationSteps + 2));
  38026. }
  38027. }
  38028. }
  38029. // Sides
  38030. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38031. // Result
  38032. var vertexData = new VertexData();
  38033. vertexData.indices = indices;
  38034. vertexData.positions = positions;
  38035. vertexData.normals = normals;
  38036. vertexData.uvs = uvs;
  38037. return vertexData;
  38038. };
  38039. /**
  38040. * Creates the VertexData for a cylinder, cone or prism
  38041. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38042. * * height sets the height (y direction) of the cylinder, optional, default 2
  38043. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  38044. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  38045. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  38046. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  38047. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  38048. * * 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
  38049. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38050. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38051. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  38052. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  38053. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38054. * * 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)
  38055. * * 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)
  38056. * @returns the VertexData of the cylinder, cone or prism
  38057. */
  38058. VertexData.CreateCylinder = function (options) {
  38059. var height = options.height || 2;
  38060. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  38061. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  38062. var tessellation = options.tessellation || 24;
  38063. var subdivisions = options.subdivisions || 1;
  38064. var hasRings = options.hasRings ? true : false;
  38065. var enclose = options.enclose ? true : false;
  38066. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38067. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38068. var faceUV = options.faceUV || new Array(3);
  38069. var faceColors = options.faceColors;
  38070. // default face colors and UV if undefined
  38071. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  38072. var ringNb = (hasRings) ? subdivisions : 1;
  38073. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  38074. var f;
  38075. for (f = 0; f < surfaceNb; f++) {
  38076. if (faceColors && faceColors[f] === undefined) {
  38077. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38078. }
  38079. }
  38080. for (f = 0; f < surfaceNb; f++) {
  38081. if (faceUV && faceUV[f] === undefined) {
  38082. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38083. }
  38084. }
  38085. var indices = new Array();
  38086. var positions = new Array();
  38087. var normals = new Array();
  38088. var uvs = new Array();
  38089. var colors = new Array();
  38090. var angle_step = Math.PI * 2 * arc / tessellation;
  38091. var angle;
  38092. var h;
  38093. var radius;
  38094. var tan = (diameterBottom - diameterTop) / 2 / height;
  38095. var ringVertex = BABYLON.Vector3.Zero();
  38096. var ringNormal = BABYLON.Vector3.Zero();
  38097. var ringFirstVertex = BABYLON.Vector3.Zero();
  38098. var ringFirstNormal = BABYLON.Vector3.Zero();
  38099. var quadNormal = BABYLON.Vector3.Zero();
  38100. var Y = BABYLON.Axis.Y;
  38101. // positions, normals, uvs
  38102. var i;
  38103. var j;
  38104. var r;
  38105. var ringIdx = 1;
  38106. var s = 1; // surface index
  38107. var cs = 0;
  38108. var v = 0;
  38109. for (i = 0; i <= subdivisions; i++) {
  38110. h = i / subdivisions;
  38111. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  38112. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  38113. for (r = 0; r < ringIdx; r++) {
  38114. if (hasRings) {
  38115. s += r;
  38116. }
  38117. if (enclose) {
  38118. s += 2 * r;
  38119. }
  38120. for (j = 0; j <= tessellation; j++) {
  38121. angle = j * angle_step;
  38122. // position
  38123. ringVertex.x = Math.cos(-angle) * radius;
  38124. ringVertex.y = -height / 2 + h * height;
  38125. ringVertex.z = Math.sin(-angle) * radius;
  38126. // normal
  38127. if (diameterTop === 0 && i === subdivisions) {
  38128. // if no top cap, reuse former normals
  38129. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  38130. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  38131. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  38132. }
  38133. else {
  38134. ringNormal.x = ringVertex.x;
  38135. ringNormal.z = ringVertex.z;
  38136. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  38137. ringNormal.normalize();
  38138. }
  38139. // keep first ring vertex values for enclose
  38140. if (j === 0) {
  38141. ringFirstVertex.copyFrom(ringVertex);
  38142. ringFirstNormal.copyFrom(ringNormal);
  38143. }
  38144. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  38145. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  38146. if (hasRings) {
  38147. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  38148. }
  38149. else {
  38150. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  38151. }
  38152. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  38153. if (faceColors) {
  38154. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  38155. }
  38156. }
  38157. // if enclose, add four vertices and their dedicated normals
  38158. if (arc !== 1 && enclose) {
  38159. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  38160. positions.push(0, ringVertex.y, 0);
  38161. positions.push(0, ringVertex.y, 0);
  38162. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  38163. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  38164. quadNormal.normalize();
  38165. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  38166. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  38167. quadNormal.normalize();
  38168. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  38169. if (hasRings) {
  38170. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  38171. }
  38172. else {
  38173. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  38174. }
  38175. uvs.push(faceUV[s + 1].x, v);
  38176. uvs.push(faceUV[s + 1].z, v);
  38177. if (hasRings) {
  38178. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  38179. }
  38180. else {
  38181. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  38182. }
  38183. uvs.push(faceUV[s + 2].x, v);
  38184. uvs.push(faceUV[s + 2].z, v);
  38185. if (faceColors) {
  38186. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  38187. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  38188. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  38189. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  38190. }
  38191. }
  38192. if (cs !== s) {
  38193. cs = s;
  38194. }
  38195. }
  38196. }
  38197. // indices
  38198. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  38199. var s;
  38200. i = 0;
  38201. for (s = 0; s < subdivisions; s++) {
  38202. var i0 = 0;
  38203. var i1 = 0;
  38204. var i2 = 0;
  38205. var i3 = 0;
  38206. for (j = 0; j < tessellation; j++) {
  38207. i0 = i * (e + 1) + j;
  38208. i1 = (i + 1) * (e + 1) + j;
  38209. i2 = i * (e + 1) + (j + 1);
  38210. i3 = (i + 1) * (e + 1) + (j + 1);
  38211. indices.push(i0, i1, i2);
  38212. indices.push(i3, i2, i1);
  38213. }
  38214. if (arc !== 1 && enclose) { // if enclose, add two quads
  38215. indices.push(i0 + 2, i1 + 2, i2 + 2);
  38216. indices.push(i3 + 2, i2 + 2, i1 + 2);
  38217. indices.push(i0 + 4, i1 + 4, i2 + 4);
  38218. indices.push(i3 + 4, i2 + 4, i1 + 4);
  38219. }
  38220. i = (hasRings) ? (i + 2) : (i + 1);
  38221. }
  38222. // Caps
  38223. var createCylinderCap = function (isTop) {
  38224. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  38225. if (radius === 0) {
  38226. return;
  38227. }
  38228. // Cap positions, normals & uvs
  38229. var angle;
  38230. var circleVector;
  38231. var i;
  38232. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  38233. var c = null;
  38234. if (faceColors) {
  38235. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  38236. }
  38237. // cap center
  38238. var vbase = positions.length / 3;
  38239. var offset = isTop ? height / 2 : -height / 2;
  38240. var center = new BABYLON.Vector3(0, offset, 0);
  38241. positions.push(center.x, center.y, center.z);
  38242. normals.push(0, isTop ? 1 : -1, 0);
  38243. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  38244. if (c) {
  38245. colors.push(c.r, c.g, c.b, c.a);
  38246. }
  38247. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  38248. for (i = 0; i <= tessellation; i++) {
  38249. angle = Math.PI * 2 * i * arc / tessellation;
  38250. var cos = Math.cos(-angle);
  38251. var sin = Math.sin(-angle);
  38252. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  38253. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  38254. positions.push(circleVector.x, circleVector.y, circleVector.z);
  38255. normals.push(0, isTop ? 1 : -1, 0);
  38256. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  38257. if (c) {
  38258. colors.push(c.r, c.g, c.b, c.a);
  38259. }
  38260. }
  38261. // Cap indices
  38262. for (i = 0; i < tessellation; i++) {
  38263. if (!isTop) {
  38264. indices.push(vbase);
  38265. indices.push(vbase + (i + 1));
  38266. indices.push(vbase + (i + 2));
  38267. }
  38268. else {
  38269. indices.push(vbase);
  38270. indices.push(vbase + (i + 2));
  38271. indices.push(vbase + (i + 1));
  38272. }
  38273. }
  38274. };
  38275. // add caps to geometry
  38276. createCylinderCap(false);
  38277. createCylinderCap(true);
  38278. // Sides
  38279. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38280. var vertexData = new VertexData();
  38281. vertexData.indices = indices;
  38282. vertexData.positions = positions;
  38283. vertexData.normals = normals;
  38284. vertexData.uvs = uvs;
  38285. if (faceColors) {
  38286. vertexData.colors = colors;
  38287. }
  38288. return vertexData;
  38289. };
  38290. /**
  38291. * Creates the VertexData for a torus
  38292. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38293. * * diameter the diameter of the torus, optional default 1
  38294. * * thickness the diameter of the tube forming the torus, optional default 0.5
  38295. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  38296. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38297. * * 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)
  38298. * * 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)
  38299. * @returns the VertexData of the torus
  38300. */
  38301. VertexData.CreateTorus = function (options) {
  38302. var indices = [];
  38303. var positions = [];
  38304. var normals = [];
  38305. var uvs = [];
  38306. var diameter = options.diameter || 1;
  38307. var thickness = options.thickness || 0.5;
  38308. var tessellation = options.tessellation || 16;
  38309. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38310. var stride = tessellation + 1;
  38311. for (var i = 0; i <= tessellation; i++) {
  38312. var u = i / tessellation;
  38313. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  38314. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  38315. for (var j = 0; j <= tessellation; j++) {
  38316. var v = 1 - j / tessellation;
  38317. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  38318. var dx = Math.cos(innerAngle);
  38319. var dy = Math.sin(innerAngle);
  38320. // Create a vertex.
  38321. var normal = new BABYLON.Vector3(dx, dy, 0);
  38322. var position = normal.scale(thickness / 2);
  38323. var textureCoordinate = new BABYLON.Vector2(u, v);
  38324. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  38325. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  38326. positions.push(position.x, position.y, position.z);
  38327. normals.push(normal.x, normal.y, normal.z);
  38328. uvs.push(textureCoordinate.x, textureCoordinate.y);
  38329. // And create indices for two triangles.
  38330. var nextI = (i + 1) % stride;
  38331. var nextJ = (j + 1) % stride;
  38332. indices.push(i * stride + j);
  38333. indices.push(i * stride + nextJ);
  38334. indices.push(nextI * stride + j);
  38335. indices.push(i * stride + nextJ);
  38336. indices.push(nextI * stride + nextJ);
  38337. indices.push(nextI * stride + j);
  38338. }
  38339. }
  38340. // Sides
  38341. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38342. // Result
  38343. var vertexData = new VertexData();
  38344. vertexData.indices = indices;
  38345. vertexData.positions = positions;
  38346. vertexData.normals = normals;
  38347. vertexData.uvs = uvs;
  38348. return vertexData;
  38349. };
  38350. /**
  38351. * Creates the VertexData of the LineSystem
  38352. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  38353. * - lines an array of lines, each line being an array of successive Vector3
  38354. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  38355. * @returns the VertexData of the LineSystem
  38356. */
  38357. VertexData.CreateLineSystem = function (options) {
  38358. var indices = [];
  38359. var positions = [];
  38360. var lines = options.lines;
  38361. var colors = options.colors;
  38362. var vertexColors = [];
  38363. var idx = 0;
  38364. for (var l = 0; l < lines.length; l++) {
  38365. var points = lines[l];
  38366. for (var index = 0; index < points.length; index++) {
  38367. positions.push(points[index].x, points[index].y, points[index].z);
  38368. if (colors) {
  38369. var color = colors[l];
  38370. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  38371. }
  38372. if (index > 0) {
  38373. indices.push(idx - 1);
  38374. indices.push(idx);
  38375. }
  38376. idx++;
  38377. }
  38378. }
  38379. var vertexData = new VertexData();
  38380. vertexData.indices = indices;
  38381. vertexData.positions = positions;
  38382. if (colors) {
  38383. vertexData.colors = vertexColors;
  38384. }
  38385. return vertexData;
  38386. };
  38387. /**
  38388. * Create the VertexData for a DashedLines
  38389. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  38390. * - points an array successive Vector3
  38391. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  38392. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  38393. * - dashNb the intended total number of dashes, optional, default 200
  38394. * @returns the VertexData for the DashedLines
  38395. */
  38396. VertexData.CreateDashedLines = function (options) {
  38397. var dashSize = options.dashSize || 3;
  38398. var gapSize = options.gapSize || 1;
  38399. var dashNb = options.dashNb || 200;
  38400. var points = options.points;
  38401. var positions = new Array();
  38402. var indices = new Array();
  38403. var curvect = BABYLON.Vector3.Zero();
  38404. var lg = 0;
  38405. var nb = 0;
  38406. var shft = 0;
  38407. var dashshft = 0;
  38408. var curshft = 0;
  38409. var idx = 0;
  38410. var i = 0;
  38411. for (i = 0; i < points.length - 1; i++) {
  38412. points[i + 1].subtractToRef(points[i], curvect);
  38413. lg += curvect.length();
  38414. }
  38415. shft = lg / dashNb;
  38416. dashshft = dashSize * shft / (dashSize + gapSize);
  38417. for (i = 0; i < points.length - 1; i++) {
  38418. points[i + 1].subtractToRef(points[i], curvect);
  38419. nb = Math.floor(curvect.length() / shft);
  38420. curvect.normalize();
  38421. for (var j = 0; j < nb; j++) {
  38422. curshft = shft * j;
  38423. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  38424. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  38425. indices.push(idx, idx + 1);
  38426. idx += 2;
  38427. }
  38428. }
  38429. // Result
  38430. var vertexData = new VertexData();
  38431. vertexData.positions = positions;
  38432. vertexData.indices = indices;
  38433. return vertexData;
  38434. };
  38435. /**
  38436. * Creates the VertexData for a Ground
  38437. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  38438. * - width the width (x direction) of the ground, optional, default 1
  38439. * - height the height (z direction) of the ground, optional, default 1
  38440. * - subdivisions the number of subdivisions per side, optional, default 1
  38441. * @returns the VertexData of the Ground
  38442. */
  38443. VertexData.CreateGround = function (options) {
  38444. var indices = [];
  38445. var positions = [];
  38446. var normals = [];
  38447. var uvs = [];
  38448. var row, col;
  38449. var width = options.width || 1;
  38450. var height = options.height || 1;
  38451. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  38452. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  38453. for (row = 0; row <= subdivisionsY; row++) {
  38454. for (col = 0; col <= subdivisionsX; col++) {
  38455. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  38456. var normal = new BABYLON.Vector3(0, 1.0, 0);
  38457. positions.push(position.x, position.y, position.z);
  38458. normals.push(normal.x, normal.y, normal.z);
  38459. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  38460. }
  38461. }
  38462. for (row = 0; row < subdivisionsY; row++) {
  38463. for (col = 0; col < subdivisionsX; col++) {
  38464. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  38465. indices.push(col + 1 + row * (subdivisionsX + 1));
  38466. indices.push(col + row * (subdivisionsX + 1));
  38467. indices.push(col + (row + 1) * (subdivisionsX + 1));
  38468. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  38469. indices.push(col + row * (subdivisionsX + 1));
  38470. }
  38471. }
  38472. // Result
  38473. var vertexData = new VertexData();
  38474. vertexData.indices = indices;
  38475. vertexData.positions = positions;
  38476. vertexData.normals = normals;
  38477. vertexData.uvs = uvs;
  38478. return vertexData;
  38479. };
  38480. /**
  38481. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  38482. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  38483. * * xmin the ground minimum X coordinate, optional, default -1
  38484. * * zmin the ground minimum Z coordinate, optional, default -1
  38485. * * xmax the ground maximum X coordinate, optional, default 1
  38486. * * zmax the ground maximum Z coordinate, optional, default 1
  38487. * * 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}
  38488. * * 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}
  38489. * @returns the VertexData of the TiledGround
  38490. */
  38491. VertexData.CreateTiledGround = function (options) {
  38492. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  38493. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  38494. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  38495. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  38496. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  38497. var precision = options.precision || { w: 1, h: 1 };
  38498. var indices = new Array();
  38499. var positions = new Array();
  38500. var normals = new Array();
  38501. var uvs = new Array();
  38502. var row, col, tileRow, tileCol;
  38503. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  38504. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  38505. precision.w = (precision.w < 1) ? 1 : precision.w;
  38506. precision.h = (precision.h < 1) ? 1 : precision.h;
  38507. var tileSize = {
  38508. 'w': (xmax - xmin) / subdivisions.w,
  38509. 'h': (zmax - zmin) / subdivisions.h
  38510. };
  38511. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  38512. // Indices
  38513. var base = positions.length / 3;
  38514. var rowLength = precision.w + 1;
  38515. for (row = 0; row < precision.h; row++) {
  38516. for (col = 0; col < precision.w; col++) {
  38517. var square = [
  38518. base + col + row * rowLength,
  38519. base + (col + 1) + row * rowLength,
  38520. base + (col + 1) + (row + 1) * rowLength,
  38521. base + col + (row + 1) * rowLength
  38522. ];
  38523. indices.push(square[1]);
  38524. indices.push(square[2]);
  38525. indices.push(square[3]);
  38526. indices.push(square[0]);
  38527. indices.push(square[1]);
  38528. indices.push(square[3]);
  38529. }
  38530. }
  38531. // Position, normals and uvs
  38532. var position = BABYLON.Vector3.Zero();
  38533. var normal = new BABYLON.Vector3(0, 1.0, 0);
  38534. for (row = 0; row <= precision.h; row++) {
  38535. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  38536. for (col = 0; col <= precision.w; col++) {
  38537. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  38538. position.y = 0;
  38539. positions.push(position.x, position.y, position.z);
  38540. normals.push(normal.x, normal.y, normal.z);
  38541. uvs.push(col / precision.w, row / precision.h);
  38542. }
  38543. }
  38544. }
  38545. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  38546. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  38547. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  38548. }
  38549. }
  38550. // Result
  38551. var vertexData = new VertexData();
  38552. vertexData.indices = indices;
  38553. vertexData.positions = positions;
  38554. vertexData.normals = normals;
  38555. vertexData.uvs = uvs;
  38556. return vertexData;
  38557. };
  38558. /**
  38559. * Creates the VertexData of the Ground designed from a heightmap
  38560. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  38561. * * width the width (x direction) of the ground
  38562. * * height the height (z direction) of the ground
  38563. * * subdivisions the number of subdivisions per side
  38564. * * minHeight the minimum altitude on the ground, optional, default 0
  38565. * * maxHeight the maximum altitude on the ground, optional default 1
  38566. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  38567. * * buffer the array holding the image color data
  38568. * * bufferWidth the width of image
  38569. * * bufferHeight the height of image
  38570. * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
  38571. * @returns the VertexData of the Ground designed from a heightmap
  38572. */
  38573. VertexData.CreateGroundFromHeightMap = function (options) {
  38574. var indices = [];
  38575. var positions = [];
  38576. var normals = [];
  38577. var uvs = [];
  38578. var row, col;
  38579. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  38580. var alphaFilter = options.alphaFilter || 0.0;
  38581. // Vertices
  38582. for (row = 0; row <= options.subdivisions; row++) {
  38583. for (col = 0; col <= options.subdivisions; col++) {
  38584. 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));
  38585. // Compute height
  38586. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  38587. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  38588. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  38589. var r = options.buffer[pos] / 255.0;
  38590. var g = options.buffer[pos + 1] / 255.0;
  38591. var b = options.buffer[pos + 2] / 255.0;
  38592. var a = options.buffer[pos + 3] / 255.0;
  38593. var gradient = r * filter.r + g * filter.g + b * filter.b;
  38594. // If our alpha channel is not within our filter then we will assign a 'special' height
  38595. // Then when building the indices, we will ignore any vertex that is using the special height
  38596. if (a >= alphaFilter)
  38597. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  38598. else {
  38599. position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
  38600. }
  38601. // Add vertex
  38602. positions.push(position.x, position.y, position.z);
  38603. normals.push(0, 0, 0);
  38604. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  38605. }
  38606. }
  38607. // Indices
  38608. for (row = 0; row < options.subdivisions; row++) {
  38609. for (col = 0; col < options.subdivisions; col++) {
  38610. // Calculate Indices
  38611. var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
  38612. var idx2 = (col + 1 + row * (options.subdivisions + 1));
  38613. var idx3 = (col + row * (options.subdivisions + 1));
  38614. var idx4 = (col + (row + 1) * (options.subdivisions + 1));
  38615. // Check that all indices are visible (based on our special height)
  38616. // Only display the vertex if all Indices are visible
  38617. // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
  38618. var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
  38619. var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
  38620. var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
  38621. if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
  38622. indices.push(idx1);
  38623. indices.push(idx2);
  38624. indices.push(idx3);
  38625. }
  38626. var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
  38627. if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
  38628. indices.push(idx4);
  38629. indices.push(idx1);
  38630. indices.push(idx3);
  38631. }
  38632. }
  38633. }
  38634. // Normals
  38635. VertexData.ComputeNormals(positions, indices, normals);
  38636. // Result
  38637. var vertexData = new VertexData();
  38638. vertexData.indices = indices;
  38639. vertexData.positions = positions;
  38640. vertexData.normals = normals;
  38641. vertexData.uvs = uvs;
  38642. return vertexData;
  38643. };
  38644. /**
  38645. * Creates the VertexData for a Plane
  38646. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  38647. * * size sets the width and height of the plane to the value of size, optional default 1
  38648. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  38649. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  38650. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38651. * * 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)
  38652. * * 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)
  38653. * @returns the VertexData of the box
  38654. */
  38655. VertexData.CreatePlane = function (options) {
  38656. var indices = [];
  38657. var positions = [];
  38658. var normals = [];
  38659. var uvs = [];
  38660. var width = options.width || options.size || 1;
  38661. var height = options.height || options.size || 1;
  38662. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38663. // Vertices
  38664. var halfWidth = width / 2.0;
  38665. var halfHeight = height / 2.0;
  38666. positions.push(-halfWidth, -halfHeight, 0);
  38667. normals.push(0, 0, -1.0);
  38668. uvs.push(0.0, 0.0);
  38669. positions.push(halfWidth, -halfHeight, 0);
  38670. normals.push(0, 0, -1.0);
  38671. uvs.push(1.0, 0.0);
  38672. positions.push(halfWidth, halfHeight, 0);
  38673. normals.push(0, 0, -1.0);
  38674. uvs.push(1.0, 1.0);
  38675. positions.push(-halfWidth, halfHeight, 0);
  38676. normals.push(0, 0, -1.0);
  38677. uvs.push(0.0, 1.0);
  38678. // Indices
  38679. indices.push(0);
  38680. indices.push(1);
  38681. indices.push(2);
  38682. indices.push(0);
  38683. indices.push(2);
  38684. indices.push(3);
  38685. // Sides
  38686. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38687. // Result
  38688. var vertexData = new VertexData();
  38689. vertexData.indices = indices;
  38690. vertexData.positions = positions;
  38691. vertexData.normals = normals;
  38692. vertexData.uvs = uvs;
  38693. return vertexData;
  38694. };
  38695. /**
  38696. * Creates the VertexData of the Disc or regular Polygon
  38697. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  38698. * * radius the radius of the disc, optional default 0.5
  38699. * * tessellation the number of polygon sides, optional, default 64
  38700. * * 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
  38701. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38702. * * 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)
  38703. * * 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)
  38704. * @returns the VertexData of the box
  38705. */
  38706. VertexData.CreateDisc = function (options) {
  38707. var positions = new Array();
  38708. var indices = new Array();
  38709. var normals = new Array();
  38710. var uvs = new Array();
  38711. var radius = options.radius || 0.5;
  38712. var tessellation = options.tessellation || 64;
  38713. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38714. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38715. // positions and uvs
  38716. positions.push(0, 0, 0); // disc center first
  38717. uvs.push(0.5, 0.5);
  38718. var theta = Math.PI * 2 * arc;
  38719. var step = theta / tessellation;
  38720. for (var a = 0; a < theta; a += step) {
  38721. var x = Math.cos(a);
  38722. var y = Math.sin(a);
  38723. var u = (x + 1) / 2;
  38724. var v = (1 - y) / 2;
  38725. positions.push(radius * x, radius * y, 0);
  38726. uvs.push(u, v);
  38727. }
  38728. if (arc === 1) {
  38729. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38730. uvs.push(uvs[2], uvs[3]);
  38731. }
  38732. //indices
  38733. var vertexNb = positions.length / 3;
  38734. for (var i = 1; i < vertexNb - 1; i++) {
  38735. indices.push(i + 1, 0, i);
  38736. }
  38737. // result
  38738. VertexData.ComputeNormals(positions, indices, normals);
  38739. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38740. var vertexData = new VertexData();
  38741. vertexData.indices = indices;
  38742. vertexData.positions = positions;
  38743. vertexData.normals = normals;
  38744. vertexData.uvs = uvs;
  38745. return vertexData;
  38746. };
  38747. /**
  38748. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38749. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38750. * @param polygon a mesh built from polygonTriangulation.build()
  38751. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38752. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38753. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38754. * @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)
  38755. * @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)
  38756. * @returns the VertexData of the Polygon
  38757. */
  38758. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38759. var faceUV = fUV || new Array(3);
  38760. var faceColors = fColors;
  38761. var colors = [];
  38762. // default face colors and UV if undefined
  38763. for (var f = 0; f < 3; f++) {
  38764. if (faceUV[f] === undefined) {
  38765. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38766. }
  38767. if (faceColors && faceColors[f] === undefined) {
  38768. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38769. }
  38770. }
  38771. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38772. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38773. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38774. var indices = polygon.getIndices();
  38775. // set face colours and textures
  38776. var idx = 0;
  38777. var face = 0;
  38778. for (var index = 0; index < normals.length; index += 3) {
  38779. //Edge Face no. 1
  38780. if (Math.abs(normals[index + 1]) < 0.001) {
  38781. face = 1;
  38782. }
  38783. //Top Face no. 0
  38784. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38785. face = 0;
  38786. }
  38787. //Bottom Face no. 2
  38788. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38789. face = 2;
  38790. }
  38791. idx = index / 3;
  38792. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38793. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38794. if (faceColors) {
  38795. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38796. }
  38797. }
  38798. // sides
  38799. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38800. // Result
  38801. var vertexData = new VertexData();
  38802. vertexData.indices = indices;
  38803. vertexData.positions = positions;
  38804. vertexData.normals = normals;
  38805. vertexData.uvs = uvs;
  38806. if (faceColors) {
  38807. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38808. vertexData.colors = totalColors;
  38809. }
  38810. return vertexData;
  38811. };
  38812. /**
  38813. * Creates the VertexData of the IcoSphere
  38814. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38815. * * radius the radius of the IcoSphere, optional default 1
  38816. * * radiusX allows stretching in the x direction, optional, default radius
  38817. * * radiusY allows stretching in the y direction, optional, default radius
  38818. * * radiusZ allows stretching in the z direction, optional, default radius
  38819. * * flat when true creates a flat shaded mesh, optional, default true
  38820. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38821. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38822. * * 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)
  38823. * * 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)
  38824. * @returns the VertexData of the IcoSphere
  38825. */
  38826. VertexData.CreateIcoSphere = function (options) {
  38827. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38828. var radius = options.radius || 1;
  38829. var flat = (options.flat === undefined) ? true : options.flat;
  38830. var subdivisions = options.subdivisions || 4;
  38831. var radiusX = options.radiusX || radius;
  38832. var radiusY = options.radiusY || radius;
  38833. var radiusZ = options.radiusZ || radius;
  38834. var t = (1 + Math.sqrt(5)) / 2;
  38835. // 12 vertex x,y,z
  38836. var ico_vertices = [
  38837. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38838. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38839. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38840. ];
  38841. // index of 3 vertex makes a face of icopshere
  38842. var ico_indices = [
  38843. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38844. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38845. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38846. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38847. ];
  38848. // vertex for uv have aliased position, not for UV
  38849. var vertices_unalias_id = [
  38850. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38851. // vertex alias
  38852. 0,
  38853. 2,
  38854. 3,
  38855. 3,
  38856. 3,
  38857. 4,
  38858. 7,
  38859. 8,
  38860. 9,
  38861. 9,
  38862. 10,
  38863. 11 // 23: B + 12
  38864. ];
  38865. // uv as integer step (not pixels !)
  38866. var ico_vertexuv = [
  38867. 5, 1, 3, 1, 6, 4, 0, 0,
  38868. 5, 3, 4, 2, 2, 2, 4, 0,
  38869. 2, 0, 1, 1, 6, 0, 6, 2,
  38870. // vertex alias (for same vertex on different faces)
  38871. 0, 4,
  38872. 3, 3,
  38873. 4, 4,
  38874. 3, 1,
  38875. 4, 2,
  38876. 4, 4,
  38877. 0, 2,
  38878. 1, 1,
  38879. 2, 2,
  38880. 3, 3,
  38881. 1, 3,
  38882. 2, 4 // 23: B + 12
  38883. ];
  38884. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38885. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38886. // First island of uv mapping
  38887. // v = 4h 3+ 2
  38888. // v = 3h 9+ 4
  38889. // v = 2h 9+ 5 B
  38890. // v = 1h 9 1 0
  38891. // v = 0h 3 8 7 A
  38892. // u = 0 1 2 3 4 5 6 *a
  38893. // Second island of uv mapping
  38894. // v = 4h 0+ B+ 4+
  38895. // v = 3h A+ 2+
  38896. // v = 2h 7+ 6 3+
  38897. // v = 1h 8+ 3+
  38898. // v = 0h
  38899. // u = 0 1 2 3 4 5 6 *a
  38900. // Face layout on texture UV mapping
  38901. // ============
  38902. // \ 4 /\ 16 / ======
  38903. // \ / \ / /\ 11 /
  38904. // \/ 7 \/ / \ /
  38905. // ======= / 10 \/
  38906. // /\ 17 /\ =======
  38907. // / \ / \ \ 15 /\
  38908. // / 8 \/ 12 \ \ / \
  38909. // ============ \/ 6 \
  38910. // \ 18 /\ ============
  38911. // \ / \ \ 5 /\ 0 /
  38912. // \/ 13 \ \ / \ /
  38913. // ======= \/ 1 \/
  38914. // =============
  38915. // /\ 19 /\ 2 /\
  38916. // / \ / \ / \
  38917. // / 14 \/ 9 \/ 3 \
  38918. // ===================
  38919. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38920. var ustep = 138 / 1024;
  38921. var vstep = 239 / 1024;
  38922. var uoffset = 60 / 1024;
  38923. var voffset = 26 / 1024;
  38924. // Second island should have margin, not to touch the first island
  38925. // avoid any borderline artefact in pixel rounding
  38926. var island_u_offset = -40 / 1024;
  38927. var island_v_offset = +20 / 1024;
  38928. // face is either island 0 or 1 :
  38929. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38930. var island = [
  38931. 0, 0, 0, 0, 1,
  38932. 0, 0, 1, 1, 0,
  38933. 0, 0, 1, 1, 0,
  38934. 0, 1, 1, 1, 0 // 15 - 19
  38935. ];
  38936. var indices = new Array();
  38937. var positions = new Array();
  38938. var normals = new Array();
  38939. var uvs = new Array();
  38940. var current_indice = 0;
  38941. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38942. var face_vertex_pos = new Array(3);
  38943. var face_vertex_uv = new Array(3);
  38944. var v012;
  38945. for (v012 = 0; v012 < 3; v012++) {
  38946. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38947. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38948. }
  38949. // create all with normals
  38950. for (var face = 0; face < 20; face++) {
  38951. // 3 vertex per face
  38952. for (v012 = 0; v012 < 3; v012++) {
  38953. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38954. var v_id = ico_indices[3 * face + v012];
  38955. // vertex have 3D position (x,y,z)
  38956. 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]);
  38957. // Normalize to get normal, then scale to radius
  38958. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38959. // uv Coordinates from vertex ID
  38960. 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);
  38961. }
  38962. // Subdivide the face (interpolate pos, norm, uv)
  38963. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38964. // - norm is linear interpolation of vertex corner normal
  38965. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38966. // - uv is linear interpolation
  38967. //
  38968. // Topology is as below for sub-divide by 2
  38969. // vertex shown as v0,v1,v2
  38970. // interp index is i1 to progress in range [v0,v1[
  38971. // interp index is i2 to progress in range [v0,v2[
  38972. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38973. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38974. //
  38975. //
  38976. // i2 v2
  38977. // ^ ^
  38978. // / / \
  38979. // / / \
  38980. // / / \
  38981. // / / (0,1) \
  38982. // / #---------\
  38983. // / / \ (0,0)'/ \
  38984. // / / \ / \
  38985. // / / \ / \
  38986. // / / (0,0) \ / (1,0) \
  38987. // / #---------#---------\
  38988. // v0 v1
  38989. //
  38990. // --------------------> i1
  38991. //
  38992. // interp of (i1,i2):
  38993. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38994. // along i1 : lerp(x0,x1, i1/(S-i2))
  38995. //
  38996. // centroid of triangle is needed to get help normal computation
  38997. // (c1,c2) are used for centroid location
  38998. var interp_vertex = function (i1, i2, c1, c2) {
  38999. // vertex is interpolated from
  39000. // - face_vertex_pos[0..2]
  39001. // - face_vertex_uv[0..2]
  39002. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  39003. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  39004. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  39005. pos_interp.normalize();
  39006. var vertex_normal;
  39007. if (flat) {
  39008. // in flat mode, recalculate normal as face centroid normal
  39009. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  39010. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  39011. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  39012. }
  39013. else {
  39014. // in smooth mode, recalculate normal from each single vertex position
  39015. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  39016. }
  39017. // Vertex normal need correction due to X,Y,Z radius scaling
  39018. vertex_normal.x /= radiusX;
  39019. vertex_normal.y /= radiusY;
  39020. vertex_normal.z /= radiusZ;
  39021. vertex_normal.normalize();
  39022. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  39023. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  39024. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  39025. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  39026. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  39027. uvs.push(uv_interp.x, uv_interp.y);
  39028. // push each vertex has member of a face
  39029. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  39030. indices.push(current_indice);
  39031. current_indice++;
  39032. };
  39033. for (var i2 = 0; i2 < subdivisions; i2++) {
  39034. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  39035. // face : (i1,i2) for /\ :
  39036. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  39037. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39038. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39039. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39040. if (i1 + i2 + 1 < subdivisions) {
  39041. // face : (i1,i2)' for \/ :
  39042. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  39043. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39044. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39045. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39046. }
  39047. }
  39048. }
  39049. }
  39050. // Sides
  39051. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39052. // Result
  39053. var vertexData = new VertexData();
  39054. vertexData.indices = indices;
  39055. vertexData.positions = positions;
  39056. vertexData.normals = normals;
  39057. vertexData.uvs = uvs;
  39058. return vertexData;
  39059. };
  39060. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  39061. /**
  39062. * Creates the VertexData for a Polyhedron
  39063. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  39064. * * type provided types are:
  39065. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  39066. * * 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)
  39067. * * size the size of the IcoSphere, optional default 1
  39068. * * sizeX allows stretching in the x direction, optional, default size
  39069. * * sizeY allows stretching in the y direction, optional, default size
  39070. * * sizeZ allows stretching in the z direction, optional, default size
  39071. * * 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
  39072. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  39073. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  39074. * * flat when true creates a flat shaded mesh, optional, default true
  39075. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  39076. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39077. * * 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)
  39078. * * 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)
  39079. * @returns the VertexData of the Polyhedron
  39080. */
  39081. VertexData.CreatePolyhedron = function (options) {
  39082. // provided polyhedron types :
  39083. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  39084. // 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)
  39085. var polyhedra = [];
  39086. 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]] };
  39087. 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]] };
  39088. polyhedra[2] = {
  39089. 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]],
  39090. 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]]
  39091. };
  39092. polyhedra[3] = {
  39093. 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]],
  39094. 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]]
  39095. };
  39096. polyhedra[4] = {
  39097. 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]],
  39098. 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]]
  39099. };
  39100. 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]] };
  39101. 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]] };
  39102. 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]] };
  39103. 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]] };
  39104. 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]] };
  39105. 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]] };
  39106. 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]] };
  39107. 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]] };
  39108. 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]] };
  39109. polyhedra[14] = {
  39110. 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]],
  39111. 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]]
  39112. };
  39113. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  39114. var size = options.size;
  39115. var sizeX = options.sizeX || size || 1;
  39116. var sizeY = options.sizeY || size || 1;
  39117. var sizeZ = options.sizeZ || size || 1;
  39118. var data = options.custom || polyhedra[type];
  39119. var nbfaces = data.face.length;
  39120. var faceUV = options.faceUV || new Array(nbfaces);
  39121. var faceColors = options.faceColors;
  39122. var flat = (options.flat === undefined) ? true : options.flat;
  39123. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39124. var positions = new Array();
  39125. var indices = new Array();
  39126. var normals = new Array();
  39127. var uvs = new Array();
  39128. var colors = new Array();
  39129. var index = 0;
  39130. var faceIdx = 0; // face cursor in the array "indexes"
  39131. var indexes = new Array();
  39132. var i = 0;
  39133. var f = 0;
  39134. var u, v, ang, x, y, tmp;
  39135. // default face colors and UV if undefined
  39136. if (flat) {
  39137. for (f = 0; f < nbfaces; f++) {
  39138. if (faceColors && faceColors[f] === undefined) {
  39139. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  39140. }
  39141. if (faceUV && faceUV[f] === undefined) {
  39142. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  39143. }
  39144. }
  39145. }
  39146. if (!flat) {
  39147. for (i = 0; i < data.vertex.length; i++) {
  39148. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  39149. uvs.push(0, 0);
  39150. }
  39151. for (f = 0; f < nbfaces; f++) {
  39152. for (i = 0; i < data.face[f].length - 2; i++) {
  39153. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  39154. }
  39155. }
  39156. }
  39157. else {
  39158. for (f = 0; f < nbfaces; f++) {
  39159. var fl = data.face[f].length; // number of vertices of the current face
  39160. ang = 2 * Math.PI / fl;
  39161. x = 0.5 * Math.tan(ang / 2);
  39162. y = 0.5;
  39163. // positions, uvs, colors
  39164. for (i = 0; i < fl; i++) {
  39165. // positions
  39166. 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);
  39167. indexes.push(index);
  39168. index++;
  39169. // uvs
  39170. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  39171. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  39172. uvs.push(u, v);
  39173. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  39174. y = x * Math.sin(ang) + y * Math.cos(ang);
  39175. x = tmp;
  39176. // colors
  39177. if (faceColors) {
  39178. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  39179. }
  39180. }
  39181. // indices from indexes
  39182. for (i = 0; i < fl - 2; i++) {
  39183. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  39184. }
  39185. faceIdx += fl;
  39186. }
  39187. }
  39188. VertexData.ComputeNormals(positions, indices, normals);
  39189. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39190. var vertexData = new VertexData();
  39191. vertexData.positions = positions;
  39192. vertexData.indices = indices;
  39193. vertexData.normals = normals;
  39194. vertexData.uvs = uvs;
  39195. if (faceColors && flat) {
  39196. vertexData.colors = colors;
  39197. }
  39198. return vertexData;
  39199. };
  39200. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  39201. /**
  39202. * Creates the VertexData for a TorusKnot
  39203. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  39204. * * radius the radius of the torus knot, optional, default 2
  39205. * * tube the thickness of the tube, optional, default 0.5
  39206. * * radialSegments the number of sides on each tube segments, optional, default 32
  39207. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  39208. * * p the number of windings around the z axis, optional, default 2
  39209. * * q the number of windings around the x axis, optional, default 3
  39210. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39211. * * 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)
  39212. * * 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)
  39213. * @returns the VertexData of the Torus Knot
  39214. */
  39215. VertexData.CreateTorusKnot = function (options) {
  39216. var indices = new Array();
  39217. var positions = new Array();
  39218. var normals = new Array();
  39219. var uvs = new Array();
  39220. var radius = options.radius || 2;
  39221. var tube = options.tube || 0.5;
  39222. var radialSegments = options.radialSegments || 32;
  39223. var tubularSegments = options.tubularSegments || 32;
  39224. var p = options.p || 2;
  39225. var q = options.q || 3;
  39226. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39227. // Helper
  39228. var getPos = function (angle) {
  39229. var cu = Math.cos(angle);
  39230. var su = Math.sin(angle);
  39231. var quOverP = q / p * angle;
  39232. var cs = Math.cos(quOverP);
  39233. var tx = radius * (2 + cs) * 0.5 * cu;
  39234. var ty = radius * (2 + cs) * su * 0.5;
  39235. var tz = radius * Math.sin(quOverP) * 0.5;
  39236. return new BABYLON.Vector3(tx, ty, tz);
  39237. };
  39238. // Vertices
  39239. var i;
  39240. var j;
  39241. for (i = 0; i <= radialSegments; i++) {
  39242. var modI = i % radialSegments;
  39243. var u = modI / radialSegments * 2 * p * Math.PI;
  39244. var p1 = getPos(u);
  39245. var p2 = getPos(u + 0.01);
  39246. var tang = p2.subtract(p1);
  39247. var n = p2.add(p1);
  39248. var bitan = BABYLON.Vector3.Cross(tang, n);
  39249. n = BABYLON.Vector3.Cross(bitan, tang);
  39250. bitan.normalize();
  39251. n.normalize();
  39252. for (j = 0; j < tubularSegments; j++) {
  39253. var modJ = j % tubularSegments;
  39254. var v = modJ / tubularSegments * 2 * Math.PI;
  39255. var cx = -tube * Math.cos(v);
  39256. var cy = tube * Math.sin(v);
  39257. positions.push(p1.x + cx * n.x + cy * bitan.x);
  39258. positions.push(p1.y + cx * n.y + cy * bitan.y);
  39259. positions.push(p1.z + cx * n.z + cy * bitan.z);
  39260. uvs.push(i / radialSegments);
  39261. uvs.push(j / tubularSegments);
  39262. }
  39263. }
  39264. for (i = 0; i < radialSegments; i++) {
  39265. for (j = 0; j < tubularSegments; j++) {
  39266. var jNext = (j + 1) % tubularSegments;
  39267. var a = i * tubularSegments + j;
  39268. var b = (i + 1) * tubularSegments + j;
  39269. var c = (i + 1) * tubularSegments + jNext;
  39270. var d = i * tubularSegments + jNext;
  39271. indices.push(d);
  39272. indices.push(b);
  39273. indices.push(a);
  39274. indices.push(d);
  39275. indices.push(c);
  39276. indices.push(b);
  39277. }
  39278. }
  39279. // Normals
  39280. VertexData.ComputeNormals(positions, indices, normals);
  39281. // Sides
  39282. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39283. // Result
  39284. var vertexData = new VertexData();
  39285. vertexData.indices = indices;
  39286. vertexData.positions = positions;
  39287. vertexData.normals = normals;
  39288. vertexData.uvs = uvs;
  39289. return vertexData;
  39290. };
  39291. // Tools
  39292. /**
  39293. * Compute normals for given positions and indices
  39294. * @param positions an array of vertex positions, [...., x, y, z, ......]
  39295. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  39296. * @param normals an array of vertex normals, [...., x, y, z, ......]
  39297. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  39298. * * facetNormals : optional array of facet normals (vector3)
  39299. * * facetPositions : optional array of facet positions (vector3)
  39300. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  39301. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  39302. * * bInfo : optional bounding info, required for facetPartitioning computation
  39303. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  39304. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  39305. * * useRightHandedSystem: optional boolean to for right handed system computation
  39306. * * depthSort : optional boolean to enable the facet depth sort computation
  39307. * * distanceTo : optional Vector3 to compute the facet depth from this location
  39308. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  39309. */
  39310. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  39311. // temporary scalar variables
  39312. var index = 0; // facet index
  39313. var p1p2x = 0.0; // p1p2 vector x coordinate
  39314. var p1p2y = 0.0; // p1p2 vector y coordinate
  39315. var p1p2z = 0.0; // p1p2 vector z coordinate
  39316. var p3p2x = 0.0; // p3p2 vector x coordinate
  39317. var p3p2y = 0.0; // p3p2 vector y coordinate
  39318. var p3p2z = 0.0; // p3p2 vector z coordinate
  39319. var faceNormalx = 0.0; // facet normal x coordinate
  39320. var faceNormaly = 0.0; // facet normal y coordinate
  39321. var faceNormalz = 0.0; // facet normal z coordinate
  39322. var length = 0.0; // facet normal length before normalization
  39323. var v1x = 0; // vector1 x index in the positions array
  39324. var v1y = 0; // vector1 y index in the positions array
  39325. var v1z = 0; // vector1 z index in the positions array
  39326. var v2x = 0; // vector2 x index in the positions array
  39327. var v2y = 0; // vector2 y index in the positions array
  39328. var v2z = 0; // vector2 z index in the positions array
  39329. var v3x = 0; // vector3 x index in the positions array
  39330. var v3y = 0; // vector3 y index in the positions array
  39331. var v3z = 0; // vector3 z index in the positions array
  39332. var computeFacetNormals = false;
  39333. var computeFacetPositions = false;
  39334. var computeFacetPartitioning = false;
  39335. var computeDepthSort = false;
  39336. var faceNormalSign = 1;
  39337. var ratio = 0;
  39338. var distanceTo = null;
  39339. if (options) {
  39340. computeFacetNormals = (options.facetNormals) ? true : false;
  39341. computeFacetPositions = (options.facetPositions) ? true : false;
  39342. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  39343. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  39344. ratio = options.ratio || 0;
  39345. computeDepthSort = (options.depthSort) ? true : false;
  39346. distanceTo = (options.distanceTo);
  39347. if (computeDepthSort) {
  39348. if (distanceTo === undefined) {
  39349. distanceTo = BABYLON.Vector3.Zero();
  39350. }
  39351. var depthSortedFacets = options.depthSortedFacets;
  39352. }
  39353. }
  39354. // facetPartitioning reinit if needed
  39355. var xSubRatio = 0;
  39356. var ySubRatio = 0;
  39357. var zSubRatio = 0;
  39358. var subSq = 0;
  39359. if (computeFacetPartitioning && options && options.bbSize) {
  39360. var ox = 0; // X partitioning index for facet position
  39361. var oy = 0; // Y partinioning index for facet position
  39362. var oz = 0; // Z partinioning index for facet position
  39363. var b1x = 0; // X partitioning index for facet v1 vertex
  39364. var b1y = 0; // Y partitioning index for facet v1 vertex
  39365. var b1z = 0; // z partitioning index for facet v1 vertex
  39366. var b2x = 0; // X partitioning index for facet v2 vertex
  39367. var b2y = 0; // Y partitioning index for facet v2 vertex
  39368. var b2z = 0; // Z partitioning index for facet v2 vertex
  39369. var b3x = 0; // X partitioning index for facet v3 vertex
  39370. var b3y = 0; // Y partitioning index for facet v3 vertex
  39371. var b3z = 0; // Z partitioning index for facet v3 vertex
  39372. var block_idx_o = 0; // facet barycenter block index
  39373. var block_idx_v1 = 0; // v1 vertex block index
  39374. var block_idx_v2 = 0; // v2 vertex block index
  39375. var block_idx_v3 = 0; // v3 vertex block index
  39376. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  39377. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  39378. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  39379. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  39380. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  39381. subSq = options.subDiv.max * options.subDiv.max;
  39382. options.facetPartitioning.length = 0;
  39383. }
  39384. // reset the normals
  39385. for (index = 0; index < positions.length; index++) {
  39386. normals[index] = 0.0;
  39387. }
  39388. // Loop : 1 indice triplet = 1 facet
  39389. var nbFaces = (indices.length / 3) | 0;
  39390. for (index = 0; index < nbFaces; index++) {
  39391. // get the indexes of the coordinates of each vertex of the facet
  39392. v1x = indices[index * 3] * 3;
  39393. v1y = v1x + 1;
  39394. v1z = v1x + 2;
  39395. v2x = indices[index * 3 + 1] * 3;
  39396. v2y = v2x + 1;
  39397. v2z = v2x + 2;
  39398. v3x = indices[index * 3 + 2] * 3;
  39399. v3y = v3x + 1;
  39400. v3z = v3x + 2;
  39401. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  39402. p1p2y = positions[v1y] - positions[v2y];
  39403. p1p2z = positions[v1z] - positions[v2z];
  39404. p3p2x = positions[v3x] - positions[v2x];
  39405. p3p2y = positions[v3y] - positions[v2y];
  39406. p3p2z = positions[v3z] - positions[v2z];
  39407. // compute the face normal with the cross product
  39408. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  39409. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  39410. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  39411. // normalize this normal and store it in the array facetData
  39412. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  39413. length = (length === 0) ? 1.0 : length;
  39414. faceNormalx /= length;
  39415. faceNormaly /= length;
  39416. faceNormalz /= length;
  39417. if (computeFacetNormals && options) {
  39418. options.facetNormals[index].x = faceNormalx;
  39419. options.facetNormals[index].y = faceNormaly;
  39420. options.facetNormals[index].z = faceNormalz;
  39421. }
  39422. if (computeFacetPositions && options) {
  39423. // compute and the facet barycenter coordinates in the array facetPositions
  39424. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  39425. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  39426. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  39427. }
  39428. if (computeFacetPartitioning && options) {
  39429. // store the facet indexes in arrays in the main facetPartitioning array :
  39430. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  39431. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  39432. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  39433. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  39434. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39435. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39436. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39437. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39438. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39439. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39440. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39441. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39442. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39443. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  39444. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  39445. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  39446. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  39447. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  39448. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  39449. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  39450. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  39451. // push each facet index in each block containing the vertex
  39452. options.facetPartitioning[block_idx_v1].push(index);
  39453. if (block_idx_v2 != block_idx_v1) {
  39454. options.facetPartitioning[block_idx_v2].push(index);
  39455. }
  39456. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  39457. options.facetPartitioning[block_idx_v3].push(index);
  39458. }
  39459. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  39460. options.facetPartitioning[block_idx_o].push(index);
  39461. }
  39462. }
  39463. if (computeDepthSort && options && options.facetPositions) {
  39464. var dsf = depthSortedFacets[index];
  39465. dsf.ind = index * 3;
  39466. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  39467. }
  39468. // compute the normals anyway
  39469. normals[v1x] += faceNormalx; // accumulate all the normals per face
  39470. normals[v1y] += faceNormaly;
  39471. normals[v1z] += faceNormalz;
  39472. normals[v2x] += faceNormalx;
  39473. normals[v2y] += faceNormaly;
  39474. normals[v2z] += faceNormalz;
  39475. normals[v3x] += faceNormalx;
  39476. normals[v3y] += faceNormaly;
  39477. normals[v3z] += faceNormalz;
  39478. }
  39479. // last normalization of each normal
  39480. for (index = 0; index < normals.length / 3; index++) {
  39481. faceNormalx = normals[index * 3];
  39482. faceNormaly = normals[index * 3 + 1];
  39483. faceNormalz = normals[index * 3 + 2];
  39484. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  39485. length = (length === 0) ? 1.0 : length;
  39486. faceNormalx /= length;
  39487. faceNormaly /= length;
  39488. faceNormalz /= length;
  39489. normals[index * 3] = faceNormalx;
  39490. normals[index * 3 + 1] = faceNormaly;
  39491. normals[index * 3 + 2] = faceNormalz;
  39492. }
  39493. };
  39494. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  39495. var li = indices.length;
  39496. var ln = normals.length;
  39497. var i;
  39498. var n;
  39499. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39500. switch (sideOrientation) {
  39501. case BABYLON.Mesh.FRONTSIDE:
  39502. // nothing changed
  39503. break;
  39504. case BABYLON.Mesh.BACKSIDE:
  39505. var tmp;
  39506. // indices
  39507. for (i = 0; i < li; i += 3) {
  39508. tmp = indices[i];
  39509. indices[i] = indices[i + 2];
  39510. indices[i + 2] = tmp;
  39511. }
  39512. // normals
  39513. for (n = 0; n < ln; n++) {
  39514. normals[n] = -normals[n];
  39515. }
  39516. break;
  39517. case BABYLON.Mesh.DOUBLESIDE:
  39518. // positions
  39519. var lp = positions.length;
  39520. var l = lp / 3;
  39521. for (var p = 0; p < lp; p++) {
  39522. positions[lp + p] = positions[p];
  39523. }
  39524. // indices
  39525. for (i = 0; i < li; i += 3) {
  39526. indices[i + li] = indices[i + 2] + l;
  39527. indices[i + 1 + li] = indices[i + 1] + l;
  39528. indices[i + 2 + li] = indices[i] + l;
  39529. }
  39530. // normals
  39531. for (n = 0; n < ln; n++) {
  39532. normals[ln + n] = -normals[n];
  39533. }
  39534. // uvs
  39535. var lu = uvs.length;
  39536. var u = 0;
  39537. for (u = 0; u < lu; u++) {
  39538. uvs[u + lu] = uvs[u];
  39539. }
  39540. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  39541. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  39542. u = 0;
  39543. for (i = 0; i < lu / 2; i++) {
  39544. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  39545. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  39546. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  39547. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  39548. u += 2;
  39549. }
  39550. break;
  39551. }
  39552. };
  39553. /**
  39554. * Applies VertexData created from the imported parameters to the geometry
  39555. * @param parsedVertexData the parsed data from an imported file
  39556. * @param geometry the geometry to apply the VertexData to
  39557. */
  39558. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  39559. var vertexData = new VertexData();
  39560. // positions
  39561. var positions = parsedVertexData.positions;
  39562. if (positions) {
  39563. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  39564. }
  39565. // normals
  39566. var normals = parsedVertexData.normals;
  39567. if (normals) {
  39568. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  39569. }
  39570. // tangents
  39571. var tangents = parsedVertexData.tangents;
  39572. if (tangents) {
  39573. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  39574. }
  39575. // uvs
  39576. var uvs = parsedVertexData.uvs;
  39577. if (uvs) {
  39578. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  39579. }
  39580. // uv2s
  39581. var uv2s = parsedVertexData.uv2s;
  39582. if (uv2s) {
  39583. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  39584. }
  39585. // uv3s
  39586. var uv3s = parsedVertexData.uv3s;
  39587. if (uv3s) {
  39588. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  39589. }
  39590. // uv4s
  39591. var uv4s = parsedVertexData.uv4s;
  39592. if (uv4s) {
  39593. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  39594. }
  39595. // uv5s
  39596. var uv5s = parsedVertexData.uv5s;
  39597. if (uv5s) {
  39598. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  39599. }
  39600. // uv6s
  39601. var uv6s = parsedVertexData.uv6s;
  39602. if (uv6s) {
  39603. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  39604. }
  39605. // colors
  39606. var colors = parsedVertexData.colors;
  39607. if (colors) {
  39608. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  39609. }
  39610. // matricesIndices
  39611. var matricesIndices = parsedVertexData.matricesIndices;
  39612. if (matricesIndices) {
  39613. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  39614. }
  39615. // matricesWeights
  39616. var matricesWeights = parsedVertexData.matricesWeights;
  39617. if (matricesWeights) {
  39618. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  39619. }
  39620. // indices
  39621. var indices = parsedVertexData.indices;
  39622. if (indices) {
  39623. vertexData.indices = indices;
  39624. }
  39625. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  39626. };
  39627. return VertexData;
  39628. }());
  39629. BABYLON.VertexData = VertexData;
  39630. })(BABYLON || (BABYLON = {}));
  39631. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  39632. var BABYLON;
  39633. (function (BABYLON) {
  39634. /**
  39635. * Class used to store geometry data (vertex buffers + index buffer)
  39636. */
  39637. var Geometry = /** @class */ (function () {
  39638. /**
  39639. * Creates a new geometry
  39640. * @param id defines the unique ID
  39641. * @param scene defines the hosting scene
  39642. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  39643. * @param updatable defines if geometry must be updatable (false by default)
  39644. * @param mesh defines the mesh that will be associated with the geometry
  39645. */
  39646. function Geometry(id, scene, vertexData, updatable, mesh) {
  39647. if (updatable === void 0) { updatable = false; }
  39648. if (mesh === void 0) { mesh = null; }
  39649. /**
  39650. * Gets the delay loading state of the geometry (none by default which means not delayed)
  39651. */
  39652. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39653. this._totalVertices = 0;
  39654. this._isDisposed = false;
  39655. this._indexBufferIsUpdatable = false;
  39656. this.id = id;
  39657. this._engine = scene.getEngine();
  39658. this._meshes = [];
  39659. this._scene = scene;
  39660. //Init vertex buffer cache
  39661. this._vertexBuffers = {};
  39662. this._indices = [];
  39663. this._updatable = updatable;
  39664. // vertexData
  39665. if (vertexData) {
  39666. this.setAllVerticesData(vertexData, updatable);
  39667. }
  39668. else {
  39669. this._totalVertices = 0;
  39670. this._indices = [];
  39671. }
  39672. if (this._engine.getCaps().vertexArrayObject) {
  39673. this._vertexArrayObjects = {};
  39674. }
  39675. // applyToMesh
  39676. if (mesh) {
  39677. if (mesh.getClassName() === "LinesMesh") {
  39678. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  39679. this._updateExtend();
  39680. }
  39681. this.applyToMesh(mesh);
  39682. mesh.computeWorldMatrix(true);
  39683. }
  39684. }
  39685. Object.defineProperty(Geometry.prototype, "boundingBias", {
  39686. /**
  39687. * 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
  39688. */
  39689. get: function () {
  39690. return this._boundingBias;
  39691. },
  39692. /**
  39693. * 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
  39694. */
  39695. set: function (value) {
  39696. if (this._boundingBias) {
  39697. if (this._boundingBias.equals(value)) {
  39698. return;
  39699. }
  39700. this._boundingBias.copyFrom(value);
  39701. }
  39702. else {
  39703. this._boundingBias = value.clone();
  39704. }
  39705. this._updateBoundingInfo(true, null);
  39706. },
  39707. enumerable: true,
  39708. configurable: true
  39709. });
  39710. /**
  39711. * Static function used to attach a new empty geometry to a mesh
  39712. * @param mesh defines the mesh to attach the geometry to
  39713. * @returns the new {BABYLON.Geometry}
  39714. */
  39715. Geometry.CreateGeometryForMesh = function (mesh) {
  39716. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  39717. geometry.applyToMesh(mesh);
  39718. return geometry;
  39719. };
  39720. Object.defineProperty(Geometry.prototype, "extend", {
  39721. /**
  39722. * Gets the current extend of the geometry
  39723. */
  39724. get: function () {
  39725. return this._extend;
  39726. },
  39727. enumerable: true,
  39728. configurable: true
  39729. });
  39730. /**
  39731. * Gets the hosting scene
  39732. * @returns the hosting {BABYLON.Scene}
  39733. */
  39734. Geometry.prototype.getScene = function () {
  39735. return this._scene;
  39736. };
  39737. /**
  39738. * Gets the hosting engine
  39739. * @returns the hosting {BABYLON.Engine}
  39740. */
  39741. Geometry.prototype.getEngine = function () {
  39742. return this._engine;
  39743. };
  39744. /**
  39745. * Defines if the geometry is ready to use
  39746. * @returns true if the geometry is ready to be used
  39747. */
  39748. Geometry.prototype.isReady = function () {
  39749. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39750. };
  39751. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39752. /**
  39753. * Gets a value indicating that the geometry should not be serialized
  39754. */
  39755. get: function () {
  39756. for (var index = 0; index < this._meshes.length; index++) {
  39757. if (!this._meshes[index].doNotSerialize) {
  39758. return false;
  39759. }
  39760. }
  39761. return true;
  39762. },
  39763. enumerable: true,
  39764. configurable: true
  39765. });
  39766. /** @hidden */
  39767. Geometry.prototype._rebuild = function () {
  39768. if (this._vertexArrayObjects) {
  39769. this._vertexArrayObjects = {};
  39770. }
  39771. // Index buffer
  39772. if (this._meshes.length !== 0 && this._indices) {
  39773. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39774. }
  39775. // Vertex buffers
  39776. for (var key in this._vertexBuffers) {
  39777. var vertexBuffer = this._vertexBuffers[key];
  39778. vertexBuffer._rebuild();
  39779. }
  39780. };
  39781. /**
  39782. * Affects all geometry data in one call
  39783. * @param vertexData defines the geometry data
  39784. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39785. */
  39786. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39787. vertexData.applyToGeometry(this, updatable);
  39788. this.notifyUpdate();
  39789. };
  39790. /**
  39791. * Set specific vertex data
  39792. * @param kind defines the data kind (Position, normal, etc...)
  39793. * @param data defines the vertex data to use
  39794. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39795. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39796. */
  39797. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39798. if (updatable === void 0) { updatable = false; }
  39799. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39800. this.setVerticesBuffer(buffer);
  39801. };
  39802. /**
  39803. * Removes a specific vertex data
  39804. * @param kind defines the data kind (Position, normal, etc...)
  39805. */
  39806. Geometry.prototype.removeVerticesData = function (kind) {
  39807. if (this._vertexBuffers[kind]) {
  39808. this._vertexBuffers[kind].dispose();
  39809. delete this._vertexBuffers[kind];
  39810. }
  39811. };
  39812. /**
  39813. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39814. * @param buffer defines the vertex buffer to use
  39815. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39816. */
  39817. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39818. if (totalVertices === void 0) { totalVertices = null; }
  39819. var kind = buffer.getKind();
  39820. if (this._vertexBuffers[kind]) {
  39821. this._vertexBuffers[kind].dispose();
  39822. }
  39823. this._vertexBuffers[kind] = buffer;
  39824. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39825. var data = buffer.getData();
  39826. if (totalVertices != null) {
  39827. this._totalVertices = totalVertices;
  39828. }
  39829. else {
  39830. if (data != null) {
  39831. this._totalVertices = data.length / (buffer.byteStride / 4);
  39832. }
  39833. }
  39834. this._updateExtend(data);
  39835. this._resetPointsArrayCache();
  39836. var meshes = this._meshes;
  39837. var numOfMeshes = meshes.length;
  39838. for (var index = 0; index < numOfMeshes; index++) {
  39839. var mesh = meshes[index];
  39840. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39841. mesh._createGlobalSubMesh(false);
  39842. mesh.computeWorldMatrix(true);
  39843. }
  39844. }
  39845. this.notifyUpdate(kind);
  39846. if (this._vertexArrayObjects) {
  39847. this._disposeVertexArrayObjects();
  39848. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39849. }
  39850. };
  39851. /**
  39852. * Update a specific vertex buffer
  39853. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39854. * It will do nothing if the buffer is not updatable
  39855. * @param kind defines the data kind (Position, normal, etc...)
  39856. * @param data defines the data to use
  39857. * @param offset defines the offset in the target buffer where to store the data
  39858. * @param useBytes set to true if the offset is in bytes
  39859. */
  39860. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39861. if (useBytes === void 0) { useBytes = false; }
  39862. var vertexBuffer = this.getVertexBuffer(kind);
  39863. if (!vertexBuffer) {
  39864. return;
  39865. }
  39866. vertexBuffer.updateDirectly(data, offset, useBytes);
  39867. this.notifyUpdate(kind);
  39868. };
  39869. /**
  39870. * Update a specific vertex buffer
  39871. * This function will create a new buffer if the current one is not updatable
  39872. * @param kind defines the data kind (Position, normal, etc...)
  39873. * @param data defines the data to use
  39874. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39875. */
  39876. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39877. if (updateExtends === void 0) { updateExtends = false; }
  39878. var vertexBuffer = this.getVertexBuffer(kind);
  39879. if (!vertexBuffer) {
  39880. return;
  39881. }
  39882. vertexBuffer.update(data);
  39883. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39884. this._updateBoundingInfo(updateExtends, data);
  39885. }
  39886. this.notifyUpdate(kind);
  39887. };
  39888. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39889. if (updateExtends) {
  39890. this._updateExtend(data);
  39891. }
  39892. var meshes = this._meshes;
  39893. var numOfMeshes = meshes.length;
  39894. this._resetPointsArrayCache();
  39895. for (var index = 0; index < numOfMeshes; index++) {
  39896. var mesh = meshes[index];
  39897. if (updateExtends) {
  39898. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39899. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39900. var subMesh = mesh.subMeshes[subIndex];
  39901. subMesh.refreshBoundingInfo();
  39902. }
  39903. }
  39904. }
  39905. };
  39906. /** @hidden */
  39907. Geometry.prototype._bind = function (effect, indexToBind) {
  39908. if (!effect) {
  39909. return;
  39910. }
  39911. if (indexToBind === undefined) {
  39912. indexToBind = this._indexBuffer;
  39913. }
  39914. var vbs = this.getVertexBuffers();
  39915. if (!vbs) {
  39916. return;
  39917. }
  39918. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39919. this._engine.bindBuffers(vbs, indexToBind, effect);
  39920. return;
  39921. }
  39922. // Using VAO
  39923. if (!this._vertexArrayObjects[effect.key]) {
  39924. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39925. }
  39926. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39927. };
  39928. /**
  39929. * Gets total number of vertices
  39930. * @returns the total number of vertices
  39931. */
  39932. Geometry.prototype.getTotalVertices = function () {
  39933. if (!this.isReady()) {
  39934. return 0;
  39935. }
  39936. return this._totalVertices;
  39937. };
  39938. /**
  39939. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39940. * @param kind defines the data kind (Position, normal, etc...)
  39941. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39942. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39943. * @returns a float array containing vertex data
  39944. */
  39945. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39946. var vertexBuffer = this.getVertexBuffer(kind);
  39947. if (!vertexBuffer) {
  39948. return null;
  39949. }
  39950. var data = vertexBuffer.getData();
  39951. if (!data) {
  39952. return null;
  39953. }
  39954. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39955. var count = this._totalVertices * vertexBuffer.getSize();
  39956. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39957. var copy_1 = new Array(count);
  39958. vertexBuffer.forEach(count, function (value, index) {
  39959. copy_1[index] = value;
  39960. });
  39961. return copy_1;
  39962. }
  39963. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39964. if (data instanceof Array) {
  39965. var offset = vertexBuffer.byteOffset / 4;
  39966. return BABYLON.Tools.Slice(data, offset, offset + count);
  39967. }
  39968. else if (data instanceof ArrayBuffer) {
  39969. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39970. }
  39971. else {
  39972. var offset = data.byteOffset + vertexBuffer.byteOffset;
  39973. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39974. var result = new Float32Array(count);
  39975. var source = new Float32Array(data.buffer, offset, count);
  39976. result.set(source);
  39977. return result;
  39978. }
  39979. return new Float32Array(data.buffer, offset, count);
  39980. }
  39981. }
  39982. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39983. return BABYLON.Tools.Slice(data);
  39984. }
  39985. return data;
  39986. };
  39987. /**
  39988. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39989. * @param kind defines the data kind (Position, normal, etc...)
  39990. * @returns true if the vertex buffer with the specified kind is updatable
  39991. */
  39992. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39993. var vb = this._vertexBuffers[kind];
  39994. if (!vb) {
  39995. return false;
  39996. }
  39997. return vb.isUpdatable();
  39998. };
  39999. /**
  40000. * Gets a specific vertex buffer
  40001. * @param kind defines the data kind (Position, normal, etc...)
  40002. * @returns a {BABYLON.VertexBuffer}
  40003. */
  40004. Geometry.prototype.getVertexBuffer = function (kind) {
  40005. if (!this.isReady()) {
  40006. return null;
  40007. }
  40008. return this._vertexBuffers[kind];
  40009. };
  40010. /**
  40011. * Returns all vertex buffers
  40012. * @return an object holding all vertex buffers indexed by kind
  40013. */
  40014. Geometry.prototype.getVertexBuffers = function () {
  40015. if (!this.isReady()) {
  40016. return null;
  40017. }
  40018. return this._vertexBuffers;
  40019. };
  40020. /**
  40021. * Gets a boolean indicating if specific vertex buffer is present
  40022. * @param kind defines the data kind (Position, normal, etc...)
  40023. * @returns true if data is present
  40024. */
  40025. Geometry.prototype.isVerticesDataPresent = function (kind) {
  40026. if (!this._vertexBuffers) {
  40027. if (this._delayInfo) {
  40028. return this._delayInfo.indexOf(kind) !== -1;
  40029. }
  40030. return false;
  40031. }
  40032. return this._vertexBuffers[kind] !== undefined;
  40033. };
  40034. /**
  40035. * Gets a list of all attached data kinds (Position, normal, etc...)
  40036. * @returns a list of string containing all kinds
  40037. */
  40038. Geometry.prototype.getVerticesDataKinds = function () {
  40039. var result = [];
  40040. var kind;
  40041. if (!this._vertexBuffers && this._delayInfo) {
  40042. for (kind in this._delayInfo) {
  40043. result.push(kind);
  40044. }
  40045. }
  40046. else {
  40047. for (kind in this._vertexBuffers) {
  40048. result.push(kind);
  40049. }
  40050. }
  40051. return result;
  40052. };
  40053. /**
  40054. * Update index buffer
  40055. * @param indices defines the indices to store in the index buffer
  40056. * @param offset defines the offset in the target buffer where to store the data
  40057. */
  40058. Geometry.prototype.updateIndices = function (indices, offset) {
  40059. if (!this._indexBuffer) {
  40060. return;
  40061. }
  40062. if (!this._indexBufferIsUpdatable) {
  40063. this.setIndices(indices, null, true);
  40064. }
  40065. else {
  40066. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  40067. }
  40068. };
  40069. /**
  40070. * Creates a new index buffer
  40071. * @param indices defines the indices to store in the index buffer
  40072. * @param totalVertices defines the total number of vertices (could be null)
  40073. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  40074. */
  40075. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  40076. if (totalVertices === void 0) { totalVertices = null; }
  40077. if (updatable === void 0) { updatable = false; }
  40078. if (this._indexBuffer) {
  40079. this._engine._releaseBuffer(this._indexBuffer);
  40080. }
  40081. this._disposeVertexArrayObjects();
  40082. this._indices = indices;
  40083. this._indexBufferIsUpdatable = updatable;
  40084. if (this._meshes.length !== 0 && this._indices) {
  40085. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  40086. }
  40087. if (totalVertices != undefined) { // including null and undefined
  40088. this._totalVertices = totalVertices;
  40089. }
  40090. var meshes = this._meshes;
  40091. var numOfMeshes = meshes.length;
  40092. for (var index = 0; index < numOfMeshes; index++) {
  40093. meshes[index]._createGlobalSubMesh(true);
  40094. }
  40095. this.notifyUpdate();
  40096. };
  40097. /**
  40098. * Return the total number of indices
  40099. * @returns the total number of indices
  40100. */
  40101. Geometry.prototype.getTotalIndices = function () {
  40102. if (!this.isReady()) {
  40103. return 0;
  40104. }
  40105. return this._indices.length;
  40106. };
  40107. /**
  40108. * Gets the index buffer array
  40109. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  40110. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  40111. * @returns the index buffer array
  40112. */
  40113. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  40114. if (!this.isReady()) {
  40115. return null;
  40116. }
  40117. var orig = this._indices;
  40118. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  40119. return orig;
  40120. }
  40121. else {
  40122. var len = orig.length;
  40123. var copy = [];
  40124. for (var i = 0; i < len; i++) {
  40125. copy.push(orig[i]);
  40126. }
  40127. return copy;
  40128. }
  40129. };
  40130. /**
  40131. * Gets the index buffer
  40132. * @return the index buffer
  40133. */
  40134. Geometry.prototype.getIndexBuffer = function () {
  40135. if (!this.isReady()) {
  40136. return null;
  40137. }
  40138. return this._indexBuffer;
  40139. };
  40140. /** @hidden */
  40141. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  40142. if (effect === void 0) { effect = null; }
  40143. if (!effect || !this._vertexArrayObjects) {
  40144. return;
  40145. }
  40146. if (this._vertexArrayObjects[effect.key]) {
  40147. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  40148. delete this._vertexArrayObjects[effect.key];
  40149. }
  40150. };
  40151. /**
  40152. * Release the associated resources for a specific mesh
  40153. * @param mesh defines the source mesh
  40154. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  40155. */
  40156. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  40157. var meshes = this._meshes;
  40158. var index = meshes.indexOf(mesh);
  40159. if (index === -1) {
  40160. return;
  40161. }
  40162. meshes.splice(index, 1);
  40163. mesh._geometry = null;
  40164. if (meshes.length === 0 && shouldDispose) {
  40165. this.dispose();
  40166. }
  40167. };
  40168. /**
  40169. * Apply current geometry to a given mesh
  40170. * @param mesh defines the mesh to apply geometry to
  40171. */
  40172. Geometry.prototype.applyToMesh = function (mesh) {
  40173. if (mesh._geometry === this) {
  40174. return;
  40175. }
  40176. var previousGeometry = mesh._geometry;
  40177. if (previousGeometry) {
  40178. previousGeometry.releaseForMesh(mesh);
  40179. }
  40180. var meshes = this._meshes;
  40181. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  40182. mesh._geometry = this;
  40183. this._scene.pushGeometry(this);
  40184. meshes.push(mesh);
  40185. if (this.isReady()) {
  40186. this._applyToMesh(mesh);
  40187. }
  40188. else {
  40189. mesh._boundingInfo = this._boundingInfo;
  40190. }
  40191. };
  40192. Geometry.prototype._updateExtend = function (data) {
  40193. if (data === void 0) { data = null; }
  40194. if (!data) {
  40195. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40196. }
  40197. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  40198. };
  40199. Geometry.prototype._applyToMesh = function (mesh) {
  40200. var numOfMeshes = this._meshes.length;
  40201. // vertexBuffers
  40202. for (var kind in this._vertexBuffers) {
  40203. if (numOfMeshes === 1) {
  40204. this._vertexBuffers[kind].create();
  40205. }
  40206. var buffer = this._vertexBuffers[kind].getBuffer();
  40207. if (buffer)
  40208. buffer.references = numOfMeshes;
  40209. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40210. if (!this._extend) {
  40211. this._updateExtend();
  40212. }
  40213. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40214. mesh._createGlobalSubMesh(false);
  40215. //bounding info was just created again, world matrix should be applied again.
  40216. mesh._updateBoundingInfo();
  40217. }
  40218. }
  40219. // indexBuffer
  40220. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  40221. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  40222. }
  40223. if (this._indexBuffer) {
  40224. this._indexBuffer.references = numOfMeshes;
  40225. }
  40226. };
  40227. Geometry.prototype.notifyUpdate = function (kind) {
  40228. if (this.onGeometryUpdated) {
  40229. this.onGeometryUpdated(this, kind);
  40230. }
  40231. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  40232. var mesh = _a[_i];
  40233. mesh._markSubMeshesAsAttributesDirty();
  40234. }
  40235. };
  40236. /**
  40237. * Load the geometry if it was flagged as delay loaded
  40238. * @param scene defines the hosting scene
  40239. * @param onLoaded defines a callback called when the geometry is loaded
  40240. */
  40241. Geometry.prototype.load = function (scene, onLoaded) {
  40242. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  40243. return;
  40244. }
  40245. if (this.isReady()) {
  40246. if (onLoaded) {
  40247. onLoaded();
  40248. }
  40249. return;
  40250. }
  40251. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  40252. this._queueLoad(scene, onLoaded);
  40253. };
  40254. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  40255. var _this = this;
  40256. if (!this.delayLoadingFile) {
  40257. return;
  40258. }
  40259. scene._addPendingData(this);
  40260. scene._loadFile(this.delayLoadingFile, function (data) {
  40261. if (!_this._delayLoadingFunction) {
  40262. return;
  40263. }
  40264. _this._delayLoadingFunction(JSON.parse(data), _this);
  40265. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  40266. _this._delayInfo = [];
  40267. scene._removePendingData(_this);
  40268. var meshes = _this._meshes;
  40269. var numOfMeshes = meshes.length;
  40270. for (var index = 0; index < numOfMeshes; index++) {
  40271. _this._applyToMesh(meshes[index]);
  40272. }
  40273. if (onLoaded) {
  40274. onLoaded();
  40275. }
  40276. }, undefined, true);
  40277. };
  40278. /**
  40279. * Invert the geometry to move from a right handed system to a left handed one.
  40280. */
  40281. Geometry.prototype.toLeftHanded = function () {
  40282. // Flip faces
  40283. var tIndices = this.getIndices(false);
  40284. if (tIndices != null && tIndices.length > 0) {
  40285. for (var i = 0; i < tIndices.length; i += 3) {
  40286. var tTemp = tIndices[i + 0];
  40287. tIndices[i + 0] = tIndices[i + 2];
  40288. tIndices[i + 2] = tTemp;
  40289. }
  40290. this.setIndices(tIndices);
  40291. }
  40292. // Negate position.z
  40293. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  40294. if (tPositions != null && tPositions.length > 0) {
  40295. for (var i = 0; i < tPositions.length; i += 3) {
  40296. tPositions[i + 2] = -tPositions[i + 2];
  40297. }
  40298. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  40299. }
  40300. // Negate normal.z
  40301. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  40302. if (tNormals != null && tNormals.length > 0) {
  40303. for (var i = 0; i < tNormals.length; i += 3) {
  40304. tNormals[i + 2] = -tNormals[i + 2];
  40305. }
  40306. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  40307. }
  40308. };
  40309. // Cache
  40310. /** @hidden */
  40311. Geometry.prototype._resetPointsArrayCache = function () {
  40312. this._positions = null;
  40313. };
  40314. /** @hidden */
  40315. Geometry.prototype._generatePointsArray = function () {
  40316. if (this._positions)
  40317. return true;
  40318. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40319. if (!data || data.length === 0) {
  40320. return false;
  40321. }
  40322. this._positions = [];
  40323. for (var index = 0; index < data.length; index += 3) {
  40324. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  40325. }
  40326. return true;
  40327. };
  40328. /**
  40329. * Gets a value indicating if the geometry is disposed
  40330. * @returns true if the geometry was disposed
  40331. */
  40332. Geometry.prototype.isDisposed = function () {
  40333. return this._isDisposed;
  40334. };
  40335. Geometry.prototype._disposeVertexArrayObjects = function () {
  40336. if (this._vertexArrayObjects) {
  40337. for (var kind in this._vertexArrayObjects) {
  40338. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  40339. }
  40340. this._vertexArrayObjects = {};
  40341. }
  40342. };
  40343. /**
  40344. * Free all associated resources
  40345. */
  40346. Geometry.prototype.dispose = function () {
  40347. var meshes = this._meshes;
  40348. var numOfMeshes = meshes.length;
  40349. var index;
  40350. for (index = 0; index < numOfMeshes; index++) {
  40351. this.releaseForMesh(meshes[index]);
  40352. }
  40353. this._meshes = [];
  40354. this._disposeVertexArrayObjects();
  40355. for (var kind in this._vertexBuffers) {
  40356. this._vertexBuffers[kind].dispose();
  40357. }
  40358. this._vertexBuffers = {};
  40359. this._totalVertices = 0;
  40360. if (this._indexBuffer) {
  40361. this._engine._releaseBuffer(this._indexBuffer);
  40362. }
  40363. this._indexBuffer = null;
  40364. this._indices = [];
  40365. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  40366. this.delayLoadingFile = null;
  40367. this._delayLoadingFunction = null;
  40368. this._delayInfo = [];
  40369. this._boundingInfo = null;
  40370. this._scene.removeGeometry(this);
  40371. this._isDisposed = true;
  40372. };
  40373. /**
  40374. * Clone the current geometry into a new geometry
  40375. * @param id defines the unique ID of the new geometry
  40376. * @returns a new geometry object
  40377. */
  40378. Geometry.prototype.copy = function (id) {
  40379. var vertexData = new BABYLON.VertexData();
  40380. vertexData.indices = [];
  40381. var indices = this.getIndices();
  40382. if (indices) {
  40383. for (var index = 0; index < indices.length; index++) {
  40384. vertexData.indices.push(indices[index]);
  40385. }
  40386. }
  40387. var updatable = false;
  40388. var stopChecking = false;
  40389. var kind;
  40390. for (kind in this._vertexBuffers) {
  40391. // using slice() to make a copy of the array and not just reference it
  40392. var data = this.getVerticesData(kind);
  40393. if (data instanceof Float32Array) {
  40394. vertexData.set(new Float32Array(data), kind);
  40395. }
  40396. else {
  40397. vertexData.set(data.slice(0), kind);
  40398. }
  40399. if (!stopChecking) {
  40400. var vb = this.getVertexBuffer(kind);
  40401. if (vb) {
  40402. updatable = vb.isUpdatable();
  40403. stopChecking = !updatable;
  40404. }
  40405. }
  40406. }
  40407. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  40408. geometry.delayLoadState = this.delayLoadState;
  40409. geometry.delayLoadingFile = this.delayLoadingFile;
  40410. geometry._delayLoadingFunction = this._delayLoadingFunction;
  40411. for (kind in this._delayInfo) {
  40412. geometry._delayInfo = geometry._delayInfo || [];
  40413. geometry._delayInfo.push(kind);
  40414. }
  40415. // Bounding info
  40416. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40417. return geometry;
  40418. };
  40419. /**
  40420. * Serialize the current geometry info (and not the vertices data) into a JSON object
  40421. * @return a JSON representation of the current geometry data (without the vertices data)
  40422. */
  40423. Geometry.prototype.serialize = function () {
  40424. var serializationObject = {};
  40425. serializationObject.id = this.id;
  40426. serializationObject.updatable = this._updatable;
  40427. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  40428. serializationObject.tags = BABYLON.Tags.GetTags(this);
  40429. }
  40430. return serializationObject;
  40431. };
  40432. Geometry.prototype.toNumberArray = function (origin) {
  40433. if (Array.isArray(origin)) {
  40434. return origin;
  40435. }
  40436. else {
  40437. return Array.prototype.slice.call(origin);
  40438. }
  40439. };
  40440. /**
  40441. * Serialize all vertices data into a JSON oject
  40442. * @returns a JSON representation of the current geometry data
  40443. */
  40444. Geometry.prototype.serializeVerticeData = function () {
  40445. var serializationObject = this.serialize();
  40446. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  40447. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  40448. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  40449. serializationObject.positions._updatable = true;
  40450. }
  40451. }
  40452. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40453. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  40454. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  40455. serializationObject.normals._updatable = true;
  40456. }
  40457. }
  40458. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40459. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  40460. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  40461. serializationObject.tangets._updatable = true;
  40462. }
  40463. }
  40464. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  40465. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  40466. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  40467. serializationObject.uvs._updatable = true;
  40468. }
  40469. }
  40470. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  40471. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  40472. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  40473. serializationObject.uv2s._updatable = true;
  40474. }
  40475. }
  40476. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  40477. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  40478. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  40479. serializationObject.uv3s._updatable = true;
  40480. }
  40481. }
  40482. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  40483. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  40484. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  40485. serializationObject.uv4s._updatable = true;
  40486. }
  40487. }
  40488. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  40489. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  40490. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  40491. serializationObject.uv5s._updatable = true;
  40492. }
  40493. }
  40494. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  40495. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  40496. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  40497. serializationObject.uv6s._updatable = true;
  40498. }
  40499. }
  40500. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  40501. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  40502. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  40503. serializationObject.colors._updatable = true;
  40504. }
  40505. }
  40506. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  40507. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  40508. serializationObject.matricesIndices._isExpanded = true;
  40509. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  40510. serializationObject.matricesIndices._updatable = true;
  40511. }
  40512. }
  40513. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  40514. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  40515. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  40516. serializationObject.matricesWeights._updatable = true;
  40517. }
  40518. }
  40519. serializationObject.indices = this.toNumberArray(this.getIndices());
  40520. return serializationObject;
  40521. };
  40522. // Statics
  40523. /**
  40524. * Extracts a clone of a mesh geometry
  40525. * @param mesh defines the source mesh
  40526. * @param id defines the unique ID of the new geometry object
  40527. * @returns the new geometry object
  40528. */
  40529. Geometry.ExtractFromMesh = function (mesh, id) {
  40530. var geometry = mesh._geometry;
  40531. if (!geometry) {
  40532. return null;
  40533. }
  40534. return geometry.copy(id);
  40535. };
  40536. /**
  40537. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  40538. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  40539. * Be aware Math.random() could cause collisions, but:
  40540. * "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"
  40541. * @returns a string containing a new GUID
  40542. */
  40543. Geometry.RandomId = function () {
  40544. return BABYLON.Tools.RandomId();
  40545. };
  40546. /** @hidden */
  40547. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  40548. var scene = mesh.getScene();
  40549. // Geometry
  40550. var geometryId = parsedGeometry.geometryId;
  40551. if (geometryId) {
  40552. var geometry = scene.getGeometryByID(geometryId);
  40553. if (geometry) {
  40554. geometry.applyToMesh(mesh);
  40555. }
  40556. }
  40557. else if (parsedGeometry instanceof ArrayBuffer) {
  40558. var binaryInfo = mesh._binaryInfo;
  40559. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  40560. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  40561. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  40562. }
  40563. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  40564. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  40565. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  40566. }
  40567. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  40568. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  40569. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  40570. }
  40571. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  40572. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  40573. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  40574. }
  40575. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  40576. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  40577. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  40578. }
  40579. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  40580. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  40581. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  40582. }
  40583. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  40584. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  40585. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  40586. }
  40587. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  40588. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  40589. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  40590. }
  40591. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  40592. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  40593. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  40594. }
  40595. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  40596. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  40597. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  40598. }
  40599. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  40600. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  40601. var floatIndices = [];
  40602. for (var i = 0; i < matricesIndicesData.length; i++) {
  40603. var index = matricesIndicesData[i];
  40604. floatIndices.push(index & 0x000000FF);
  40605. floatIndices.push((index & 0x0000FF00) >> 8);
  40606. floatIndices.push((index & 0x00FF0000) >> 16);
  40607. floatIndices.push(index >> 24);
  40608. }
  40609. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  40610. }
  40611. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  40612. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  40613. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  40614. }
  40615. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  40616. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  40617. mesh.setIndices(indicesData, null);
  40618. }
  40619. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  40620. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  40621. mesh.subMeshes = [];
  40622. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  40623. var materialIndex = subMeshesData[(i * 5) + 0];
  40624. var verticesStart = subMeshesData[(i * 5) + 1];
  40625. var verticesCount = subMeshesData[(i * 5) + 2];
  40626. var indexStart = subMeshesData[(i * 5) + 3];
  40627. var indexCount = subMeshesData[(i * 5) + 4];
  40628. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  40629. }
  40630. }
  40631. }
  40632. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  40633. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  40634. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  40635. if (parsedGeometry.tangents) {
  40636. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  40637. }
  40638. if (parsedGeometry.uvs) {
  40639. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  40640. }
  40641. if (parsedGeometry.uvs2) {
  40642. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  40643. }
  40644. if (parsedGeometry.uvs3) {
  40645. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  40646. }
  40647. if (parsedGeometry.uvs4) {
  40648. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  40649. }
  40650. if (parsedGeometry.uvs5) {
  40651. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  40652. }
  40653. if (parsedGeometry.uvs6) {
  40654. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  40655. }
  40656. if (parsedGeometry.colors) {
  40657. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  40658. }
  40659. if (parsedGeometry.matricesIndices) {
  40660. if (!parsedGeometry.matricesIndices._isExpanded) {
  40661. var floatIndices = [];
  40662. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  40663. var matricesIndex = parsedGeometry.matricesIndices[i];
  40664. floatIndices.push(matricesIndex & 0x000000FF);
  40665. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40666. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40667. floatIndices.push(matricesIndex >> 24);
  40668. }
  40669. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  40670. }
  40671. else {
  40672. delete parsedGeometry.matricesIndices._isExpanded;
  40673. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  40674. }
  40675. }
  40676. if (parsedGeometry.matricesIndicesExtra) {
  40677. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  40678. var floatIndices = [];
  40679. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  40680. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  40681. floatIndices.push(matricesIndex & 0x000000FF);
  40682. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40683. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40684. floatIndices.push(matricesIndex >> 24);
  40685. }
  40686. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  40687. }
  40688. else {
  40689. delete parsedGeometry.matricesIndices._isExpanded;
  40690. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  40691. }
  40692. }
  40693. if (parsedGeometry.matricesWeights) {
  40694. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  40695. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  40696. }
  40697. if (parsedGeometry.matricesWeightsExtra) {
  40698. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  40699. }
  40700. mesh.setIndices(parsedGeometry.indices, null);
  40701. }
  40702. // SubMeshes
  40703. if (parsedGeometry.subMeshes) {
  40704. mesh.subMeshes = [];
  40705. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  40706. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  40707. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  40708. }
  40709. }
  40710. // Flat shading
  40711. if (mesh._shouldGenerateFlatShading) {
  40712. mesh.convertToFlatShadedMesh();
  40713. delete mesh._shouldGenerateFlatShading;
  40714. }
  40715. // Update
  40716. mesh.computeWorldMatrix(true);
  40717. scene.onMeshImportedObservable.notifyObservers(mesh);
  40718. };
  40719. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  40720. var epsilon = 1e-3;
  40721. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  40722. return;
  40723. }
  40724. var noInfluenceBoneIndex = 0.0;
  40725. if (parsedGeometry.skeletonId > -1) {
  40726. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  40727. if (!skeleton) {
  40728. return;
  40729. }
  40730. noInfluenceBoneIndex = skeleton.bones.length;
  40731. }
  40732. else {
  40733. return;
  40734. }
  40735. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40736. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40737. var matricesWeights = parsedGeometry.matricesWeights;
  40738. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  40739. var influencers = parsedGeometry.numBoneInfluencer;
  40740. var size = matricesWeights.length;
  40741. for (var i = 0; i < size; i += 4) {
  40742. var weight = 0.0;
  40743. var firstZeroWeight = -1;
  40744. for (var j = 0; j < 4; j++) {
  40745. var w = matricesWeights[i + j];
  40746. weight += w;
  40747. if (w < epsilon && firstZeroWeight < 0) {
  40748. firstZeroWeight = j;
  40749. }
  40750. }
  40751. if (matricesWeightsExtra) {
  40752. for (var j = 0; j < 4; j++) {
  40753. var w = matricesWeightsExtra[i + j];
  40754. weight += w;
  40755. if (w < epsilon && firstZeroWeight < 0) {
  40756. firstZeroWeight = j + 4;
  40757. }
  40758. }
  40759. }
  40760. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40761. firstZeroWeight = influencers - 1;
  40762. }
  40763. if (weight > epsilon) {
  40764. var mweight = 1.0 / weight;
  40765. for (var j = 0; j < 4; j++) {
  40766. matricesWeights[i + j] *= mweight;
  40767. }
  40768. if (matricesWeightsExtra) {
  40769. for (var j = 0; j < 4; j++) {
  40770. matricesWeightsExtra[i + j] *= mweight;
  40771. }
  40772. }
  40773. }
  40774. else {
  40775. if (firstZeroWeight >= 4) {
  40776. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40777. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40778. }
  40779. else {
  40780. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40781. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40782. }
  40783. }
  40784. }
  40785. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40786. if (parsedGeometry.matricesWeightsExtra) {
  40787. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40788. }
  40789. };
  40790. /**
  40791. * Create a new geometry from persisted data (Using .babylon file format)
  40792. * @param parsedVertexData defines the persisted data
  40793. * @param scene defines the hosting scene
  40794. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40795. * @returns the new geometry object
  40796. */
  40797. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40798. if (scene.getGeometryByID(parsedVertexData.id)) {
  40799. return null; // null since geometry could be something else than a box...
  40800. }
  40801. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40802. if (BABYLON.Tags) {
  40803. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40804. }
  40805. if (parsedVertexData.delayLoadingFile) {
  40806. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40807. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40808. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40809. geometry._delayInfo = [];
  40810. if (parsedVertexData.hasUVs) {
  40811. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40812. }
  40813. if (parsedVertexData.hasUVs2) {
  40814. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40815. }
  40816. if (parsedVertexData.hasUVs3) {
  40817. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40818. }
  40819. if (parsedVertexData.hasUVs4) {
  40820. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40821. }
  40822. if (parsedVertexData.hasUVs5) {
  40823. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40824. }
  40825. if (parsedVertexData.hasUVs6) {
  40826. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40827. }
  40828. if (parsedVertexData.hasColors) {
  40829. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40830. }
  40831. if (parsedVertexData.hasMatricesIndices) {
  40832. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40833. }
  40834. if (parsedVertexData.hasMatricesWeights) {
  40835. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40836. }
  40837. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40838. }
  40839. else {
  40840. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40841. }
  40842. scene.pushGeometry(geometry, true);
  40843. return geometry;
  40844. };
  40845. return Geometry;
  40846. }());
  40847. BABYLON.Geometry = Geometry;
  40848. // Primitives
  40849. /// Abstract class
  40850. /**
  40851. * Abstract class used to provide common services for all typed geometries
  40852. * @hidden
  40853. */
  40854. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40855. __extends(_PrimitiveGeometry, _super);
  40856. /**
  40857. * Creates a new typed geometry
  40858. * @param id defines the unique ID of the geometry
  40859. * @param scene defines the hosting scene
  40860. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40861. * @param mesh defines the hosting mesh (can be null)
  40862. */
  40863. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40864. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40865. if (mesh === void 0) { mesh = null; }
  40866. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40867. _this._canBeRegenerated = _canBeRegenerated;
  40868. _this._beingRegenerated = true;
  40869. _this.regenerate();
  40870. _this._beingRegenerated = false;
  40871. return _this;
  40872. }
  40873. /**
  40874. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40875. * @returns true if the geometry can be regenerated
  40876. */
  40877. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40878. return this._canBeRegenerated;
  40879. };
  40880. /**
  40881. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40882. */
  40883. _PrimitiveGeometry.prototype.regenerate = function () {
  40884. if (!this._canBeRegenerated) {
  40885. return;
  40886. }
  40887. this._beingRegenerated = true;
  40888. this.setAllVerticesData(this._regenerateVertexData(), false);
  40889. this._beingRegenerated = false;
  40890. };
  40891. /**
  40892. * Clone the geometry
  40893. * @param id defines the unique ID of the new geometry
  40894. * @returns the new geometry
  40895. */
  40896. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40897. return _super.prototype.copy.call(this, id);
  40898. };
  40899. // overrides
  40900. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40901. if (!this._beingRegenerated) {
  40902. return;
  40903. }
  40904. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40905. };
  40906. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40907. if (!this._beingRegenerated) {
  40908. return;
  40909. }
  40910. _super.prototype.setVerticesData.call(this, kind, data, false);
  40911. };
  40912. // to override
  40913. /** @hidden */
  40914. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40915. throw new Error("Abstract method");
  40916. };
  40917. _PrimitiveGeometry.prototype.copy = function (id) {
  40918. throw new Error("Must be overriden in sub-classes.");
  40919. };
  40920. _PrimitiveGeometry.prototype.serialize = function () {
  40921. var serializationObject = _super.prototype.serialize.call(this);
  40922. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40923. return serializationObject;
  40924. };
  40925. return _PrimitiveGeometry;
  40926. }(Geometry));
  40927. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40928. /**
  40929. * Creates a ribbon geometry
  40930. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40931. */
  40932. var RibbonGeometry = /** @class */ (function (_super) {
  40933. __extends(RibbonGeometry, _super);
  40934. /**
  40935. * Creates a ribbon geometry
  40936. * @param id defines the unique ID of the geometry
  40937. * @param scene defines the hosting scene
  40938. * @param pathArray defines the array of paths to use
  40939. * @param closeArray defines if the last path and the first path must be joined
  40940. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40941. * @param offset defines the offset between points
  40942. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40943. * @param mesh defines the hosting mesh (can be null)
  40944. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40945. */
  40946. function RibbonGeometry(id, scene,
  40947. /**
  40948. * Defines the array of paths to use
  40949. */
  40950. pathArray,
  40951. /**
  40952. * Defines if the last and first points of each path in your pathArray must be joined
  40953. */
  40954. closeArray,
  40955. /**
  40956. * Defines if the last and first points of each path in your pathArray must be joined
  40957. */
  40958. closePath,
  40959. /**
  40960. * Defines the offset between points
  40961. */
  40962. offset, canBeRegenerated, mesh,
  40963. /**
  40964. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40965. */
  40966. side) {
  40967. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40968. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40969. _this.pathArray = pathArray;
  40970. _this.closeArray = closeArray;
  40971. _this.closePath = closePath;
  40972. _this.offset = offset;
  40973. _this.side = side;
  40974. return _this;
  40975. }
  40976. /** @hidden */
  40977. RibbonGeometry.prototype._regenerateVertexData = function () {
  40978. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40979. };
  40980. RibbonGeometry.prototype.copy = function (id) {
  40981. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40982. };
  40983. return RibbonGeometry;
  40984. }(_PrimitiveGeometry));
  40985. BABYLON.RibbonGeometry = RibbonGeometry;
  40986. /**
  40987. * Creates a box geometry
  40988. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40989. */
  40990. var BoxGeometry = /** @class */ (function (_super) {
  40991. __extends(BoxGeometry, _super);
  40992. /**
  40993. * Creates a box geometry
  40994. * @param id defines the unique ID of the geometry
  40995. * @param scene defines the hosting scene
  40996. * @param size defines the zise of the box (width, height and depth are the same)
  40997. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40998. * @param mesh defines the hosting mesh (can be null)
  40999. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41000. */
  41001. function BoxGeometry(id, scene,
  41002. /**
  41003. * Defines the zise of the box (width, height and depth are the same)
  41004. */
  41005. size, canBeRegenerated, mesh,
  41006. /**
  41007. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41008. */
  41009. side) {
  41010. if (mesh === void 0) { mesh = null; }
  41011. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41012. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41013. _this.size = size;
  41014. _this.side = side;
  41015. return _this;
  41016. }
  41017. /** @hidden */
  41018. BoxGeometry.prototype._regenerateVertexData = function () {
  41019. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  41020. };
  41021. BoxGeometry.prototype.copy = function (id) {
  41022. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  41023. };
  41024. BoxGeometry.prototype.serialize = function () {
  41025. var serializationObject = _super.prototype.serialize.call(this);
  41026. serializationObject.size = this.size;
  41027. return serializationObject;
  41028. };
  41029. BoxGeometry.Parse = function (parsedBox, scene) {
  41030. if (scene.getGeometryByID(parsedBox.id)) {
  41031. return null; // null since geometry could be something else than a box...
  41032. }
  41033. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  41034. if (BABYLON.Tags) {
  41035. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  41036. }
  41037. scene.pushGeometry(box, true);
  41038. return box;
  41039. };
  41040. return BoxGeometry;
  41041. }(_PrimitiveGeometry));
  41042. BABYLON.BoxGeometry = BoxGeometry;
  41043. /**
  41044. * Creates a sphere geometry
  41045. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  41046. */
  41047. var SphereGeometry = /** @class */ (function (_super) {
  41048. __extends(SphereGeometry, _super);
  41049. /**
  41050. * Create a new sphere geometry
  41051. * @param id defines the unique ID of the geometry
  41052. * @param scene defines the hosting scene
  41053. * @param segments defines the number of segments to use to create the sphere
  41054. * @param diameter defines the diameter of the sphere
  41055. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41056. * @param mesh defines the hosting mesh (can be null)
  41057. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41058. */
  41059. function SphereGeometry(id, scene,
  41060. /**
  41061. * Defines the number of segments to use to create the sphere
  41062. */
  41063. segments,
  41064. /**
  41065. * Defines the diameter of the sphere
  41066. */
  41067. diameter, canBeRegenerated, mesh,
  41068. /**
  41069. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41070. */
  41071. side) {
  41072. if (mesh === void 0) { mesh = null; }
  41073. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41074. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41075. _this.segments = segments;
  41076. _this.diameter = diameter;
  41077. _this.side = side;
  41078. return _this;
  41079. }
  41080. /** @hidden */
  41081. SphereGeometry.prototype._regenerateVertexData = function () {
  41082. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  41083. };
  41084. SphereGeometry.prototype.copy = function (id) {
  41085. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  41086. };
  41087. SphereGeometry.prototype.serialize = function () {
  41088. var serializationObject = _super.prototype.serialize.call(this);
  41089. serializationObject.segments = this.segments;
  41090. serializationObject.diameter = this.diameter;
  41091. return serializationObject;
  41092. };
  41093. SphereGeometry.Parse = function (parsedSphere, scene) {
  41094. if (scene.getGeometryByID(parsedSphere.id)) {
  41095. return null; // null since geometry could be something else than a sphere...
  41096. }
  41097. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  41098. if (BABYLON.Tags) {
  41099. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  41100. }
  41101. scene.pushGeometry(sphere, true);
  41102. return sphere;
  41103. };
  41104. return SphereGeometry;
  41105. }(_PrimitiveGeometry));
  41106. BABYLON.SphereGeometry = SphereGeometry;
  41107. /**
  41108. * Creates a disc geometry
  41109. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  41110. */
  41111. var DiscGeometry = /** @class */ (function (_super) {
  41112. __extends(DiscGeometry, _super);
  41113. /**
  41114. * Creates a new disc geometry
  41115. * @param id defines the unique ID of the geometry
  41116. * @param scene defines the hosting scene
  41117. * @param radius defines the radius of the disc
  41118. * @param tessellation defines the tesselation factor to apply to the disc
  41119. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41120. * @param mesh defines the hosting mesh (can be null)
  41121. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41122. */
  41123. function DiscGeometry(id, scene,
  41124. /**
  41125. * Defines the radius of the disc
  41126. */
  41127. radius,
  41128. /**
  41129. * Defines the tesselation factor to apply to the disc
  41130. */
  41131. tessellation, canBeRegenerated, mesh,
  41132. /**
  41133. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41134. */
  41135. side) {
  41136. if (mesh === void 0) { mesh = null; }
  41137. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41138. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41139. _this.radius = radius;
  41140. _this.tessellation = tessellation;
  41141. _this.side = side;
  41142. return _this;
  41143. }
  41144. /** @hidden */
  41145. DiscGeometry.prototype._regenerateVertexData = function () {
  41146. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  41147. };
  41148. DiscGeometry.prototype.copy = function (id) {
  41149. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  41150. };
  41151. return DiscGeometry;
  41152. }(_PrimitiveGeometry));
  41153. BABYLON.DiscGeometry = DiscGeometry;
  41154. /**
  41155. * Creates a new cylinder geometry
  41156. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  41157. */
  41158. var CylinderGeometry = /** @class */ (function (_super) {
  41159. __extends(CylinderGeometry, _super);
  41160. /**
  41161. * Creates a new cylinder geometry
  41162. * @param id defines the unique ID of the geometry
  41163. * @param scene defines the hosting scene
  41164. * @param height defines the height of the cylinder
  41165. * @param diameterTop defines the diameter of the cylinder's top cap
  41166. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  41167. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  41168. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  41169. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41170. * @param mesh defines the hosting mesh (can be null)
  41171. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41172. */
  41173. function CylinderGeometry(id, scene,
  41174. /**
  41175. * Defines the height of the cylinder
  41176. */
  41177. height,
  41178. /**
  41179. * Defines the diameter of the cylinder's top cap
  41180. */
  41181. diameterTop,
  41182. /**
  41183. * Defines the diameter of the cylinder's bottom cap
  41184. */
  41185. diameterBottom,
  41186. /**
  41187. * Defines the tessellation factor to apply to the cylinder
  41188. */
  41189. tessellation,
  41190. /**
  41191. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  41192. */
  41193. subdivisions, canBeRegenerated, mesh,
  41194. /**
  41195. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41196. */
  41197. side) {
  41198. if (subdivisions === void 0) { subdivisions = 1; }
  41199. if (mesh === void 0) { mesh = null; }
  41200. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41201. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41202. _this.height = height;
  41203. _this.diameterTop = diameterTop;
  41204. _this.diameterBottom = diameterBottom;
  41205. _this.tessellation = tessellation;
  41206. _this.subdivisions = subdivisions;
  41207. _this.side = side;
  41208. return _this;
  41209. }
  41210. /** @hidden */
  41211. CylinderGeometry.prototype._regenerateVertexData = function () {
  41212. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  41213. };
  41214. CylinderGeometry.prototype.copy = function (id) {
  41215. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  41216. };
  41217. CylinderGeometry.prototype.serialize = function () {
  41218. var serializationObject = _super.prototype.serialize.call(this);
  41219. serializationObject.height = this.height;
  41220. serializationObject.diameterTop = this.diameterTop;
  41221. serializationObject.diameterBottom = this.diameterBottom;
  41222. serializationObject.tessellation = this.tessellation;
  41223. return serializationObject;
  41224. };
  41225. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  41226. if (scene.getGeometryByID(parsedCylinder.id)) {
  41227. return null; // null since geometry could be something else than a cylinder...
  41228. }
  41229. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  41230. if (BABYLON.Tags) {
  41231. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  41232. }
  41233. scene.pushGeometry(cylinder, true);
  41234. return cylinder;
  41235. };
  41236. return CylinderGeometry;
  41237. }(_PrimitiveGeometry));
  41238. BABYLON.CylinderGeometry = CylinderGeometry;
  41239. /**
  41240. * Creates a new torus geometry
  41241. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  41242. */
  41243. var TorusGeometry = /** @class */ (function (_super) {
  41244. __extends(TorusGeometry, _super);
  41245. /**
  41246. * Creates a new torus geometry
  41247. * @param id defines the unique ID of the geometry
  41248. * @param scene defines the hosting scene
  41249. * @param diameter defines the diameter of the torus
  41250. * @param thickness defines the thickness of the torus (ie. internal diameter)
  41251. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  41252. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41253. * @param mesh defines the hosting mesh (can be null)
  41254. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41255. */
  41256. function TorusGeometry(id, scene,
  41257. /**
  41258. * Defines the diameter of the torus
  41259. */
  41260. diameter,
  41261. /**
  41262. * Defines the thickness of the torus (ie. internal diameter)
  41263. */
  41264. thickness,
  41265. /**
  41266. * Defines the tesselation factor to apply to the torus
  41267. */
  41268. tessellation, canBeRegenerated, mesh,
  41269. /**
  41270. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41271. */
  41272. side) {
  41273. if (mesh === void 0) { mesh = null; }
  41274. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41275. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41276. _this.diameter = diameter;
  41277. _this.thickness = thickness;
  41278. _this.tessellation = tessellation;
  41279. _this.side = side;
  41280. return _this;
  41281. }
  41282. /** @hidden */
  41283. TorusGeometry.prototype._regenerateVertexData = function () {
  41284. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  41285. };
  41286. TorusGeometry.prototype.copy = function (id) {
  41287. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  41288. };
  41289. TorusGeometry.prototype.serialize = function () {
  41290. var serializationObject = _super.prototype.serialize.call(this);
  41291. serializationObject.diameter = this.diameter;
  41292. serializationObject.thickness = this.thickness;
  41293. serializationObject.tessellation = this.tessellation;
  41294. return serializationObject;
  41295. };
  41296. TorusGeometry.Parse = function (parsedTorus, scene) {
  41297. if (scene.getGeometryByID(parsedTorus.id)) {
  41298. return null; // null since geometry could be something else than a torus...
  41299. }
  41300. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  41301. if (BABYLON.Tags) {
  41302. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  41303. }
  41304. scene.pushGeometry(torus, true);
  41305. return torus;
  41306. };
  41307. return TorusGeometry;
  41308. }(_PrimitiveGeometry));
  41309. BABYLON.TorusGeometry = TorusGeometry;
  41310. /**
  41311. * Creates a new ground geometry
  41312. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  41313. */
  41314. var GroundGeometry = /** @class */ (function (_super) {
  41315. __extends(GroundGeometry, _super);
  41316. /**
  41317. * Creates a new ground geometry
  41318. * @param id defines the unique ID of the geometry
  41319. * @param scene defines the hosting scene
  41320. * @param width defines the width of the ground
  41321. * @param height defines the height of the ground
  41322. * @param subdivisions defines the subdivisions to apply to the ground
  41323. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41324. * @param mesh defines the hosting mesh (can be null)
  41325. */
  41326. function GroundGeometry(id, scene,
  41327. /**
  41328. * Defines the width of the ground
  41329. */
  41330. width,
  41331. /**
  41332. * Defines the height of the ground
  41333. */
  41334. height,
  41335. /**
  41336. * Defines the subdivisions to apply to the ground
  41337. */
  41338. subdivisions, canBeRegenerated, mesh) {
  41339. if (mesh === void 0) { mesh = null; }
  41340. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41341. _this.width = width;
  41342. _this.height = height;
  41343. _this.subdivisions = subdivisions;
  41344. return _this;
  41345. }
  41346. /** @hidden */
  41347. GroundGeometry.prototype._regenerateVertexData = function () {
  41348. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  41349. };
  41350. GroundGeometry.prototype.copy = function (id) {
  41351. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  41352. };
  41353. GroundGeometry.prototype.serialize = function () {
  41354. var serializationObject = _super.prototype.serialize.call(this);
  41355. serializationObject.width = this.width;
  41356. serializationObject.height = this.height;
  41357. serializationObject.subdivisions = this.subdivisions;
  41358. return serializationObject;
  41359. };
  41360. GroundGeometry.Parse = function (parsedGround, scene) {
  41361. if (scene.getGeometryByID(parsedGround.id)) {
  41362. return null; // null since geometry could be something else than a ground...
  41363. }
  41364. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  41365. if (BABYLON.Tags) {
  41366. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  41367. }
  41368. scene.pushGeometry(ground, true);
  41369. return ground;
  41370. };
  41371. return GroundGeometry;
  41372. }(_PrimitiveGeometry));
  41373. BABYLON.GroundGeometry = GroundGeometry;
  41374. /**
  41375. * Creates a tiled ground geometry
  41376. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  41377. */
  41378. var TiledGroundGeometry = /** @class */ (function (_super) {
  41379. __extends(TiledGroundGeometry, _super);
  41380. /**
  41381. * Creates a tiled ground geometry
  41382. * @param id defines the unique ID of the geometry
  41383. * @param scene defines the hosting scene
  41384. * @param xmin defines the minimum value on X axis
  41385. * @param zmin defines the minimum value on Z axis
  41386. * @param xmax defines the maximum value on X axis
  41387. * @param zmax defines the maximum value on Z axis
  41388. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  41389. * @param precision defines the precision to use when computing the tiles
  41390. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41391. * @param mesh defines the hosting mesh (can be null)
  41392. */
  41393. function TiledGroundGeometry(id, scene,
  41394. /**
  41395. * Defines the minimum value on X axis
  41396. */
  41397. xmin,
  41398. /**
  41399. * Defines the minimum value on Z axis
  41400. */
  41401. zmin,
  41402. /**
  41403. * Defines the maximum value on X axis
  41404. */
  41405. xmax,
  41406. /**
  41407. * Defines the maximum value on Z axis
  41408. */
  41409. zmax,
  41410. /**
  41411. * Defines the subdivisions to apply to the ground
  41412. */
  41413. subdivisions,
  41414. /**
  41415. * Defines the precision to use when computing the tiles
  41416. */
  41417. precision, canBeRegenerated, mesh) {
  41418. if (mesh === void 0) { mesh = null; }
  41419. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41420. _this.xmin = xmin;
  41421. _this.zmin = zmin;
  41422. _this.xmax = xmax;
  41423. _this.zmax = zmax;
  41424. _this.subdivisions = subdivisions;
  41425. _this.precision = precision;
  41426. return _this;
  41427. }
  41428. /** @hidden */
  41429. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  41430. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  41431. };
  41432. TiledGroundGeometry.prototype.copy = function (id) {
  41433. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  41434. };
  41435. return TiledGroundGeometry;
  41436. }(_PrimitiveGeometry));
  41437. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  41438. /**
  41439. * Creates a plane geometry
  41440. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  41441. */
  41442. var PlaneGeometry = /** @class */ (function (_super) {
  41443. __extends(PlaneGeometry, _super);
  41444. /**
  41445. * Creates a plane geometry
  41446. * @param id defines the unique ID of the geometry
  41447. * @param scene defines the hosting scene
  41448. * @param size defines the size of the plane (width === height)
  41449. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41450. * @param mesh defines the hosting mesh (can be null)
  41451. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41452. */
  41453. function PlaneGeometry(id, scene,
  41454. /**
  41455. * Defines the size of the plane (width === height)
  41456. */
  41457. size, canBeRegenerated, mesh,
  41458. /**
  41459. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41460. */
  41461. side) {
  41462. if (mesh === void 0) { mesh = null; }
  41463. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41464. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41465. _this.size = size;
  41466. _this.side = side;
  41467. return _this;
  41468. }
  41469. /** @hidden */
  41470. PlaneGeometry.prototype._regenerateVertexData = function () {
  41471. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  41472. };
  41473. PlaneGeometry.prototype.copy = function (id) {
  41474. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  41475. };
  41476. PlaneGeometry.prototype.serialize = function () {
  41477. var serializationObject = _super.prototype.serialize.call(this);
  41478. serializationObject.size = this.size;
  41479. return serializationObject;
  41480. };
  41481. PlaneGeometry.Parse = function (parsedPlane, scene) {
  41482. if (scene.getGeometryByID(parsedPlane.id)) {
  41483. return null; // null since geometry could be something else than a ground...
  41484. }
  41485. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  41486. if (BABYLON.Tags) {
  41487. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  41488. }
  41489. scene.pushGeometry(plane, true);
  41490. return plane;
  41491. };
  41492. return PlaneGeometry;
  41493. }(_PrimitiveGeometry));
  41494. BABYLON.PlaneGeometry = PlaneGeometry;
  41495. /**
  41496. * Creates a torus knot geometry
  41497. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  41498. */
  41499. var TorusKnotGeometry = /** @class */ (function (_super) {
  41500. __extends(TorusKnotGeometry, _super);
  41501. /**
  41502. * Creates a torus knot geometry
  41503. * @param id defines the unique ID of the geometry
  41504. * @param scene defines the hosting scene
  41505. * @param radius defines the radius of the torus knot
  41506. * @param tube defines the thickness of the torus knot tube
  41507. * @param radialSegments defines the number of radial segments
  41508. * @param tubularSegments defines the number of tubular segments
  41509. * @param p defines the first number of windings
  41510. * @param q defines the second number of windings
  41511. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41512. * @param mesh defines the hosting mesh (can be null)
  41513. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41514. */
  41515. function TorusKnotGeometry(id, scene,
  41516. /**
  41517. * Defines the radius of the torus knot
  41518. */
  41519. radius,
  41520. /**
  41521. * Defines the thickness of the torus knot tube
  41522. */
  41523. tube,
  41524. /**
  41525. * Defines the number of radial segments
  41526. */
  41527. radialSegments,
  41528. /**
  41529. * Defines the number of tubular segments
  41530. */
  41531. tubularSegments,
  41532. /**
  41533. * Defines the first number of windings
  41534. */
  41535. p,
  41536. /**
  41537. * Defines the second number of windings
  41538. */
  41539. q, canBeRegenerated, mesh,
  41540. /**
  41541. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41542. */
  41543. side) {
  41544. if (mesh === void 0) { mesh = null; }
  41545. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41546. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41547. _this.radius = radius;
  41548. _this.tube = tube;
  41549. _this.radialSegments = radialSegments;
  41550. _this.tubularSegments = tubularSegments;
  41551. _this.p = p;
  41552. _this.q = q;
  41553. _this.side = side;
  41554. return _this;
  41555. }
  41556. /** @hidden */
  41557. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  41558. 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 });
  41559. };
  41560. TorusKnotGeometry.prototype.copy = function (id) {
  41561. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  41562. };
  41563. TorusKnotGeometry.prototype.serialize = function () {
  41564. var serializationObject = _super.prototype.serialize.call(this);
  41565. serializationObject.radius = this.radius;
  41566. serializationObject.tube = this.tube;
  41567. serializationObject.radialSegments = this.radialSegments;
  41568. serializationObject.tubularSegments = this.tubularSegments;
  41569. serializationObject.p = this.p;
  41570. serializationObject.q = this.q;
  41571. return serializationObject;
  41572. };
  41573. ;
  41574. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  41575. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  41576. return null; // null since geometry could be something else than a ground...
  41577. }
  41578. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  41579. if (BABYLON.Tags) {
  41580. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  41581. }
  41582. scene.pushGeometry(torusKnot, true);
  41583. return torusKnot;
  41584. };
  41585. return TorusKnotGeometry;
  41586. }(_PrimitiveGeometry));
  41587. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  41588. //}
  41589. })(BABYLON || (BABYLON = {}));
  41590. //# sourceMappingURL=babylon.geometry.js.map
  41591. var BABYLON;
  41592. (function (BABYLON) {
  41593. /**
  41594. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  41595. */
  41596. var PerformanceMonitor = /** @class */ (function () {
  41597. /**
  41598. * constructor
  41599. * @param frameSampleSize The number of samples required to saturate the sliding window
  41600. */
  41601. function PerformanceMonitor(frameSampleSize) {
  41602. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  41603. this._enabled = true;
  41604. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  41605. }
  41606. /**
  41607. * Samples current frame
  41608. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  41609. */
  41610. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  41611. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  41612. if (!this._enabled)
  41613. return;
  41614. if (this._lastFrameTimeMs != null) {
  41615. var dt = timeMs - this._lastFrameTimeMs;
  41616. this._rollingFrameTime.add(dt);
  41617. }
  41618. this._lastFrameTimeMs = timeMs;
  41619. };
  41620. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  41621. /**
  41622. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41623. */
  41624. get: function () {
  41625. return this._rollingFrameTime.average;
  41626. },
  41627. enumerable: true,
  41628. configurable: true
  41629. });
  41630. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  41631. /**
  41632. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41633. */
  41634. get: function () {
  41635. return this._rollingFrameTime.variance;
  41636. },
  41637. enumerable: true,
  41638. configurable: true
  41639. });
  41640. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  41641. /**
  41642. * Returns the frame time of the most recent frame
  41643. */
  41644. get: function () {
  41645. return this._rollingFrameTime.history(0);
  41646. },
  41647. enumerable: true,
  41648. configurable: true
  41649. });
  41650. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  41651. /**
  41652. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  41653. */
  41654. get: function () {
  41655. return 1000.0 / this._rollingFrameTime.average;
  41656. },
  41657. enumerable: true,
  41658. configurable: true
  41659. });
  41660. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  41661. /**
  41662. * Returns the average framerate in frames per second using the most recent frame time
  41663. */
  41664. get: function () {
  41665. var history = this._rollingFrameTime.history(0);
  41666. if (history === 0) {
  41667. return 0;
  41668. }
  41669. return 1000.0 / history;
  41670. },
  41671. enumerable: true,
  41672. configurable: true
  41673. });
  41674. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  41675. /**
  41676. * Returns true if enough samples have been taken to completely fill the sliding window
  41677. */
  41678. get: function () {
  41679. return this._rollingFrameTime.isSaturated();
  41680. },
  41681. enumerable: true,
  41682. configurable: true
  41683. });
  41684. /**
  41685. * Enables contributions to the sliding window sample set
  41686. */
  41687. PerformanceMonitor.prototype.enable = function () {
  41688. this._enabled = true;
  41689. };
  41690. /**
  41691. * Disables contributions to the sliding window sample set
  41692. * Samples will not be interpolated over the disabled period
  41693. */
  41694. PerformanceMonitor.prototype.disable = function () {
  41695. this._enabled = false;
  41696. //clear last sample to avoid interpolating over the disabled period when next enabled
  41697. this._lastFrameTimeMs = null;
  41698. };
  41699. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41700. /**
  41701. * Returns true if sampling is enabled
  41702. */
  41703. get: function () {
  41704. return this._enabled;
  41705. },
  41706. enumerable: true,
  41707. configurable: true
  41708. });
  41709. /**
  41710. * Resets performance monitor
  41711. */
  41712. PerformanceMonitor.prototype.reset = function () {
  41713. //clear last sample to avoid interpolating over the disabled period when next enabled
  41714. this._lastFrameTimeMs = null;
  41715. //wipe record
  41716. this._rollingFrameTime.reset();
  41717. };
  41718. return PerformanceMonitor;
  41719. }());
  41720. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41721. /**
  41722. * RollingAverage
  41723. *
  41724. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41725. */
  41726. var RollingAverage = /** @class */ (function () {
  41727. /**
  41728. * constructor
  41729. * @param length The number of samples required to saturate the sliding window
  41730. */
  41731. function RollingAverage(length) {
  41732. this._samples = new Array(length);
  41733. this.reset();
  41734. }
  41735. /**
  41736. * Adds a sample to the sample set
  41737. * @param v The sample value
  41738. */
  41739. RollingAverage.prototype.add = function (v) {
  41740. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41741. var delta;
  41742. //we need to check if we've already wrapped round
  41743. if (this.isSaturated()) {
  41744. //remove bottom of stack from mean
  41745. var bottomValue = this._samples[this._pos];
  41746. delta = bottomValue - this.average;
  41747. this.average -= delta / (this._sampleCount - 1);
  41748. this._m2 -= delta * (bottomValue - this.average);
  41749. }
  41750. else {
  41751. this._sampleCount++;
  41752. }
  41753. //add new value to mean
  41754. delta = v - this.average;
  41755. this.average += delta / (this._sampleCount);
  41756. this._m2 += delta * (v - this.average);
  41757. //set the new variance
  41758. this.variance = this._m2 / (this._sampleCount - 1);
  41759. this._samples[this._pos] = v;
  41760. this._pos++;
  41761. this._pos %= this._samples.length; //positive wrap around
  41762. };
  41763. /**
  41764. * Returns previously added values or null if outside of history or outside the sliding window domain
  41765. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41766. * @return Value previously recorded with add() or null if outside of range
  41767. */
  41768. RollingAverage.prototype.history = function (i) {
  41769. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41770. return 0;
  41771. }
  41772. var i0 = this._wrapPosition(this._pos - 1.0);
  41773. return this._samples[this._wrapPosition(i0 - i)];
  41774. };
  41775. /**
  41776. * Returns true if enough samples have been taken to completely fill the sliding window
  41777. * @return true if sample-set saturated
  41778. */
  41779. RollingAverage.prototype.isSaturated = function () {
  41780. return this._sampleCount >= this._samples.length;
  41781. };
  41782. /**
  41783. * Resets the rolling average (equivalent to 0 samples taken so far)
  41784. */
  41785. RollingAverage.prototype.reset = function () {
  41786. this.average = 0;
  41787. this.variance = 0;
  41788. this._sampleCount = 0;
  41789. this._pos = 0;
  41790. this._m2 = 0;
  41791. };
  41792. /**
  41793. * Wraps a value around the sample range boundaries
  41794. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41795. * @return Wrapped position in sample range
  41796. */
  41797. RollingAverage.prototype._wrapPosition = function (i) {
  41798. var max = this._samples.length;
  41799. return ((i % max) + max) % max;
  41800. };
  41801. return RollingAverage;
  41802. }());
  41803. BABYLON.RollingAverage = RollingAverage;
  41804. })(BABYLON || (BABYLON = {}));
  41805. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41806. var BABYLON;
  41807. (function (BABYLON) {
  41808. /**
  41809. * "Static Class" containing the most commonly used helper while dealing with material for
  41810. * rendering purpose.
  41811. *
  41812. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41813. *
  41814. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41815. */
  41816. var MaterialHelper = /** @class */ (function () {
  41817. function MaterialHelper() {
  41818. }
  41819. /**
  41820. * Bind the current view position to an effect.
  41821. * @param effect The effect to be bound
  41822. * @param scene The scene the eyes position is used from
  41823. */
  41824. MaterialHelper.BindEyePosition = function (effect, scene) {
  41825. if (scene._forcedViewPosition) {
  41826. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41827. return;
  41828. }
  41829. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41830. };
  41831. /**
  41832. * Helps preparing the defines values about the UVs in used in the effect.
  41833. * UVs are shared as much as we can accross channels in the shaders.
  41834. * @param texture The texture we are preparing the UVs for
  41835. * @param defines The defines to update
  41836. * @param key The channel key "diffuse", "specular"... used in the shader
  41837. */
  41838. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41839. defines._needUVs = true;
  41840. defines[key] = true;
  41841. if (texture.getTextureMatrix().isIdentity(true)) {
  41842. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41843. if (texture.coordinatesIndex === 0) {
  41844. defines["MAINUV1"] = true;
  41845. }
  41846. else {
  41847. defines["MAINUV2"] = true;
  41848. }
  41849. }
  41850. else {
  41851. defines[key + "DIRECTUV"] = 0;
  41852. }
  41853. };
  41854. /**
  41855. * Binds a texture matrix value to its corrsponding uniform
  41856. * @param texture The texture to bind the matrix for
  41857. * @param uniformBuffer The uniform buffer receivin the data
  41858. * @param key The channel key "diffuse", "specular"... used in the shader
  41859. */
  41860. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41861. var matrix = texture.getTextureMatrix();
  41862. if (!matrix.isIdentity(true)) {
  41863. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41864. }
  41865. };
  41866. /**
  41867. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41868. * @param mesh defines the current mesh
  41869. * @param scene defines the current scene
  41870. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41871. * @param pointsCloud defines if point cloud rendering has to be turned on
  41872. * @param fogEnabled defines if fog has to be turned on
  41873. * @param alphaTest defines if alpha testing has to be turned on
  41874. * @param defines defines the current list of defines
  41875. */
  41876. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41877. if (defines._areMiscDirty) {
  41878. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41879. defines["POINTSIZE"] = pointsCloud;
  41880. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41881. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41882. defines["ALPHATEST"] = alphaTest;
  41883. }
  41884. };
  41885. /**
  41886. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41887. * @param scene defines the current scene
  41888. * @param engine defines the current engine
  41889. * @param defines specifies the list of active defines
  41890. * @param useInstances defines if instances have to be turned on
  41891. * @param useClipPlane defines if clip plane have to be turned on
  41892. */
  41893. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41894. if (useClipPlane === void 0) { useClipPlane = null; }
  41895. var changed = false;
  41896. var useClipPlane1 = false;
  41897. var useClipPlane2 = false;
  41898. var useClipPlane3 = false;
  41899. var useClipPlane4 = false;
  41900. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  41901. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  41902. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  41903. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  41904. if (defines["CLIPPLANE"] !== useClipPlane1) {
  41905. defines["CLIPPLANE"] = useClipPlane1;
  41906. changed = true;
  41907. }
  41908. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  41909. defines["CLIPPLANE2"] = useClipPlane2;
  41910. changed = true;
  41911. }
  41912. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  41913. defines["CLIPPLANE3"] = useClipPlane3;
  41914. changed = true;
  41915. }
  41916. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  41917. defines["CLIPPLANE4"] = useClipPlane4;
  41918. changed = true;
  41919. }
  41920. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41921. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41922. changed = true;
  41923. }
  41924. if (defines["INSTANCES"] !== useInstances) {
  41925. defines["INSTANCES"] = useInstances;
  41926. changed = true;
  41927. }
  41928. if (changed) {
  41929. defines.markAsUnprocessed();
  41930. }
  41931. };
  41932. /**
  41933. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41934. * @param mesh The mesh containing the geometry data we will draw
  41935. * @param defines The defines to update
  41936. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41937. * @param useBones Precise whether bones should be used or not (override mesh info)
  41938. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41939. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41940. * @returns false if defines are considered not dirty and have not been checked
  41941. */
  41942. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41943. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41944. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41945. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41946. return false;
  41947. }
  41948. defines._normals = defines._needNormals;
  41949. defines._uvs = defines._needUVs;
  41950. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41951. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41952. defines["TANGENT"] = true;
  41953. }
  41954. if (defines._needUVs) {
  41955. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41956. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41957. }
  41958. else {
  41959. defines["UV1"] = false;
  41960. defines["UV2"] = false;
  41961. }
  41962. if (useVertexColor) {
  41963. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41964. defines["VERTEXCOLOR"] = hasVertexColors;
  41965. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41966. }
  41967. if (useBones) {
  41968. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41969. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41970. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41971. }
  41972. else {
  41973. defines["NUM_BONE_INFLUENCERS"] = 0;
  41974. defines["BonesPerMesh"] = 0;
  41975. }
  41976. }
  41977. if (useMorphTargets) {
  41978. var manager = mesh.morphTargetManager;
  41979. if (manager) {
  41980. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41981. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41982. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41983. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41984. }
  41985. else {
  41986. defines["MORPHTARGETS_TANGENT"] = false;
  41987. defines["MORPHTARGETS_NORMAL"] = false;
  41988. defines["MORPHTARGETS"] = false;
  41989. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41990. }
  41991. }
  41992. return true;
  41993. };
  41994. /**
  41995. * Prepares the defines related to the light information passed in parameter
  41996. * @param scene The scene we are intending to draw
  41997. * @param mesh The mesh the effect is compiling for
  41998. * @param defines The defines to update
  41999. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42000. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42001. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42002. * @returns true if normals will be required for the rest of the effect
  42003. */
  42004. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42005. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42006. if (disableLighting === void 0) { disableLighting = false; }
  42007. if (!defines._areLightsDirty) {
  42008. return defines._needNormals;
  42009. }
  42010. var lightIndex = 0;
  42011. var needNormals = false;
  42012. var needRebuild = false;
  42013. var lightmapMode = false;
  42014. var shadowEnabled = false;
  42015. var specularEnabled = false;
  42016. if (scene.lightsEnabled && !disableLighting) {
  42017. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42018. var light = _a[_i];
  42019. needNormals = true;
  42020. if (defines["LIGHT" + lightIndex] === undefined) {
  42021. needRebuild = true;
  42022. }
  42023. defines["LIGHT" + lightIndex] = true;
  42024. defines["SPOTLIGHT" + lightIndex] = false;
  42025. defines["HEMILIGHT" + lightIndex] = false;
  42026. defines["POINTLIGHT" + lightIndex] = false;
  42027. defines["DIRLIGHT" + lightIndex] = false;
  42028. light.prepareLightSpecificDefines(defines, lightIndex);
  42029. // FallOff.
  42030. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  42031. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  42032. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  42033. switch (light.falloffType) {
  42034. case BABYLON.Light.FALLOFF_GLTF:
  42035. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  42036. break;
  42037. case BABYLON.Light.FALLOFF_PHYSICAL:
  42038. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  42039. break;
  42040. case BABYLON.Light.FALLOFF_STANDARD:
  42041. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  42042. break;
  42043. }
  42044. // Specular
  42045. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42046. specularEnabled = true;
  42047. }
  42048. // Shadows
  42049. defines["SHADOW" + lightIndex] = false;
  42050. defines["SHADOWPCF" + lightIndex] = false;
  42051. defines["SHADOWPCSS" + lightIndex] = false;
  42052. defines["SHADOWPOISSON" + lightIndex] = false;
  42053. defines["SHADOWESM" + lightIndex] = false;
  42054. defines["SHADOWCUBE" + lightIndex] = false;
  42055. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42056. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42057. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42058. var shadowGenerator = light.getShadowGenerator();
  42059. if (shadowGenerator) {
  42060. var shadowMap = shadowGenerator.getShadowMap();
  42061. if (shadowMap) {
  42062. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  42063. shadowEnabled = true;
  42064. shadowGenerator.prepareDefines(defines, lightIndex);
  42065. }
  42066. }
  42067. }
  42068. }
  42069. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42070. lightmapMode = true;
  42071. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42072. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42073. }
  42074. else {
  42075. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42076. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42077. }
  42078. lightIndex++;
  42079. if (lightIndex === maxSimultaneousLights)
  42080. break;
  42081. }
  42082. }
  42083. defines["SPECULARTERM"] = specularEnabled;
  42084. defines["SHADOWS"] = shadowEnabled;
  42085. // Resetting all other lights if any
  42086. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42087. if (defines["LIGHT" + index] !== undefined) {
  42088. defines["LIGHT" + index] = false;
  42089. defines["HEMILIGHT" + lightIndex] = false;
  42090. defines["POINTLIGHT" + lightIndex] = false;
  42091. defines["DIRLIGHT" + lightIndex] = false;
  42092. defines["SPOTLIGHT" + lightIndex] = false;
  42093. defines["SHADOW" + lightIndex] = false;
  42094. }
  42095. }
  42096. var caps = scene.getEngine().getCaps();
  42097. if (defines["SHADOWFLOAT"] === undefined) {
  42098. needRebuild = true;
  42099. }
  42100. defines["SHADOWFLOAT"] = shadowEnabled &&
  42101. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42102. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42103. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42104. if (needRebuild) {
  42105. defines.rebuild();
  42106. }
  42107. return needNormals;
  42108. };
  42109. /**
  42110. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42111. * that won t be acctive due to defines being turned off.
  42112. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42113. * @param samplersList The samplers list
  42114. * @param defines The defines helping in the list generation
  42115. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42116. */
  42117. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42118. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42119. var uniformsList;
  42120. var uniformBuffersList = null;
  42121. if (uniformsListOrOptions.uniformsNames) {
  42122. var options = uniformsListOrOptions;
  42123. uniformsList = options.uniformsNames;
  42124. uniformBuffersList = options.uniformBuffersNames;
  42125. samplersList = options.samplers;
  42126. defines = options.defines;
  42127. maxSimultaneousLights = options.maxSimultaneousLights;
  42128. }
  42129. else {
  42130. uniformsList = uniformsListOrOptions;
  42131. if (!samplersList) {
  42132. samplersList = [];
  42133. }
  42134. }
  42135. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42136. if (!defines["LIGHT" + lightIndex]) {
  42137. break;
  42138. }
  42139. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42140. if (uniformBuffersList) {
  42141. uniformBuffersList.push("Light" + lightIndex);
  42142. }
  42143. samplersList.push("shadowSampler" + lightIndex);
  42144. samplersList.push("depthSampler" + lightIndex);
  42145. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42146. samplersList.push("projectionLightSampler" + lightIndex);
  42147. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42148. }
  42149. }
  42150. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42151. uniformsList.push("morphTargetInfluences");
  42152. }
  42153. };
  42154. /**
  42155. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42156. * @param defines The defines to update while falling back
  42157. * @param fallbacks The authorized effect fallbacks
  42158. * @param maxSimultaneousLights The maximum number of lights allowed
  42159. * @param rank the current rank of the Effect
  42160. * @returns The newly affected rank
  42161. */
  42162. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42163. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42164. if (rank === void 0) { rank = 0; }
  42165. var lightFallbackRank = 0;
  42166. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42167. if (!defines["LIGHT" + lightIndex]) {
  42168. break;
  42169. }
  42170. if (lightIndex > 0) {
  42171. lightFallbackRank = rank + lightIndex;
  42172. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42173. }
  42174. if (!defines["SHADOWS"]) {
  42175. if (defines["SHADOW" + lightIndex]) {
  42176. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42177. }
  42178. if (defines["SHADOWPCF" + lightIndex]) {
  42179. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42180. }
  42181. if (defines["SHADOWPCSS" + lightIndex]) {
  42182. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42183. }
  42184. if (defines["SHADOWPOISSON" + lightIndex]) {
  42185. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42186. }
  42187. if (defines["SHADOWESM" + lightIndex]) {
  42188. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42189. }
  42190. }
  42191. }
  42192. return lightFallbackRank++;
  42193. };
  42194. /**
  42195. * Prepares the list of attributes required for morph targets according to the effect defines.
  42196. * @param attribs The current list of supported attribs
  42197. * @param mesh The mesh to prepare the morph targets attributes for
  42198. * @param defines The current Defines of the effect
  42199. */
  42200. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42201. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42202. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42203. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42204. var manager = mesh.morphTargetManager;
  42205. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42206. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42207. for (var index = 0; index < influencers; index++) {
  42208. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42209. if (normal) {
  42210. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42211. }
  42212. if (tangent) {
  42213. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42214. }
  42215. if (attribs.length > maxAttributesCount) {
  42216. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42217. }
  42218. }
  42219. }
  42220. };
  42221. /**
  42222. * Prepares the list of attributes required for bones according to the effect defines.
  42223. * @param attribs The current list of supported attribs
  42224. * @param mesh The mesh to prepare the bones attributes for
  42225. * @param defines The current Defines of the effect
  42226. * @param fallbacks The current efffect fallback strategy
  42227. */
  42228. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42229. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42230. fallbacks.addCPUSkinningFallback(0, mesh);
  42231. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42232. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42233. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42234. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42235. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42236. }
  42237. }
  42238. };
  42239. /**
  42240. * Prepares the list of attributes required for instances according to the effect defines.
  42241. * @param attribs The current list of supported attribs
  42242. * @param defines The current Defines of the effect
  42243. */
  42244. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42245. if (defines["INSTANCES"]) {
  42246. attribs.push("world0");
  42247. attribs.push("world1");
  42248. attribs.push("world2");
  42249. attribs.push("world3");
  42250. }
  42251. };
  42252. /**
  42253. * Binds the light shadow information to the effect for the given mesh.
  42254. * @param light The light containing the generator
  42255. * @param scene The scene the lights belongs to
  42256. * @param mesh The mesh we are binding the information to render
  42257. * @param lightIndex The light index in the effect used to render the mesh
  42258. * @param effect The effect we are binding the data to
  42259. */
  42260. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42261. if (light.shadowEnabled && mesh.receiveShadows) {
  42262. var shadowGenerator = light.getShadowGenerator();
  42263. if (shadowGenerator) {
  42264. shadowGenerator.bindShadowLight(lightIndex, effect);
  42265. }
  42266. }
  42267. };
  42268. /**
  42269. * Binds the light information to the effect.
  42270. * @param light The light containing the generator
  42271. * @param effect The effect we are binding the data to
  42272. * @param lightIndex The light index in the effect used to render
  42273. */
  42274. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42275. light.transferToEffect(effect, lightIndex + "");
  42276. };
  42277. /**
  42278. * Binds the lights information from the scene to the effect for the given mesh.
  42279. * @param scene The scene the lights belongs to
  42280. * @param mesh The mesh we are binding the information to render
  42281. * @param effect The effect we are binding the data to
  42282. * @param defines The generated defines for the effect
  42283. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42284. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42285. */
  42286. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42287. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42288. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42289. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42290. for (var i = 0; i < len; i++) {
  42291. var light = mesh._lightSources[i];
  42292. var iAsString = i.toString();
  42293. var scaledIntensity = light.getScaledIntensity();
  42294. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42295. MaterialHelper.BindLightProperties(light, effect, i);
  42296. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42297. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42298. if (defines["SPECULARTERM"]) {
  42299. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42300. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42301. }
  42302. // Shadows
  42303. if (scene.shadowsEnabled) {
  42304. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42305. }
  42306. light._uniformBuffer.update();
  42307. }
  42308. };
  42309. /**
  42310. * Binds the fog information from the scene to the effect for the given mesh.
  42311. * @param scene The scene the lights belongs to
  42312. * @param mesh The mesh we are binding the information to render
  42313. * @param effect The effect we are binding the data to
  42314. * @param linearSpace Defines if the fog effect is applied in linear space
  42315. */
  42316. MaterialHelper.BindFogParameters = function (scene, mesh, effect, linearSpace) {
  42317. if (linearSpace === void 0) { linearSpace = false; }
  42318. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42319. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42320. // Convert fog color to linear space if used in a linear space computed shader.
  42321. if (linearSpace) {
  42322. scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
  42323. effect.setColor3("vFogColor", this._tempFogColor);
  42324. }
  42325. else {
  42326. effect.setColor3("vFogColor", scene.fogColor);
  42327. }
  42328. }
  42329. };
  42330. /**
  42331. * Binds the bones information from the mesh to the effect.
  42332. * @param mesh The mesh we are binding the information to render
  42333. * @param effect The effect we are binding the data to
  42334. */
  42335. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42336. if (!effect || !mesh) {
  42337. return;
  42338. }
  42339. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  42340. mesh.computeBonesUsingShaders = false;
  42341. }
  42342. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42343. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42344. if (matrices) {
  42345. effect.setMatrices("mBones", matrices);
  42346. }
  42347. }
  42348. };
  42349. /**
  42350. * Binds the morph targets information from the mesh to the effect.
  42351. * @param abstractMesh The mesh we are binding the information to render
  42352. * @param effect The effect we are binding the data to
  42353. */
  42354. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42355. var manager = abstractMesh.morphTargetManager;
  42356. if (!abstractMesh || !manager) {
  42357. return;
  42358. }
  42359. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42360. };
  42361. /**
  42362. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42363. * @param defines The generated defines used in the effect
  42364. * @param effect The effect we are binding the data to
  42365. * @param scene The scene we are willing to render with logarithmic scale for
  42366. */
  42367. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42368. if (defines["LOGARITHMICDEPTH"]) {
  42369. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42370. }
  42371. };
  42372. /**
  42373. * Binds the clip plane information from the scene to the effect.
  42374. * @param scene The scene the clip plane information are extracted from
  42375. * @param effect The effect we are binding the data to
  42376. */
  42377. MaterialHelper.BindClipPlane = function (effect, scene) {
  42378. if (scene.clipPlane) {
  42379. var clipPlane = scene.clipPlane;
  42380. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42381. }
  42382. if (scene.clipPlane2) {
  42383. var clipPlane = scene.clipPlane2;
  42384. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42385. }
  42386. if (scene.clipPlane3) {
  42387. var clipPlane = scene.clipPlane3;
  42388. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42389. }
  42390. if (scene.clipPlane4) {
  42391. var clipPlane = scene.clipPlane4;
  42392. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42393. }
  42394. };
  42395. MaterialHelper._tempFogColor = BABYLON.Color3.Black();
  42396. return MaterialHelper;
  42397. }());
  42398. BABYLON.MaterialHelper = MaterialHelper;
  42399. })(BABYLON || (BABYLON = {}));
  42400. //# sourceMappingURL=babylon.materialHelper.js.map
  42401. var BABYLON;
  42402. (function (BABYLON) {
  42403. /**
  42404. * Base class of materials working in push mode in babylon JS
  42405. * @hidden
  42406. */
  42407. var PushMaterial = /** @class */ (function (_super) {
  42408. __extends(PushMaterial, _super);
  42409. function PushMaterial(name, scene) {
  42410. var _this = _super.call(this, name, scene) || this;
  42411. _this._normalMatrix = new BABYLON.Matrix();
  42412. _this.storeEffectOnSubMeshes = true;
  42413. return _this;
  42414. }
  42415. PushMaterial.prototype.getEffect = function () {
  42416. return this._activeEffect;
  42417. };
  42418. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42419. if (!mesh) {
  42420. return false;
  42421. }
  42422. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42423. return true;
  42424. }
  42425. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42426. };
  42427. /**
  42428. * Binds the given world matrix to the active effect
  42429. *
  42430. * @param world the matrix to bind
  42431. */
  42432. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42433. this._activeEffect.setMatrix("world", world);
  42434. };
  42435. /**
  42436. * Binds the given normal matrix to the active effect
  42437. *
  42438. * @param normalMatrix the matrix to bind
  42439. */
  42440. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42441. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42442. };
  42443. PushMaterial.prototype.bind = function (world, mesh) {
  42444. if (!mesh) {
  42445. return;
  42446. }
  42447. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42448. };
  42449. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42450. if (effect === void 0) { effect = null; }
  42451. _super.prototype._afterBind.call(this, mesh);
  42452. this.getScene()._cachedEffect = effect;
  42453. };
  42454. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42455. if (visibility === void 0) { visibility = 1; }
  42456. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42457. };
  42458. return PushMaterial;
  42459. }(BABYLON.Material));
  42460. BABYLON.PushMaterial = PushMaterial;
  42461. })(BABYLON || (BABYLON = {}));
  42462. //# sourceMappingURL=babylon.pushMaterial.js.map
  42463. var BABYLON;
  42464. (function (BABYLON) {
  42465. /** @hidden */
  42466. var StandardMaterialDefines = /** @class */ (function (_super) {
  42467. __extends(StandardMaterialDefines, _super);
  42468. function StandardMaterialDefines() {
  42469. var _this = _super.call(this) || this;
  42470. _this.MAINUV1 = false;
  42471. _this.MAINUV2 = false;
  42472. _this.DIFFUSE = false;
  42473. _this.DIFFUSEDIRECTUV = 0;
  42474. _this.AMBIENT = false;
  42475. _this.AMBIENTDIRECTUV = 0;
  42476. _this.OPACITY = false;
  42477. _this.OPACITYDIRECTUV = 0;
  42478. _this.OPACITYRGB = false;
  42479. _this.REFLECTION = false;
  42480. _this.EMISSIVE = false;
  42481. _this.EMISSIVEDIRECTUV = 0;
  42482. _this.SPECULAR = false;
  42483. _this.SPECULARDIRECTUV = 0;
  42484. _this.BUMP = false;
  42485. _this.BUMPDIRECTUV = 0;
  42486. _this.PARALLAX = false;
  42487. _this.PARALLAXOCCLUSION = false;
  42488. _this.SPECULAROVERALPHA = false;
  42489. _this.CLIPPLANE = false;
  42490. _this.CLIPPLANE2 = false;
  42491. _this.CLIPPLANE3 = false;
  42492. _this.CLIPPLANE4 = false;
  42493. _this.ALPHATEST = false;
  42494. _this.DEPTHPREPASS = false;
  42495. _this.ALPHAFROMDIFFUSE = false;
  42496. _this.POINTSIZE = false;
  42497. _this.FOG = false;
  42498. _this.SPECULARTERM = false;
  42499. _this.DIFFUSEFRESNEL = false;
  42500. _this.OPACITYFRESNEL = false;
  42501. _this.REFLECTIONFRESNEL = false;
  42502. _this.REFRACTIONFRESNEL = false;
  42503. _this.EMISSIVEFRESNEL = false;
  42504. _this.FRESNEL = false;
  42505. _this.NORMAL = false;
  42506. _this.UV1 = false;
  42507. _this.UV2 = false;
  42508. _this.VERTEXCOLOR = false;
  42509. _this.VERTEXALPHA = false;
  42510. _this.NUM_BONE_INFLUENCERS = 0;
  42511. _this.BonesPerMesh = 0;
  42512. _this.INSTANCES = false;
  42513. _this.GLOSSINESS = false;
  42514. _this.ROUGHNESS = false;
  42515. _this.EMISSIVEASILLUMINATION = false;
  42516. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42517. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42518. _this.LIGHTMAP = false;
  42519. _this.LIGHTMAPDIRECTUV = 0;
  42520. _this.OBJECTSPACE_NORMALMAP = false;
  42521. _this.USELIGHTMAPASSHADOWMAP = false;
  42522. _this.REFLECTIONMAP_3D = false;
  42523. _this.REFLECTIONMAP_SPHERICAL = false;
  42524. _this.REFLECTIONMAP_PLANAR = false;
  42525. _this.REFLECTIONMAP_CUBIC = false;
  42526. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42527. _this.REFLECTIONMAP_PROJECTION = false;
  42528. _this.REFLECTIONMAP_SKYBOX = false;
  42529. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  42530. _this.REFLECTIONMAP_EXPLICIT = false;
  42531. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42532. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42533. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42534. _this.INVERTCUBICMAP = false;
  42535. _this.LOGARITHMICDEPTH = false;
  42536. _this.REFRACTION = false;
  42537. _this.REFRACTIONMAP_3D = false;
  42538. _this.REFLECTIONOVERALPHA = false;
  42539. _this.TWOSIDEDLIGHTING = false;
  42540. _this.SHADOWFLOAT = false;
  42541. _this.MORPHTARGETS = false;
  42542. _this.MORPHTARGETS_NORMAL = false;
  42543. _this.MORPHTARGETS_TANGENT = false;
  42544. _this.NUM_MORPH_INFLUENCERS = 0;
  42545. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42546. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42547. _this.IMAGEPROCESSING = false;
  42548. _this.VIGNETTE = false;
  42549. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42550. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42551. _this.TONEMAPPING = false;
  42552. _this.TONEMAPPING_ACES = false;
  42553. _this.CONTRAST = false;
  42554. _this.COLORCURVES = false;
  42555. _this.COLORGRADING = false;
  42556. _this.COLORGRADING3D = false;
  42557. _this.SAMPLER3DGREENDEPTH = false;
  42558. _this.SAMPLER3DBGRMAP = false;
  42559. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42560. /**
  42561. * If the reflection texture on this material is in linear color space
  42562. * @hidden
  42563. */
  42564. _this.IS_REFLECTION_LINEAR = false;
  42565. /**
  42566. * If the refraction texture on this material is in linear color space
  42567. * @hidden
  42568. */
  42569. _this.IS_REFRACTION_LINEAR = false;
  42570. _this.EXPOSURE = false;
  42571. _this.rebuild();
  42572. return _this;
  42573. }
  42574. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42575. var modes = [
  42576. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42577. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42578. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42579. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42580. ];
  42581. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42582. var mode = modes_1[_i];
  42583. this[mode] = (mode === modeToEnable);
  42584. }
  42585. };
  42586. return StandardMaterialDefines;
  42587. }(BABYLON.MaterialDefines));
  42588. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42589. /**
  42590. * This is the default material used in Babylon. It is the best trade off between quality
  42591. * and performances.
  42592. * @see http://doc.babylonjs.com/babylon101/materials
  42593. */
  42594. var StandardMaterial = /** @class */ (function (_super) {
  42595. __extends(StandardMaterial, _super);
  42596. /**
  42597. * Instantiates a new standard material.
  42598. * This is the default material used in Babylon. It is the best trade off between quality
  42599. * and performances.
  42600. * @see http://doc.babylonjs.com/babylon101/materials
  42601. * @param name Define the name of the material in the scene
  42602. * @param scene Define the scene the material belong to
  42603. */
  42604. function StandardMaterial(name, scene) {
  42605. var _this = _super.call(this, name, scene) || this;
  42606. /**
  42607. * The color of the material lit by the environmental background lighting.
  42608. * @see http://doc.babylonjs.com/babylon101/materials#ambient-color-example
  42609. */
  42610. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42611. /**
  42612. * The basic color of the material as viewed under a light.
  42613. */
  42614. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42615. /**
  42616. * Define how the color and intensity of the highlight given by the light in the material.
  42617. */
  42618. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42619. /**
  42620. * Define the color of the material as if self lit.
  42621. * This will be mixed in the final result even in the absence of light.
  42622. */
  42623. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42624. /**
  42625. * Defines how sharp are the highlights in the material.
  42626. * The bigger the value the sharper giving a more glossy feeling to the result.
  42627. * Reversely, the smaller the value the blurrier giving a more rough feeling to the result.
  42628. */
  42629. _this.specularPower = 64;
  42630. _this._useAlphaFromDiffuseTexture = false;
  42631. _this._useEmissiveAsIllumination = false;
  42632. _this._linkEmissiveWithDiffuse = false;
  42633. _this._useSpecularOverAlpha = false;
  42634. _this._useReflectionOverAlpha = false;
  42635. _this._disableLighting = false;
  42636. _this._useObjectSpaceNormalMap = false;
  42637. _this._useParallax = false;
  42638. _this._useParallaxOcclusion = false;
  42639. /**
  42640. * Apply a scaling factor that determine which "depth" the height map should reprensent. A value between 0.05 and 0.1 is reasonnable in Parallax, you can reach 0.2 using Parallax Occlusion.
  42641. */
  42642. _this.parallaxScaleBias = 0.05;
  42643. _this._roughness = 0;
  42644. /**
  42645. * In case of refraction, define the value of the indice of refraction.
  42646. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  42647. */
  42648. _this.indexOfRefraction = 0.98;
  42649. /**
  42650. * Invert the refraction texture alongside the y axis.
  42651. * It can be usefull with procedural textures or probe for instance.
  42652. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  42653. */
  42654. _this.invertRefractionY = true;
  42655. /**
  42656. * Defines the alpha limits in alpha test mode.
  42657. */
  42658. _this.alphaCutOff = 0.4;
  42659. _this._useLightmapAsShadowmap = false;
  42660. _this._useReflectionFresnelFromSpecular = false;
  42661. _this._useGlossinessFromSpecularMapAlpha = false;
  42662. _this._maxSimultaneousLights = 4;
  42663. _this._invertNormalMapX = false;
  42664. _this._invertNormalMapY = false;
  42665. _this._twoSidedLighting = false;
  42666. _this._renderTargets = new BABYLON.SmartArray(16);
  42667. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42668. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42669. // Setup the default processing configuration to the scene.
  42670. _this._attachImageProcessingConfiguration(null);
  42671. _this.getRenderTargetTextures = function () {
  42672. _this._renderTargets.reset();
  42673. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42674. _this._renderTargets.push(_this._reflectionTexture);
  42675. }
  42676. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42677. _this._renderTargets.push(_this._refractionTexture);
  42678. }
  42679. return _this._renderTargets;
  42680. };
  42681. return _this;
  42682. }
  42683. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42684. /**
  42685. * Gets the image processing configuration used either in this material.
  42686. */
  42687. get: function () {
  42688. return this._imageProcessingConfiguration;
  42689. },
  42690. /**
  42691. * Sets the Default image processing configuration used either in the this material.
  42692. *
  42693. * If sets to null, the scene one is in use.
  42694. */
  42695. set: function (value) {
  42696. this._attachImageProcessingConfiguration(value);
  42697. // Ensure the effect will be rebuilt.
  42698. this._markAllSubMeshesAsTexturesDirty();
  42699. },
  42700. enumerable: true,
  42701. configurable: true
  42702. });
  42703. /**
  42704. * Attaches a new image processing configuration to the Standard Material.
  42705. * @param configuration
  42706. */
  42707. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42708. var _this = this;
  42709. if (configuration === this._imageProcessingConfiguration) {
  42710. return;
  42711. }
  42712. // Detaches observer.
  42713. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42714. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42715. }
  42716. // Pick the scene configuration if needed.
  42717. if (!configuration) {
  42718. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42719. }
  42720. else {
  42721. this._imageProcessingConfiguration = configuration;
  42722. }
  42723. // Attaches observer.
  42724. if (this._imageProcessingConfiguration) {
  42725. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42726. _this._markAllSubMeshesAsImageProcessingDirty();
  42727. });
  42728. }
  42729. };
  42730. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42731. /**
  42732. * Gets wether the color curves effect is enabled.
  42733. */
  42734. get: function () {
  42735. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42736. },
  42737. /**
  42738. * Sets wether the color curves effect is enabled.
  42739. */
  42740. set: function (value) {
  42741. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42742. },
  42743. enumerable: true,
  42744. configurable: true
  42745. });
  42746. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42747. /**
  42748. * Gets wether the color grading effect is enabled.
  42749. */
  42750. get: function () {
  42751. return this.imageProcessingConfiguration.colorGradingEnabled;
  42752. },
  42753. /**
  42754. * Gets wether the color grading effect is enabled.
  42755. */
  42756. set: function (value) {
  42757. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42758. },
  42759. enumerable: true,
  42760. configurable: true
  42761. });
  42762. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42763. /**
  42764. * Gets wether tonemapping is enabled or not.
  42765. */
  42766. get: function () {
  42767. return this._imageProcessingConfiguration.toneMappingEnabled;
  42768. },
  42769. /**
  42770. * Sets wether tonemapping is enabled or not
  42771. */
  42772. set: function (value) {
  42773. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42774. },
  42775. enumerable: true,
  42776. configurable: true
  42777. });
  42778. ;
  42779. ;
  42780. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42781. /**
  42782. * The camera exposure used on this material.
  42783. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42784. * This corresponds to a photographic exposure.
  42785. */
  42786. get: function () {
  42787. return this._imageProcessingConfiguration.exposure;
  42788. },
  42789. /**
  42790. * The camera exposure used on this material.
  42791. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42792. * This corresponds to a photographic exposure.
  42793. */
  42794. set: function (value) {
  42795. this._imageProcessingConfiguration.exposure = value;
  42796. },
  42797. enumerable: true,
  42798. configurable: true
  42799. });
  42800. ;
  42801. ;
  42802. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42803. /**
  42804. * Gets The camera contrast used on this material.
  42805. */
  42806. get: function () {
  42807. return this._imageProcessingConfiguration.contrast;
  42808. },
  42809. /**
  42810. * Sets The camera contrast used on this material.
  42811. */
  42812. set: function (value) {
  42813. this._imageProcessingConfiguration.contrast = value;
  42814. },
  42815. enumerable: true,
  42816. configurable: true
  42817. });
  42818. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42819. /**
  42820. * Gets the Color Grading 2D Lookup Texture.
  42821. */
  42822. get: function () {
  42823. return this._imageProcessingConfiguration.colorGradingTexture;
  42824. },
  42825. /**
  42826. * Sets the Color Grading 2D Lookup Texture.
  42827. */
  42828. set: function (value) {
  42829. this._imageProcessingConfiguration.colorGradingTexture = value;
  42830. },
  42831. enumerable: true,
  42832. configurable: true
  42833. });
  42834. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42835. /**
  42836. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42837. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42838. * 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;
  42839. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42840. */
  42841. get: function () {
  42842. return this._imageProcessingConfiguration.colorCurves;
  42843. },
  42844. /**
  42845. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42846. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42847. * 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;
  42848. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42849. */
  42850. set: function (value) {
  42851. this._imageProcessingConfiguration.colorCurves = value;
  42852. },
  42853. enumerable: true,
  42854. configurable: true
  42855. });
  42856. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  42857. /**
  42858. * Gets a boolean indicating that current material needs to register RTT
  42859. */
  42860. get: function () {
  42861. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42862. return true;
  42863. }
  42864. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42865. return true;
  42866. }
  42867. return false;
  42868. },
  42869. enumerable: true,
  42870. configurable: true
  42871. });
  42872. /**
  42873. * Gets the current class name of the material e.g. "StandardMaterial"
  42874. * Mainly use in serialization.
  42875. * @returns the class name
  42876. */
  42877. StandardMaterial.prototype.getClassName = function () {
  42878. return "StandardMaterial";
  42879. };
  42880. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42881. /**
  42882. * In case the depth buffer does not allow enough depth precision for your scene (might be the case in large scenes)
  42883. * You can try switching to logarithmic depth.
  42884. * @see http://doc.babylonjs.com/how_to/using_logarithmic_depth_buffer
  42885. */
  42886. get: function () {
  42887. return this._useLogarithmicDepth;
  42888. },
  42889. set: function (value) {
  42890. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42891. this._markAllSubMeshesAsMiscDirty();
  42892. },
  42893. enumerable: true,
  42894. configurable: true
  42895. });
  42896. /**
  42897. * Specifies if the material will require alpha blending
  42898. * @returns a boolean specifying if alpha blending is needed
  42899. */
  42900. StandardMaterial.prototype.needAlphaBlending = function () {
  42901. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42902. };
  42903. /**
  42904. * Specifies if this material should be rendered in alpha test mode
  42905. * @returns a boolean specifying if an alpha test is needed.
  42906. */
  42907. StandardMaterial.prototype.needAlphaTesting = function () {
  42908. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42909. };
  42910. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42911. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42912. };
  42913. /**
  42914. * Get the texture used for alpha test purpose.
  42915. * @returns the diffuse texture in case of the standard material.
  42916. */
  42917. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42918. return this._diffuseTexture;
  42919. };
  42920. /**
  42921. * Get if the submesh is ready to be used and all its information available.
  42922. * Child classes can use it to update shaders
  42923. * @param mesh defines the mesh to check
  42924. * @param subMesh defines which submesh to check
  42925. * @param useInstances specifies that instances should be used
  42926. * @returns a boolean indicating that the submesh is ready or not
  42927. */
  42928. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42929. if (useInstances === void 0) { useInstances = false; }
  42930. if (subMesh.effect && this.isFrozen) {
  42931. if (this._wasPreviouslyReady) {
  42932. return true;
  42933. }
  42934. }
  42935. if (!subMesh._materialDefines) {
  42936. subMesh._materialDefines = new StandardMaterialDefines();
  42937. }
  42938. var scene = this.getScene();
  42939. var defines = subMesh._materialDefines;
  42940. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42941. if (defines._renderId === scene.getRenderId()) {
  42942. return true;
  42943. }
  42944. }
  42945. var engine = scene.getEngine();
  42946. // Lights
  42947. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42948. // Textures
  42949. if (defines._areTexturesDirty) {
  42950. defines._needUVs = false;
  42951. defines.MAINUV1 = false;
  42952. defines.MAINUV2 = false;
  42953. if (scene.texturesEnabled) {
  42954. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42955. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42956. return false;
  42957. }
  42958. else {
  42959. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42960. }
  42961. }
  42962. else {
  42963. defines.DIFFUSE = false;
  42964. }
  42965. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42966. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42967. return false;
  42968. }
  42969. else {
  42970. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42971. }
  42972. }
  42973. else {
  42974. defines.AMBIENT = false;
  42975. }
  42976. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42977. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42978. return false;
  42979. }
  42980. else {
  42981. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42982. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42983. }
  42984. }
  42985. else {
  42986. defines.OPACITY = false;
  42987. }
  42988. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42989. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42990. return false;
  42991. }
  42992. else {
  42993. defines._needNormals = true;
  42994. defines.REFLECTION = true;
  42995. defines.ROUGHNESS = (this._roughness > 0);
  42996. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42997. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42998. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42999. switch (this._reflectionTexture.coordinatesMode) {
  43000. case BABYLON.Texture.EXPLICIT_MODE:
  43001. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43002. break;
  43003. case BABYLON.Texture.PLANAR_MODE:
  43004. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43005. break;
  43006. case BABYLON.Texture.PROJECTION_MODE:
  43007. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43008. break;
  43009. case BABYLON.Texture.SKYBOX_MODE:
  43010. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43011. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  43012. break;
  43013. case BABYLON.Texture.SPHERICAL_MODE:
  43014. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43015. break;
  43016. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43017. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43018. break;
  43019. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43020. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43021. break;
  43022. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43023. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43024. break;
  43025. case BABYLON.Texture.CUBIC_MODE:
  43026. case BABYLON.Texture.INVCUBIC_MODE:
  43027. default:
  43028. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43029. break;
  43030. }
  43031. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43032. }
  43033. }
  43034. else {
  43035. defines.REFLECTION = false;
  43036. }
  43037. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43038. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43039. return false;
  43040. }
  43041. else {
  43042. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43043. }
  43044. }
  43045. else {
  43046. defines.EMISSIVE = false;
  43047. }
  43048. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43049. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43050. return false;
  43051. }
  43052. else {
  43053. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43054. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43055. }
  43056. }
  43057. else {
  43058. defines.LIGHTMAP = false;
  43059. }
  43060. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43061. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43062. return false;
  43063. }
  43064. else {
  43065. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43066. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43067. }
  43068. }
  43069. else {
  43070. defines.SPECULAR = false;
  43071. }
  43072. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43073. // Bump texure can not be not blocking.
  43074. if (!this._bumpTexture.isReady()) {
  43075. return false;
  43076. }
  43077. else {
  43078. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43079. defines.PARALLAX = this._useParallax;
  43080. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43081. }
  43082. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43083. }
  43084. else {
  43085. defines.BUMP = false;
  43086. }
  43087. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43088. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43089. return false;
  43090. }
  43091. else {
  43092. defines._needUVs = true;
  43093. defines.REFRACTION = true;
  43094. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43095. }
  43096. }
  43097. else {
  43098. defines.REFRACTION = false;
  43099. }
  43100. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43101. }
  43102. else {
  43103. defines.DIFFUSE = false;
  43104. defines.AMBIENT = false;
  43105. defines.OPACITY = false;
  43106. defines.REFLECTION = false;
  43107. defines.EMISSIVE = false;
  43108. defines.LIGHTMAP = false;
  43109. defines.BUMP = false;
  43110. defines.REFRACTION = false;
  43111. }
  43112. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43113. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43114. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43115. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43116. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43117. }
  43118. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43119. if (!this._imageProcessingConfiguration.isReady()) {
  43120. return false;
  43121. }
  43122. this._imageProcessingConfiguration.prepareDefines(defines);
  43123. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43124. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43125. }
  43126. if (defines._areFresnelDirty) {
  43127. if (StandardMaterial.FresnelEnabled) {
  43128. // Fresnel
  43129. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43130. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43131. this._reflectionFresnelParameters) {
  43132. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43133. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43134. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43135. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43136. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43137. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43138. defines._needNormals = true;
  43139. defines.FRESNEL = true;
  43140. }
  43141. }
  43142. else {
  43143. defines.FRESNEL = false;
  43144. }
  43145. }
  43146. // Misc.
  43147. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43148. // Attribs
  43149. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43150. // Values that need to be evaluated on every frame
  43151. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43152. // Get correct effect
  43153. if (defines.isDirty) {
  43154. defines.markAsProcessed();
  43155. scene.resetCachedMaterial();
  43156. // Fallbacks
  43157. var fallbacks = new BABYLON.EffectFallbacks();
  43158. if (defines.REFLECTION) {
  43159. fallbacks.addFallback(0, "REFLECTION");
  43160. }
  43161. if (defines.SPECULAR) {
  43162. fallbacks.addFallback(0, "SPECULAR");
  43163. }
  43164. if (defines.BUMP) {
  43165. fallbacks.addFallback(0, "BUMP");
  43166. }
  43167. if (defines.PARALLAX) {
  43168. fallbacks.addFallback(1, "PARALLAX");
  43169. }
  43170. if (defines.PARALLAXOCCLUSION) {
  43171. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43172. }
  43173. if (defines.SPECULAROVERALPHA) {
  43174. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43175. }
  43176. if (defines.FOG) {
  43177. fallbacks.addFallback(1, "FOG");
  43178. }
  43179. if (defines.POINTSIZE) {
  43180. fallbacks.addFallback(0, "POINTSIZE");
  43181. }
  43182. if (defines.LOGARITHMICDEPTH) {
  43183. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43184. }
  43185. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43186. if (defines.SPECULARTERM) {
  43187. fallbacks.addFallback(0, "SPECULARTERM");
  43188. }
  43189. if (defines.DIFFUSEFRESNEL) {
  43190. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43191. }
  43192. if (defines.OPACITYFRESNEL) {
  43193. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43194. }
  43195. if (defines.REFLECTIONFRESNEL) {
  43196. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43197. }
  43198. if (defines.EMISSIVEFRESNEL) {
  43199. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43200. }
  43201. if (defines.FRESNEL) {
  43202. fallbacks.addFallback(4, "FRESNEL");
  43203. }
  43204. //Attributes
  43205. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43206. if (defines.NORMAL) {
  43207. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43208. }
  43209. if (defines.UV1) {
  43210. attribs.push(BABYLON.VertexBuffer.UVKind);
  43211. }
  43212. if (defines.UV2) {
  43213. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43214. }
  43215. if (defines.VERTEXCOLOR) {
  43216. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43217. }
  43218. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43219. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43220. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43221. var shaderName = "default";
  43222. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43223. "vFogInfos", "vFogColor", "pointSize",
  43224. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43225. "mBones",
  43226. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43227. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43228. "vReflectionPosition", "vReflectionSize",
  43229. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43230. ];
  43231. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43232. var uniformBuffers = ["Material", "Scene"];
  43233. if (BABYLON.ImageProcessingConfiguration) {
  43234. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43235. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43236. }
  43237. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43238. uniformsNames: uniforms,
  43239. uniformBuffersNames: uniformBuffers,
  43240. samplers: samplers,
  43241. defines: defines,
  43242. maxSimultaneousLights: this._maxSimultaneousLights
  43243. });
  43244. if (this.customShaderNameResolve) {
  43245. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43246. }
  43247. var join = defines.toString();
  43248. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43249. attributes: attribs,
  43250. uniformsNames: uniforms,
  43251. uniformBuffersNames: uniformBuffers,
  43252. samplers: samplers,
  43253. defines: join,
  43254. fallbacks: fallbacks,
  43255. onCompiled: this.onCompiled,
  43256. onError: this.onError,
  43257. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43258. }, engine), defines);
  43259. this.buildUniformLayout();
  43260. }
  43261. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43262. return false;
  43263. }
  43264. defines._renderId = scene.getRenderId();
  43265. this._wasPreviouslyReady = true;
  43266. return true;
  43267. };
  43268. /**
  43269. * Builds the material UBO layouts.
  43270. * Used internally during the effect preparation.
  43271. */
  43272. StandardMaterial.prototype.buildUniformLayout = function () {
  43273. // Order is important !
  43274. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43275. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43276. this._uniformBuffer.addUniform("opacityParts", 4);
  43277. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43278. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43279. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43280. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43281. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43282. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43283. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43284. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43285. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43286. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43287. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43288. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43289. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43290. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43291. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43292. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43293. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43294. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43295. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43296. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43297. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43298. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43299. this._uniformBuffer.addUniform("specularMatrix", 16);
  43300. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43301. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43302. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43303. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43304. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43305. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43306. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43307. this._uniformBuffer.addUniform("pointSize", 1);
  43308. this._uniformBuffer.create();
  43309. };
  43310. /**
  43311. * Unbinds the material from the mesh
  43312. */
  43313. StandardMaterial.prototype.unbind = function () {
  43314. if (this._activeEffect) {
  43315. var needFlag = false;
  43316. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43317. this._activeEffect.setTexture("reflection2DSampler", null);
  43318. needFlag = true;
  43319. }
  43320. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43321. this._activeEffect.setTexture("refraction2DSampler", null);
  43322. needFlag = true;
  43323. }
  43324. if (needFlag) {
  43325. this._markAllSubMeshesAsTexturesDirty();
  43326. }
  43327. }
  43328. _super.prototype.unbind.call(this);
  43329. };
  43330. /**
  43331. * Binds the submesh to this material by preparing the effect and shader to draw
  43332. * @param world defines the world transformation matrix
  43333. * @param mesh defines the mesh containing the submesh
  43334. * @param subMesh defines the submesh to bind the material to
  43335. */
  43336. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43337. var scene = this.getScene();
  43338. var defines = subMesh._materialDefines;
  43339. if (!defines) {
  43340. return;
  43341. }
  43342. var effect = subMesh.effect;
  43343. if (!effect) {
  43344. return;
  43345. }
  43346. this._activeEffect = effect;
  43347. // Matrices
  43348. this.bindOnlyWorldMatrix(world);
  43349. // Normal Matrix
  43350. if (defines.OBJECTSPACE_NORMALMAP) {
  43351. world.toNormalMatrix(this._normalMatrix);
  43352. this.bindOnlyNormalMatrix(this._normalMatrix);
  43353. }
  43354. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43355. // Bones
  43356. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43357. if (mustRebind) {
  43358. this._uniformBuffer.bindToEffect(effect, "Material");
  43359. this.bindViewProjection(effect);
  43360. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43361. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43362. // Fresnel
  43363. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43364. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43365. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43366. }
  43367. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43368. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43369. }
  43370. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43371. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43372. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43373. }
  43374. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43375. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43376. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43377. }
  43378. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43379. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43380. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43381. }
  43382. }
  43383. // Textures
  43384. if (scene.texturesEnabled) {
  43385. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43386. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43387. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43388. if (this._diffuseTexture.hasAlpha) {
  43389. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43390. }
  43391. }
  43392. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43393. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43394. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43395. }
  43396. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43397. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43398. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43399. }
  43400. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43401. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43402. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43403. if (this._reflectionTexture.boundingBoxSize) {
  43404. var cubeTexture = this._reflectionTexture;
  43405. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43406. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43407. }
  43408. }
  43409. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43410. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43411. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43412. }
  43413. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43414. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43415. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43416. }
  43417. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43418. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43419. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43420. }
  43421. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43422. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43423. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43424. if (scene._mirroredCameraPosition) {
  43425. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43426. }
  43427. else {
  43428. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43429. }
  43430. }
  43431. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43432. var depth = 1.0;
  43433. if (!this._refractionTexture.isCube) {
  43434. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43435. if (this._refractionTexture.depth) {
  43436. depth = this._refractionTexture.depth;
  43437. }
  43438. }
  43439. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43440. }
  43441. }
  43442. // Point size
  43443. if (this.pointsCloud) {
  43444. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43445. }
  43446. if (defines.SPECULARTERM) {
  43447. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43448. }
  43449. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43450. // Diffuse
  43451. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43452. }
  43453. // Textures
  43454. if (scene.texturesEnabled) {
  43455. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43456. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43457. }
  43458. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43459. effect.setTexture("ambientSampler", this._ambientTexture);
  43460. }
  43461. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43462. effect.setTexture("opacitySampler", this._opacityTexture);
  43463. }
  43464. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43465. if (this._reflectionTexture.isCube) {
  43466. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43467. }
  43468. else {
  43469. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43470. }
  43471. }
  43472. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43473. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43474. }
  43475. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43476. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43477. }
  43478. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43479. effect.setTexture("specularSampler", this._specularTexture);
  43480. }
  43481. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43482. effect.setTexture("bumpSampler", this._bumpTexture);
  43483. }
  43484. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43485. var depth = 1.0;
  43486. if (this._refractionTexture.isCube) {
  43487. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43488. }
  43489. else {
  43490. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43491. }
  43492. }
  43493. }
  43494. // Clip plane
  43495. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43496. // Colors
  43497. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43498. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43499. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43500. }
  43501. if (mustRebind || !this.isFrozen) {
  43502. // Lights
  43503. if (scene.lightsEnabled && !this._disableLighting) {
  43504. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43505. }
  43506. // View
  43507. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43508. this.bindView(effect);
  43509. }
  43510. // Fog
  43511. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43512. // Morph targets
  43513. if (defines.NUM_MORPH_INFLUENCERS) {
  43514. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43515. }
  43516. // Log. depth
  43517. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43518. // image processing
  43519. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  43520. this._imageProcessingConfiguration.bind(this._activeEffect);
  43521. }
  43522. }
  43523. this._uniformBuffer.update();
  43524. this._afterBind(mesh, this._activeEffect);
  43525. };
  43526. /**
  43527. * Get the list of animatables in the material.
  43528. * @returns the list of animatables object used in the material
  43529. */
  43530. StandardMaterial.prototype.getAnimatables = function () {
  43531. var results = [];
  43532. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43533. results.push(this._diffuseTexture);
  43534. }
  43535. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43536. results.push(this._ambientTexture);
  43537. }
  43538. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43539. results.push(this._opacityTexture);
  43540. }
  43541. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43542. results.push(this._reflectionTexture);
  43543. }
  43544. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43545. results.push(this._emissiveTexture);
  43546. }
  43547. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43548. results.push(this._specularTexture);
  43549. }
  43550. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43551. results.push(this._bumpTexture);
  43552. }
  43553. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43554. results.push(this._lightmapTexture);
  43555. }
  43556. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43557. results.push(this._refractionTexture);
  43558. }
  43559. return results;
  43560. };
  43561. /**
  43562. * Gets the active textures from the material
  43563. * @returns an array of textures
  43564. */
  43565. StandardMaterial.prototype.getActiveTextures = function () {
  43566. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43567. if (this._diffuseTexture) {
  43568. activeTextures.push(this._diffuseTexture);
  43569. }
  43570. if (this._ambientTexture) {
  43571. activeTextures.push(this._ambientTexture);
  43572. }
  43573. if (this._opacityTexture) {
  43574. activeTextures.push(this._opacityTexture);
  43575. }
  43576. if (this._reflectionTexture) {
  43577. activeTextures.push(this._reflectionTexture);
  43578. }
  43579. if (this._emissiveTexture) {
  43580. activeTextures.push(this._emissiveTexture);
  43581. }
  43582. if (this._specularTexture) {
  43583. activeTextures.push(this._specularTexture);
  43584. }
  43585. if (this._bumpTexture) {
  43586. activeTextures.push(this._bumpTexture);
  43587. }
  43588. if (this._lightmapTexture) {
  43589. activeTextures.push(this._lightmapTexture);
  43590. }
  43591. if (this._refractionTexture) {
  43592. activeTextures.push(this._refractionTexture);
  43593. }
  43594. return activeTextures;
  43595. };
  43596. /**
  43597. * Specifies if the material uses a texture
  43598. * @param texture defines the texture to check against the material
  43599. * @returns a boolean specifying if the material uses the texture
  43600. */
  43601. StandardMaterial.prototype.hasTexture = function (texture) {
  43602. if (_super.prototype.hasTexture.call(this, texture)) {
  43603. return true;
  43604. }
  43605. if (this._diffuseTexture === texture) {
  43606. return true;
  43607. }
  43608. if (this._ambientTexture === texture) {
  43609. return true;
  43610. }
  43611. if (this._opacityTexture === texture) {
  43612. return true;
  43613. }
  43614. if (this._reflectionTexture === texture) {
  43615. return true;
  43616. }
  43617. if (this._emissiveTexture === texture) {
  43618. return true;
  43619. }
  43620. if (this._specularTexture === texture) {
  43621. return true;
  43622. }
  43623. if (this._bumpTexture === texture) {
  43624. return true;
  43625. }
  43626. if (this._lightmapTexture === texture) {
  43627. return true;
  43628. }
  43629. if (this._refractionTexture === texture) {
  43630. return true;
  43631. }
  43632. return false;
  43633. };
  43634. /**
  43635. * Disposes the material
  43636. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  43637. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  43638. */
  43639. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43640. if (forceDisposeTextures) {
  43641. if (this._diffuseTexture) {
  43642. this._diffuseTexture.dispose();
  43643. }
  43644. if (this._ambientTexture) {
  43645. this._ambientTexture.dispose();
  43646. }
  43647. if (this._opacityTexture) {
  43648. this._opacityTexture.dispose();
  43649. }
  43650. if (this._reflectionTexture) {
  43651. this._reflectionTexture.dispose();
  43652. }
  43653. if (this._emissiveTexture) {
  43654. this._emissiveTexture.dispose();
  43655. }
  43656. if (this._specularTexture) {
  43657. this._specularTexture.dispose();
  43658. }
  43659. if (this._bumpTexture) {
  43660. this._bumpTexture.dispose();
  43661. }
  43662. if (this._lightmapTexture) {
  43663. this._lightmapTexture.dispose();
  43664. }
  43665. if (this._refractionTexture) {
  43666. this._refractionTexture.dispose();
  43667. }
  43668. }
  43669. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43670. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43671. }
  43672. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43673. };
  43674. /**
  43675. * Makes a duplicate of the material, and gives it a new name
  43676. * @param name defines the new name for the duplicated material
  43677. * @returns the cloned material
  43678. */
  43679. StandardMaterial.prototype.clone = function (name) {
  43680. var _this = this;
  43681. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43682. result.name = name;
  43683. result.id = name;
  43684. return result;
  43685. };
  43686. /**
  43687. * Serializes this material in a JSON representation
  43688. * @returns the serialized material object
  43689. */
  43690. StandardMaterial.prototype.serialize = function () {
  43691. return BABYLON.SerializationHelper.Serialize(this);
  43692. };
  43693. /**
  43694. * Creates a standard material from parsed material data
  43695. * @param source defines the JSON represnetation of the material
  43696. * @param scene defines the hosting scene
  43697. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  43698. * @returns a new material
  43699. */
  43700. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43701. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43702. };
  43703. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43704. /**
  43705. * Are diffuse textures enabled in the application.
  43706. */
  43707. get: function () {
  43708. return StandardMaterial._DiffuseTextureEnabled;
  43709. },
  43710. set: function (value) {
  43711. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43712. return;
  43713. }
  43714. StandardMaterial._DiffuseTextureEnabled = value;
  43715. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43716. },
  43717. enumerable: true,
  43718. configurable: true
  43719. });
  43720. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43721. /**
  43722. * Are ambient textures enabled in the application.
  43723. */
  43724. get: function () {
  43725. return StandardMaterial._AmbientTextureEnabled;
  43726. },
  43727. set: function (value) {
  43728. if (StandardMaterial._AmbientTextureEnabled === value) {
  43729. return;
  43730. }
  43731. StandardMaterial._AmbientTextureEnabled = value;
  43732. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43733. },
  43734. enumerable: true,
  43735. configurable: true
  43736. });
  43737. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43738. /**
  43739. * Are opacity textures enabled in the application.
  43740. */
  43741. get: function () {
  43742. return StandardMaterial._OpacityTextureEnabled;
  43743. },
  43744. set: function (value) {
  43745. if (StandardMaterial._OpacityTextureEnabled === value) {
  43746. return;
  43747. }
  43748. StandardMaterial._OpacityTextureEnabled = value;
  43749. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43750. },
  43751. enumerable: true,
  43752. configurable: true
  43753. });
  43754. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43755. /**
  43756. * Are reflection textures enabled in the application.
  43757. */
  43758. get: function () {
  43759. return StandardMaterial._ReflectionTextureEnabled;
  43760. },
  43761. set: function (value) {
  43762. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43763. return;
  43764. }
  43765. StandardMaterial._ReflectionTextureEnabled = value;
  43766. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43767. },
  43768. enumerable: true,
  43769. configurable: true
  43770. });
  43771. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43772. /**
  43773. * Are emissive textures enabled in the application.
  43774. */
  43775. get: function () {
  43776. return StandardMaterial._EmissiveTextureEnabled;
  43777. },
  43778. set: function (value) {
  43779. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43780. return;
  43781. }
  43782. StandardMaterial._EmissiveTextureEnabled = value;
  43783. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43784. },
  43785. enumerable: true,
  43786. configurable: true
  43787. });
  43788. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43789. /**
  43790. * Are specular textures enabled in the application.
  43791. */
  43792. get: function () {
  43793. return StandardMaterial._SpecularTextureEnabled;
  43794. },
  43795. set: function (value) {
  43796. if (StandardMaterial._SpecularTextureEnabled === value) {
  43797. return;
  43798. }
  43799. StandardMaterial._SpecularTextureEnabled = value;
  43800. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43801. },
  43802. enumerable: true,
  43803. configurable: true
  43804. });
  43805. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43806. /**
  43807. * Are bump textures enabled in the application.
  43808. */
  43809. get: function () {
  43810. return StandardMaterial._BumpTextureEnabled;
  43811. },
  43812. set: function (value) {
  43813. if (StandardMaterial._BumpTextureEnabled === value) {
  43814. return;
  43815. }
  43816. StandardMaterial._BumpTextureEnabled = value;
  43817. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43818. },
  43819. enumerable: true,
  43820. configurable: true
  43821. });
  43822. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43823. /**
  43824. * Are lightmap textures enabled in the application.
  43825. */
  43826. get: function () {
  43827. return StandardMaterial._LightmapTextureEnabled;
  43828. },
  43829. set: function (value) {
  43830. if (StandardMaterial._LightmapTextureEnabled === value) {
  43831. return;
  43832. }
  43833. StandardMaterial._LightmapTextureEnabled = value;
  43834. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43835. },
  43836. enumerable: true,
  43837. configurable: true
  43838. });
  43839. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43840. /**
  43841. * Are refraction textures enabled in the application.
  43842. */
  43843. get: function () {
  43844. return StandardMaterial._RefractionTextureEnabled;
  43845. },
  43846. set: function (value) {
  43847. if (StandardMaterial._RefractionTextureEnabled === value) {
  43848. return;
  43849. }
  43850. StandardMaterial._RefractionTextureEnabled = value;
  43851. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43852. },
  43853. enumerable: true,
  43854. configurable: true
  43855. });
  43856. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43857. /**
  43858. * Are color grading textures enabled in the application.
  43859. */
  43860. get: function () {
  43861. return StandardMaterial._ColorGradingTextureEnabled;
  43862. },
  43863. set: function (value) {
  43864. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43865. return;
  43866. }
  43867. StandardMaterial._ColorGradingTextureEnabled = value;
  43868. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43869. },
  43870. enumerable: true,
  43871. configurable: true
  43872. });
  43873. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43874. /**
  43875. * Are fresnels enabled in the application.
  43876. */
  43877. get: function () {
  43878. return StandardMaterial._FresnelEnabled;
  43879. },
  43880. set: function (value) {
  43881. if (StandardMaterial._FresnelEnabled === value) {
  43882. return;
  43883. }
  43884. StandardMaterial._FresnelEnabled = value;
  43885. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43886. },
  43887. enumerable: true,
  43888. configurable: true
  43889. });
  43890. // Flags used to enable or disable a type of texture for all Standard Materials
  43891. StandardMaterial._DiffuseTextureEnabled = true;
  43892. StandardMaterial._AmbientTextureEnabled = true;
  43893. StandardMaterial._OpacityTextureEnabled = true;
  43894. StandardMaterial._ReflectionTextureEnabled = true;
  43895. StandardMaterial._EmissiveTextureEnabled = true;
  43896. StandardMaterial._SpecularTextureEnabled = true;
  43897. StandardMaterial._BumpTextureEnabled = true;
  43898. StandardMaterial._LightmapTextureEnabled = true;
  43899. StandardMaterial._RefractionTextureEnabled = true;
  43900. StandardMaterial._ColorGradingTextureEnabled = true;
  43901. StandardMaterial._FresnelEnabled = true;
  43902. __decorate([
  43903. BABYLON.serializeAsTexture("diffuseTexture")
  43904. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43905. __decorate([
  43906. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43907. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43908. __decorate([
  43909. BABYLON.serializeAsTexture("ambientTexture")
  43910. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43911. __decorate([
  43912. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43913. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43914. __decorate([
  43915. BABYLON.serializeAsTexture("opacityTexture")
  43916. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43917. __decorate([
  43918. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43919. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43920. __decorate([
  43921. BABYLON.serializeAsTexture("reflectionTexture")
  43922. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43923. __decorate([
  43924. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43925. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43926. __decorate([
  43927. BABYLON.serializeAsTexture("emissiveTexture")
  43928. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43929. __decorate([
  43930. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43931. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43932. __decorate([
  43933. BABYLON.serializeAsTexture("specularTexture")
  43934. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43935. __decorate([
  43936. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43937. ], StandardMaterial.prototype, "specularTexture", void 0);
  43938. __decorate([
  43939. BABYLON.serializeAsTexture("bumpTexture")
  43940. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43941. __decorate([
  43942. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43943. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43944. __decorate([
  43945. BABYLON.serializeAsTexture("lightmapTexture")
  43946. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43947. __decorate([
  43948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43949. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43950. __decorate([
  43951. BABYLON.serializeAsTexture("refractionTexture")
  43952. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43953. __decorate([
  43954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43955. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43956. __decorate([
  43957. BABYLON.serializeAsColor3("ambient")
  43958. ], StandardMaterial.prototype, "ambientColor", void 0);
  43959. __decorate([
  43960. BABYLON.serializeAsColor3("diffuse")
  43961. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43962. __decorate([
  43963. BABYLON.serializeAsColor3("specular")
  43964. ], StandardMaterial.prototype, "specularColor", void 0);
  43965. __decorate([
  43966. BABYLON.serializeAsColor3("emissive")
  43967. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43968. __decorate([
  43969. BABYLON.serialize()
  43970. ], StandardMaterial.prototype, "specularPower", void 0);
  43971. __decorate([
  43972. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43973. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43974. __decorate([
  43975. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43976. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43977. __decorate([
  43978. BABYLON.serialize("useEmissiveAsIllumination")
  43979. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43980. __decorate([
  43981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43982. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43983. __decorate([
  43984. BABYLON.serialize("linkEmissiveWithDiffuse")
  43985. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43986. __decorate([
  43987. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43988. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43989. __decorate([
  43990. BABYLON.serialize("useSpecularOverAlpha")
  43991. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43992. __decorate([
  43993. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43994. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43995. __decorate([
  43996. BABYLON.serialize("useReflectionOverAlpha")
  43997. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43998. __decorate([
  43999. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44000. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44001. __decorate([
  44002. BABYLON.serialize("disableLighting")
  44003. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44004. __decorate([
  44005. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44006. ], StandardMaterial.prototype, "disableLighting", void 0);
  44007. __decorate([
  44008. BABYLON.serialize("useObjectSpaceNormalMap")
  44009. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44010. __decorate([
  44011. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44012. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44013. __decorate([
  44014. BABYLON.serialize("useParallax")
  44015. ], StandardMaterial.prototype, "_useParallax", void 0);
  44016. __decorate([
  44017. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44018. ], StandardMaterial.prototype, "useParallax", void 0);
  44019. __decorate([
  44020. BABYLON.serialize("useParallaxOcclusion")
  44021. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44022. __decorate([
  44023. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44024. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44025. __decorate([
  44026. BABYLON.serialize()
  44027. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44028. __decorate([
  44029. BABYLON.serialize("roughness")
  44030. ], StandardMaterial.prototype, "_roughness", void 0);
  44031. __decorate([
  44032. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44033. ], StandardMaterial.prototype, "roughness", void 0);
  44034. __decorate([
  44035. BABYLON.serialize()
  44036. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44037. __decorate([
  44038. BABYLON.serialize()
  44039. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44040. __decorate([
  44041. BABYLON.serialize()
  44042. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44043. __decorate([
  44044. BABYLON.serialize("useLightmapAsShadowmap")
  44045. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44046. __decorate([
  44047. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44048. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44049. __decorate([
  44050. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44051. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44052. __decorate([
  44053. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44054. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44055. __decorate([
  44056. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44057. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44058. __decorate([
  44059. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44060. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44061. __decorate([
  44062. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44063. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44064. __decorate([
  44065. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44066. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44067. __decorate([
  44068. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44069. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44070. __decorate([
  44071. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44072. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44073. __decorate([
  44074. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44075. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44076. __decorate([
  44077. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44078. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44079. __decorate([
  44080. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44081. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44082. __decorate([
  44083. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44084. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44085. __decorate([
  44086. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44087. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44088. __decorate([
  44089. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44090. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44091. __decorate([
  44092. BABYLON.serialize("maxSimultaneousLights")
  44093. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44094. __decorate([
  44095. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44096. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44097. __decorate([
  44098. BABYLON.serialize("invertNormalMapX")
  44099. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44100. __decorate([
  44101. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44102. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44103. __decorate([
  44104. BABYLON.serialize("invertNormalMapY")
  44105. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44106. __decorate([
  44107. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44108. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44109. __decorate([
  44110. BABYLON.serialize("twoSidedLighting")
  44111. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44112. __decorate([
  44113. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44114. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44115. __decorate([
  44116. BABYLON.serialize()
  44117. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44118. return StandardMaterial;
  44119. }(BABYLON.PushMaterial));
  44120. BABYLON.StandardMaterial = StandardMaterial;
  44121. })(BABYLON || (BABYLON = {}));
  44122. //# sourceMappingURL=babylon.standardMaterial.js.map
  44123. var BABYLON;
  44124. (function (BABYLON) {
  44125. /**
  44126. * Class representing spherical polynomial coefficients to the 3rd degree
  44127. */
  44128. var SphericalPolynomial = /** @class */ (function () {
  44129. function SphericalPolynomial() {
  44130. /**
  44131. * The x coefficients of the spherical polynomial
  44132. */
  44133. this.x = BABYLON.Vector3.Zero();
  44134. /**
  44135. * The y coefficients of the spherical polynomial
  44136. */
  44137. this.y = BABYLON.Vector3.Zero();
  44138. /**
  44139. * The z coefficients of the spherical polynomial
  44140. */
  44141. this.z = BABYLON.Vector3.Zero();
  44142. /**
  44143. * The xx coefficients of the spherical polynomial
  44144. */
  44145. this.xx = BABYLON.Vector3.Zero();
  44146. /**
  44147. * The yy coefficients of the spherical polynomial
  44148. */
  44149. this.yy = BABYLON.Vector3.Zero();
  44150. /**
  44151. * The zz coefficients of the spherical polynomial
  44152. */
  44153. this.zz = BABYLON.Vector3.Zero();
  44154. /**
  44155. * The xy coefficients of the spherical polynomial
  44156. */
  44157. this.xy = BABYLON.Vector3.Zero();
  44158. /**
  44159. * The yz coefficients of the spherical polynomial
  44160. */
  44161. this.yz = BABYLON.Vector3.Zero();
  44162. /**
  44163. * The zx coefficients of the spherical polynomial
  44164. */
  44165. this.zx = BABYLON.Vector3.Zero();
  44166. }
  44167. /**
  44168. * Adds an ambient color to the spherical polynomial
  44169. * @param color the color to add
  44170. */
  44171. SphericalPolynomial.prototype.addAmbient = function (color) {
  44172. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  44173. this.xx = this.xx.add(colorVector);
  44174. this.yy = this.yy.add(colorVector);
  44175. this.zz = this.zz.add(colorVector);
  44176. };
  44177. /**
  44178. * Scales the spherical polynomial by the given amount
  44179. * @param scale the amount to scale
  44180. */
  44181. SphericalPolynomial.prototype.scale = function (scale) {
  44182. this.x = this.x.scale(scale);
  44183. this.y = this.y.scale(scale);
  44184. this.z = this.z.scale(scale);
  44185. this.xx = this.xx.scale(scale);
  44186. this.yy = this.yy.scale(scale);
  44187. this.zz = this.zz.scale(scale);
  44188. this.yz = this.yz.scale(scale);
  44189. this.zx = this.zx.scale(scale);
  44190. this.xy = this.xy.scale(scale);
  44191. };
  44192. /**
  44193. * Gets the spherical polynomial from harmonics
  44194. * @param harmonics the spherical harmonics
  44195. * @returns the spherical polynomial
  44196. */
  44197. SphericalPolynomial.FromHarmonics = function (harmonics) {
  44198. var result = new SphericalPolynomial();
  44199. result.x = harmonics.l11.scale(1.02333);
  44200. result.y = harmonics.l1_1.scale(1.02333);
  44201. result.z = harmonics.l10.scale(1.02333);
  44202. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  44203. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  44204. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  44205. result.yz = harmonics.l2_1.scale(0.858086);
  44206. result.zx = harmonics.l21.scale(0.858086);
  44207. result.xy = harmonics.l2_2.scale(0.858086);
  44208. result.scale(1.0 / Math.PI);
  44209. return result;
  44210. };
  44211. /**
  44212. * Constructs a spherical polynomial from an array.
  44213. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  44214. * @returns the spherical polynomial
  44215. */
  44216. SphericalPolynomial.FromArray = function (data) {
  44217. var sp = new SphericalPolynomial();
  44218. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  44219. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  44220. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  44221. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  44222. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  44223. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  44224. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  44225. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  44226. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  44227. return sp;
  44228. };
  44229. return SphericalPolynomial;
  44230. }());
  44231. BABYLON.SphericalPolynomial = SphericalPolynomial;
  44232. /**
  44233. * Class representing spherical harmonics coefficients to the 3rd degree
  44234. */
  44235. var SphericalHarmonics = /** @class */ (function () {
  44236. function SphericalHarmonics() {
  44237. /**
  44238. * The l0,0 coefficients of the spherical harmonics
  44239. */
  44240. this.l00 = BABYLON.Vector3.Zero();
  44241. /**
  44242. * The l1,-1 coefficients of the spherical harmonics
  44243. */
  44244. this.l1_1 = BABYLON.Vector3.Zero();
  44245. /**
  44246. * The l1,0 coefficients of the spherical harmonics
  44247. */
  44248. this.l10 = BABYLON.Vector3.Zero();
  44249. /**
  44250. * The l1,1 coefficients of the spherical harmonics
  44251. */
  44252. this.l11 = BABYLON.Vector3.Zero();
  44253. /**
  44254. * The l2,-2 coefficients of the spherical harmonics
  44255. */
  44256. this.l2_2 = BABYLON.Vector3.Zero();
  44257. /**
  44258. * The l2,-1 coefficients of the spherical harmonics
  44259. */
  44260. this.l2_1 = BABYLON.Vector3.Zero();
  44261. /**
  44262. * The l2,0 coefficients of the spherical harmonics
  44263. */
  44264. this.l20 = BABYLON.Vector3.Zero();
  44265. /**
  44266. * The l2,1 coefficients of the spherical harmonics
  44267. */
  44268. this.l21 = BABYLON.Vector3.Zero();
  44269. /**
  44270. * The l2,2 coefficients of the spherical harmonics
  44271. */
  44272. this.lL22 = BABYLON.Vector3.Zero();
  44273. }
  44274. /**
  44275. * Adds a light to the spherical harmonics
  44276. * @param direction the direction of the light
  44277. * @param color the color of the light
  44278. * @param deltaSolidAngle the delta solid angle of the light
  44279. */
  44280. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  44281. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  44282. var c = colorVector.scale(deltaSolidAngle);
  44283. this.l00 = this.l00.add(c.scale(0.282095));
  44284. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  44285. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  44286. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  44287. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  44288. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  44289. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  44290. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  44291. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  44292. };
  44293. /**
  44294. * Scales the spherical harmonics by the given amount
  44295. * @param scale the amount to scale
  44296. */
  44297. SphericalHarmonics.prototype.scale = function (scale) {
  44298. this.l00 = this.l00.scale(scale);
  44299. this.l1_1 = this.l1_1.scale(scale);
  44300. this.l10 = this.l10.scale(scale);
  44301. this.l11 = this.l11.scale(scale);
  44302. this.l2_2 = this.l2_2.scale(scale);
  44303. this.l2_1 = this.l2_1.scale(scale);
  44304. this.l20 = this.l20.scale(scale);
  44305. this.l21 = this.l21.scale(scale);
  44306. this.lL22 = this.lL22.scale(scale);
  44307. };
  44308. /**
  44309. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  44310. *
  44311. * ```
  44312. * E_lm = A_l * L_lm
  44313. * ```
  44314. *
  44315. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  44316. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  44317. * the scaling factors are given in equation 9.
  44318. */
  44319. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  44320. // Constant (Band 0)
  44321. this.l00 = this.l00.scale(3.141593);
  44322. // Linear (Band 1)
  44323. this.l1_1 = this.l1_1.scale(2.094395);
  44324. this.l10 = this.l10.scale(2.094395);
  44325. this.l11 = this.l11.scale(2.094395);
  44326. // Quadratic (Band 2)
  44327. this.l2_2 = this.l2_2.scale(0.785398);
  44328. this.l2_1 = this.l2_1.scale(0.785398);
  44329. this.l20 = this.l20.scale(0.785398);
  44330. this.l21 = this.l21.scale(0.785398);
  44331. this.lL22 = this.lL22.scale(0.785398);
  44332. };
  44333. /**
  44334. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  44335. *
  44336. * ```
  44337. * L = (1/pi) * E * rho
  44338. * ```
  44339. *
  44340. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  44341. */
  44342. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  44343. this.scale(1.0 / Math.PI);
  44344. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  44345. // (The pixel shader must apply albedo after texture fetches, etc).
  44346. };
  44347. /**
  44348. * Gets the spherical harmonics from polynomial
  44349. * @param polynomial the spherical polynomial
  44350. * @returns the spherical harmonics
  44351. */
  44352. SphericalHarmonics.FromPolynomial = function (polynomial) {
  44353. var result = new SphericalHarmonics();
  44354. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  44355. result.l1_1 = polynomial.y.scale(0.977204);
  44356. result.l10 = polynomial.z.scale(0.977204);
  44357. result.l11 = polynomial.x.scale(0.977204);
  44358. result.l2_2 = polynomial.xy.scale(1.16538);
  44359. result.l2_1 = polynomial.yz.scale(1.16538);
  44360. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  44361. result.l21 = polynomial.zx.scale(1.16538);
  44362. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  44363. result.scale(Math.PI);
  44364. return result;
  44365. };
  44366. /**
  44367. * Constructs a spherical harmonics from an array.
  44368. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  44369. * @returns the spherical harmonics
  44370. */
  44371. SphericalHarmonics.FromArray = function (data) {
  44372. var sh = new SphericalHarmonics();
  44373. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  44374. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  44375. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  44376. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  44377. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  44378. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  44379. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  44380. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  44381. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  44382. return sh;
  44383. };
  44384. return SphericalHarmonics;
  44385. }());
  44386. BABYLON.SphericalHarmonics = SphericalHarmonics;
  44387. })(BABYLON || (BABYLON = {}));
  44388. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  44389. var BABYLON;
  44390. (function (BABYLON) {
  44391. var FileFaceOrientation = /** @class */ (function () {
  44392. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  44393. this.name = name;
  44394. this.worldAxisForNormal = worldAxisForNormal;
  44395. this.worldAxisForFileX = worldAxisForFileX;
  44396. this.worldAxisForFileY = worldAxisForFileY;
  44397. }
  44398. return FileFaceOrientation;
  44399. }());
  44400. ;
  44401. /**
  44402. * Helper class dealing with the extraction of spherical polynomial dataArray
  44403. * from a cube map.
  44404. */
  44405. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  44406. function CubeMapToSphericalPolynomialTools() {
  44407. }
  44408. /**
  44409. * Converts a texture to the according Spherical Polynomial data.
  44410. * This extracts the first 3 orders only as they are the only one used in the lighting.
  44411. *
  44412. * @param texture The texture to extract the information from.
  44413. * @return The Spherical Polynomial data.
  44414. */
  44415. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  44416. if (!texture.isCube) {
  44417. // Only supports cube Textures currently.
  44418. return null;
  44419. }
  44420. var size = texture.getSize().width;
  44421. var right = texture.readPixels(0);
  44422. var left = texture.readPixels(1);
  44423. var up;
  44424. var down;
  44425. if (texture.isRenderTarget) {
  44426. up = texture.readPixels(3);
  44427. down = texture.readPixels(2);
  44428. }
  44429. else {
  44430. up = texture.readPixels(2);
  44431. down = texture.readPixels(3);
  44432. }
  44433. var front = texture.readPixels(4);
  44434. var back = texture.readPixels(5);
  44435. var gammaSpace = texture.gammaSpace;
  44436. // Always read as RGBA.
  44437. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  44438. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  44439. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  44440. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  44441. }
  44442. var cubeInfo = {
  44443. size: size,
  44444. right: right,
  44445. left: left,
  44446. up: up,
  44447. down: down,
  44448. front: front,
  44449. back: back,
  44450. format: format,
  44451. type: type,
  44452. gammaSpace: gammaSpace,
  44453. };
  44454. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  44455. };
  44456. /**
  44457. * Converts a cubemap to the according Spherical Polynomial data.
  44458. * This extracts the first 3 orders only as they are the only one used in the lighting.
  44459. *
  44460. * @param cubeInfo The Cube map to extract the information from.
  44461. * @return The Spherical Polynomial data.
  44462. */
  44463. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  44464. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  44465. var totalSolidAngle = 0.0;
  44466. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  44467. var du = 2.0 / cubeInfo.size;
  44468. var dv = du;
  44469. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  44470. var minUV = du * 0.5 - 1.0;
  44471. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  44472. var fileFace = this.FileFaces[faceIndex];
  44473. var dataArray = cubeInfo[fileFace.name];
  44474. var v = minUV;
  44475. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  44476. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  44477. // Because SP is still linear, so summation is fine in that basis.
  44478. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  44479. for (var y = 0; y < cubeInfo.size; y++) {
  44480. var u = minUV;
  44481. for (var x = 0; x < cubeInfo.size; x++) {
  44482. // World direction (not normalised)
  44483. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  44484. worldDirection.normalize();
  44485. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  44486. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  44487. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  44488. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  44489. // Handle Integer types.
  44490. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  44491. r /= 255;
  44492. g /= 255;
  44493. b /= 255;
  44494. }
  44495. // Handle Gamma space textures.
  44496. if (cubeInfo.gammaSpace) {
  44497. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  44498. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  44499. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  44500. }
  44501. var color = new BABYLON.Color3(r, g, b);
  44502. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  44503. totalSolidAngle += deltaSolidAngle;
  44504. u += du;
  44505. }
  44506. v += dv;
  44507. }
  44508. }
  44509. // Solid angle for entire sphere is 4*pi
  44510. var sphereSolidAngle = 4.0 * Math.PI;
  44511. // Adjust the solid angle to allow for how many faces we processed.
  44512. var facesProcessed = 6.0;
  44513. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  44514. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  44515. // This is needed because the numerical integration over the cube uses a
  44516. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  44517. // and also to compensate for accumulative error due to float precision in the summation.
  44518. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  44519. sphericalHarmonics.scale(correctionFactor);
  44520. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  44521. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  44522. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  44523. };
  44524. CubeMapToSphericalPolynomialTools.FileFaces = [
  44525. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  44526. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  44527. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  44528. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  44529. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  44530. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  44531. ];
  44532. return CubeMapToSphericalPolynomialTools;
  44533. }());
  44534. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  44535. })(BABYLON || (BABYLON = {}));
  44536. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  44537. var BABYLON;
  44538. (function (BABYLON) {
  44539. /**
  44540. * Manages the defines for the PBR Material.
  44541. * @hiddenChildren
  44542. */
  44543. var PBRMaterialDefines = /** @class */ (function (_super) {
  44544. __extends(PBRMaterialDefines, _super);
  44545. /**
  44546. * Initializes the PBR Material defines.
  44547. */
  44548. function PBRMaterialDefines() {
  44549. var _this = _super.call(this) || this;
  44550. _this.PBR = true;
  44551. _this.MAINUV1 = false;
  44552. _this.MAINUV2 = false;
  44553. _this.UV1 = false;
  44554. _this.UV2 = false;
  44555. _this.ALBEDO = false;
  44556. _this.ALBEDODIRECTUV = 0;
  44557. _this.VERTEXCOLOR = false;
  44558. _this.AMBIENT = false;
  44559. _this.AMBIENTDIRECTUV = 0;
  44560. _this.AMBIENTINGRAYSCALE = false;
  44561. _this.OPACITY = false;
  44562. _this.VERTEXALPHA = false;
  44563. _this.OPACITYDIRECTUV = 0;
  44564. _this.OPACITYRGB = false;
  44565. _this.ALPHATEST = false;
  44566. _this.DEPTHPREPASS = false;
  44567. _this.ALPHABLEND = false;
  44568. _this.ALPHAFROMALBEDO = false;
  44569. _this.ALPHATESTVALUE = "0.5";
  44570. _this.SPECULAROVERALPHA = false;
  44571. _this.RADIANCEOVERALPHA = false;
  44572. _this.ALPHAFRESNEL = false;
  44573. _this.LINEARALPHAFRESNEL = false;
  44574. _this.PREMULTIPLYALPHA = false;
  44575. _this.EMISSIVE = false;
  44576. _this.EMISSIVEDIRECTUV = 0;
  44577. _this.REFLECTIVITY = false;
  44578. _this.REFLECTIVITYDIRECTUV = 0;
  44579. _this.SPECULARTERM = false;
  44580. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44581. _this.MICROSURFACEAUTOMATIC = false;
  44582. _this.LODBASEDMICROSFURACE = false;
  44583. _this.MICROSURFACEMAP = false;
  44584. _this.MICROSURFACEMAPDIRECTUV = 0;
  44585. _this.METALLICWORKFLOW = false;
  44586. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44587. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44588. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44589. _this.AOSTOREINMETALMAPRED = false;
  44590. _this.ENVIRONMENTBRDF = false;
  44591. _this.NORMAL = false;
  44592. _this.TANGENT = false;
  44593. _this.BUMP = false;
  44594. _this.BUMPDIRECTUV = 0;
  44595. _this.OBJECTSPACE_NORMALMAP = false;
  44596. _this.PARALLAX = false;
  44597. _this.PARALLAXOCCLUSION = false;
  44598. _this.NORMALXYSCALE = true;
  44599. _this.LIGHTMAP = false;
  44600. _this.LIGHTMAPDIRECTUV = 0;
  44601. _this.USELIGHTMAPASSHADOWMAP = false;
  44602. _this.GAMMALIGHTMAP = false;
  44603. _this.REFLECTION = false;
  44604. _this.REFLECTIONMAP_3D = false;
  44605. _this.REFLECTIONMAP_SPHERICAL = false;
  44606. _this.REFLECTIONMAP_PLANAR = false;
  44607. _this.REFLECTIONMAP_CUBIC = false;
  44608. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44609. _this.REFLECTIONMAP_PROJECTION = false;
  44610. _this.REFLECTIONMAP_SKYBOX = false;
  44611. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  44612. _this.REFLECTIONMAP_EXPLICIT = false;
  44613. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44614. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44615. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44616. _this.INVERTCUBICMAP = false;
  44617. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44618. _this.USESPHERICALINVERTEX = false;
  44619. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44620. _this.LODINREFLECTIONALPHA = false;
  44621. _this.GAMMAREFLECTION = false;
  44622. _this.RGBDREFLECTION = false;
  44623. _this.RADIANCEOCCLUSION = false;
  44624. _this.HORIZONOCCLUSION = false;
  44625. _this.REFRACTION = false;
  44626. _this.REFRACTIONMAP_3D = false;
  44627. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44628. _this.LODINREFRACTIONALPHA = false;
  44629. _this.GAMMAREFRACTION = false;
  44630. _this.RGBDREFRACTION = false;
  44631. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44632. _this.INSTANCES = false;
  44633. _this.NUM_BONE_INFLUENCERS = 0;
  44634. _this.BonesPerMesh = 0;
  44635. _this.NONUNIFORMSCALING = false;
  44636. _this.MORPHTARGETS = false;
  44637. _this.MORPHTARGETS_NORMAL = false;
  44638. _this.MORPHTARGETS_TANGENT = false;
  44639. _this.NUM_MORPH_INFLUENCERS = 0;
  44640. _this.IMAGEPROCESSING = false;
  44641. _this.VIGNETTE = false;
  44642. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44643. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44644. _this.TONEMAPPING = false;
  44645. _this.TONEMAPPING_ACES = false;
  44646. _this.CONTRAST = false;
  44647. _this.COLORCURVES = false;
  44648. _this.COLORGRADING = false;
  44649. _this.COLORGRADING3D = false;
  44650. _this.SAMPLER3DGREENDEPTH = false;
  44651. _this.SAMPLER3DBGRMAP = false;
  44652. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44653. _this.EXPOSURE = false;
  44654. _this.USEPHYSICALLIGHTFALLOFF = false;
  44655. _this.USEGLTFLIGHTFALLOFF = false;
  44656. _this.TWOSIDEDLIGHTING = false;
  44657. _this.SHADOWFLOAT = false;
  44658. _this.CLIPPLANE = false;
  44659. _this.CLIPPLANE2 = false;
  44660. _this.CLIPPLANE3 = false;
  44661. _this.CLIPPLANE4 = false;
  44662. _this.POINTSIZE = false;
  44663. _this.FOG = false;
  44664. _this.LOGARITHMICDEPTH = false;
  44665. _this.FORCENORMALFORWARD = false;
  44666. _this.SPECULARAA = false;
  44667. _this.UNLIT = false;
  44668. _this.rebuild();
  44669. return _this;
  44670. }
  44671. /**
  44672. * Resets the PBR Material defines.
  44673. */
  44674. PBRMaterialDefines.prototype.reset = function () {
  44675. _super.prototype.reset.call(this);
  44676. this.ALPHATESTVALUE = "0.5";
  44677. this.PBR = true;
  44678. };
  44679. return PBRMaterialDefines;
  44680. }(BABYLON.MaterialDefines));
  44681. /**
  44682. * The Physically based material base class of BJS.
  44683. *
  44684. * This offers the main features of a standard PBR material.
  44685. * For more information, please refer to the documentation :
  44686. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44687. */
  44688. var PBRBaseMaterial = /** @class */ (function (_super) {
  44689. __extends(PBRBaseMaterial, _super);
  44690. /**
  44691. * Instantiates a new PBRMaterial instance.
  44692. *
  44693. * @param name The material name
  44694. * @param scene The scene the material will be use in.
  44695. */
  44696. function PBRBaseMaterial(name, scene) {
  44697. var _this = _super.call(this, name, scene) || this;
  44698. /**
  44699. * Intensity of the direct lights e.g. the four lights available in your scene.
  44700. * This impacts both the direct diffuse and specular highlights.
  44701. */
  44702. _this._directIntensity = 1.0;
  44703. /**
  44704. * Intensity of the emissive part of the material.
  44705. * This helps controlling the emissive effect without modifying the emissive color.
  44706. */
  44707. _this._emissiveIntensity = 1.0;
  44708. /**
  44709. * Intensity of the environment e.g. how much the environment will light the object
  44710. * either through harmonics for rough material or through the refelction for shiny ones.
  44711. */
  44712. _this._environmentIntensity = 1.0;
  44713. /**
  44714. * This is a special control allowing the reduction of the specular highlights coming from the
  44715. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44716. */
  44717. _this._specularIntensity = 1.0;
  44718. /**
  44719. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44720. */
  44721. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44722. /**
  44723. * Debug Control allowing disabling the bump map on this material.
  44724. */
  44725. _this._disableBumpMap = false;
  44726. /**
  44727. * AKA Occlusion Texture Intensity in other nomenclature.
  44728. */
  44729. _this._ambientTextureStrength = 1.0;
  44730. /**
  44731. * Defines how much the AO map is occluding the analytical lights (point spot...).
  44732. * 1 means it completely occludes it
  44733. * 0 mean it has no impact
  44734. */
  44735. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  44736. /**
  44737. * The color of a material in ambient lighting.
  44738. */
  44739. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44740. /**
  44741. * AKA Diffuse Color in other nomenclature.
  44742. */
  44743. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44744. /**
  44745. * AKA Specular Color in other nomenclature.
  44746. */
  44747. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44748. /**
  44749. * The color applied when light is reflected from a material.
  44750. */
  44751. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44752. /**
  44753. * The color applied when light is emitted from a material.
  44754. */
  44755. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44756. /**
  44757. * AKA Glossiness in other nomenclature.
  44758. */
  44759. _this._microSurface = 0.9;
  44760. /**
  44761. * source material index of refraction (IOR)' / 'destination material IOR.
  44762. */
  44763. _this._indexOfRefraction = 0.66;
  44764. /**
  44765. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44766. */
  44767. _this._invertRefractionY = false;
  44768. /**
  44769. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44770. * Materials half opaque for instance using refraction could benefit from this control.
  44771. */
  44772. _this._linkRefractionWithTransparency = false;
  44773. /**
  44774. * Specifies that the material will use the light map as a show map.
  44775. */
  44776. _this._useLightmapAsShadowmap = false;
  44777. /**
  44778. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44779. * makes the reflect vector face the model (under horizon).
  44780. */
  44781. _this._useHorizonOcclusion = true;
  44782. /**
  44783. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44784. * too much the area relying on ambient texture to define their ambient occlusion.
  44785. */
  44786. _this._useRadianceOcclusion = true;
  44787. /**
  44788. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44789. */
  44790. _this._useAlphaFromAlbedoTexture = false;
  44791. /**
  44792. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44793. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44794. */
  44795. _this._useSpecularOverAlpha = true;
  44796. /**
  44797. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44798. */
  44799. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44800. /**
  44801. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44802. */
  44803. _this._useRoughnessFromMetallicTextureAlpha = true;
  44804. /**
  44805. * Specifies if the metallic texture contains the roughness information in its green channel.
  44806. */
  44807. _this._useRoughnessFromMetallicTextureGreen = false;
  44808. /**
  44809. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44810. */
  44811. _this._useMetallnessFromMetallicTextureBlue = false;
  44812. /**
  44813. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44814. */
  44815. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44816. /**
  44817. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44818. */
  44819. _this._useAmbientInGrayScale = false;
  44820. /**
  44821. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44822. * The material will try to infer what glossiness each pixel should be.
  44823. */
  44824. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44825. /**
  44826. * Defines the falloff type used in this material.
  44827. * It by default is Physical.
  44828. */
  44829. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  44830. /**
  44831. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44832. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44833. */
  44834. _this._useRadianceOverAlpha = true;
  44835. /**
  44836. * Allows using an object space normal map (instead of tangent space).
  44837. */
  44838. _this._useObjectSpaceNormalMap = false;
  44839. /**
  44840. * Allows using the bump map in parallax mode.
  44841. */
  44842. _this._useParallax = false;
  44843. /**
  44844. * Allows using the bump map in parallax occlusion mode.
  44845. */
  44846. _this._useParallaxOcclusion = false;
  44847. /**
  44848. * Controls the scale bias of the parallax mode.
  44849. */
  44850. _this._parallaxScaleBias = 0.05;
  44851. /**
  44852. * If sets to true, disables all the lights affecting the material.
  44853. */
  44854. _this._disableLighting = false;
  44855. /**
  44856. * Number of Simultaneous lights allowed on the material.
  44857. */
  44858. _this._maxSimultaneousLights = 4;
  44859. /**
  44860. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44861. */
  44862. _this._invertNormalMapX = false;
  44863. /**
  44864. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44865. */
  44866. _this._invertNormalMapY = false;
  44867. /**
  44868. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44869. */
  44870. _this._twoSidedLighting = false;
  44871. /**
  44872. * Defines the alpha limits in alpha test mode.
  44873. */
  44874. _this._alphaCutOff = 0.4;
  44875. /**
  44876. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44877. */
  44878. _this._forceAlphaTest = false;
  44879. /**
  44880. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44881. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44882. */
  44883. _this._useAlphaFresnel = false;
  44884. /**
  44885. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44886. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44887. */
  44888. _this._useLinearAlphaFresnel = false;
  44889. /**
  44890. * The transparency mode of the material.
  44891. */
  44892. _this._transparencyMode = null;
  44893. /**
  44894. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44895. * from cos thetav and roughness:
  44896. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44897. */
  44898. _this._environmentBRDFTexture = null;
  44899. /**
  44900. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44901. */
  44902. _this._forceIrradianceInFragment = false;
  44903. /**
  44904. * Force normal to face away from face.
  44905. */
  44906. _this._forceNormalForward = false;
  44907. /**
  44908. * Enables specular anti aliasing in the PBR shader.
  44909. * It will both interacts on the Geometry for analytical and IBL lighting.
  44910. * It also prefilter the roughness map based on the bump values.
  44911. */
  44912. _this._enableSpecularAntiAliasing = false;
  44913. /**
  44914. * Stores the available render targets.
  44915. */
  44916. _this._renderTargets = new BABYLON.SmartArray(16);
  44917. /**
  44918. * Sets the global ambient color for the material used in lighting calculations.
  44919. */
  44920. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44921. /**
  44922. * If set to true, no lighting calculations will be applied.
  44923. */
  44924. _this._unlit = false;
  44925. // Setup the default processing configuration to the scene.
  44926. _this._attachImageProcessingConfiguration(null);
  44927. _this.getRenderTargetTextures = function () {
  44928. _this._renderTargets.reset();
  44929. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44930. _this._renderTargets.push(_this._reflectionTexture);
  44931. }
  44932. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44933. _this._renderTargets.push(_this._refractionTexture);
  44934. }
  44935. return _this._renderTargets;
  44936. };
  44937. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44938. return _this;
  44939. }
  44940. /**
  44941. * Attaches a new image processing configuration to the PBR Material.
  44942. * @param configuration
  44943. */
  44944. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44945. var _this = this;
  44946. if (configuration === this._imageProcessingConfiguration) {
  44947. return;
  44948. }
  44949. // Detaches observer.
  44950. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44951. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44952. }
  44953. // Pick the scene configuration if needed.
  44954. if (!configuration) {
  44955. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44956. }
  44957. else {
  44958. this._imageProcessingConfiguration = configuration;
  44959. }
  44960. // Attaches observer.
  44961. if (this._imageProcessingConfiguration) {
  44962. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44963. _this._markAllSubMeshesAsImageProcessingDirty();
  44964. });
  44965. }
  44966. };
  44967. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  44968. /**
  44969. * Gets a boolean indicating that current material needs to register RTT
  44970. */
  44971. get: function () {
  44972. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44973. return true;
  44974. }
  44975. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44976. return true;
  44977. }
  44978. return false;
  44979. },
  44980. enumerable: true,
  44981. configurable: true
  44982. });
  44983. /**
  44984. * Gets the name of the material class.
  44985. */
  44986. PBRBaseMaterial.prototype.getClassName = function () {
  44987. return "PBRBaseMaterial";
  44988. };
  44989. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44990. /**
  44991. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44992. */
  44993. get: function () {
  44994. return this._useLogarithmicDepth;
  44995. },
  44996. /**
  44997. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44998. */
  44999. set: function (value) {
  45000. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  45001. },
  45002. enumerable: true,
  45003. configurable: true
  45004. });
  45005. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  45006. /**
  45007. * Gets the current transparency mode.
  45008. */
  45009. get: function () {
  45010. return this._transparencyMode;
  45011. },
  45012. /**
  45013. * Sets the transparency mode of the material.
  45014. *
  45015. * | Value | Type | Description |
  45016. * | ----- | ----------------------------------- | ----------- |
  45017. * | 0 | OPAQUE | |
  45018. * | 1 | ALPHATEST | |
  45019. * | 2 | ALPHABLEND | |
  45020. * | 3 | ALPHATESTANDBLEND | |
  45021. *
  45022. */
  45023. set: function (value) {
  45024. if (this._transparencyMode === value) {
  45025. return;
  45026. }
  45027. this._transparencyMode = value;
  45028. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  45029. this._markAllSubMeshesAsTexturesAndMiscDirty();
  45030. },
  45031. enumerable: true,
  45032. configurable: true
  45033. });
  45034. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  45035. /**
  45036. * Returns true if alpha blending should be disabled.
  45037. */
  45038. get: function () {
  45039. return (this._linkRefractionWithTransparency ||
  45040. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  45041. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45042. },
  45043. enumerable: true,
  45044. configurable: true
  45045. });
  45046. /**
  45047. * Specifies whether or not this material should be rendered in alpha blend mode.
  45048. */
  45049. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  45050. if (this._disableAlphaBlending) {
  45051. return false;
  45052. }
  45053. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  45054. };
  45055. /**
  45056. * Specifies if the mesh will require alpha blending.
  45057. * @param mesh - BJS mesh.
  45058. */
  45059. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  45060. if (this._disableAlphaBlending) {
  45061. return false;
  45062. }
  45063. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  45064. };
  45065. /**
  45066. * Specifies whether or not this material should be rendered in alpha test mode.
  45067. */
  45068. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  45069. if (this._forceAlphaTest) {
  45070. return true;
  45071. }
  45072. if (this._linkRefractionWithTransparency) {
  45073. return false;
  45074. }
  45075. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45076. };
  45077. /**
  45078. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  45079. */
  45080. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  45081. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  45082. };
  45083. /**
  45084. * Gets the texture used for the alpha test.
  45085. */
  45086. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  45087. return this._albedoTexture;
  45088. };
  45089. /**
  45090. * Specifies that the submesh is ready to be used.
  45091. * @param mesh - BJS mesh.
  45092. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  45093. * @param useInstances - Specifies that instances should be used.
  45094. * @returns - boolean indicating that the submesh is ready or not.
  45095. */
  45096. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  45097. if (subMesh.effect && this.isFrozen) {
  45098. if (this._wasPreviouslyReady) {
  45099. return true;
  45100. }
  45101. }
  45102. if (!subMesh._materialDefines) {
  45103. subMesh._materialDefines = new PBRMaterialDefines();
  45104. }
  45105. var defines = subMesh._materialDefines;
  45106. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  45107. if (defines._renderId === this.getScene().getRenderId()) {
  45108. return true;
  45109. }
  45110. }
  45111. var scene = this.getScene();
  45112. var engine = scene.getEngine();
  45113. if (defines._areTexturesDirty) {
  45114. if (scene.texturesEnabled) {
  45115. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45116. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  45117. return false;
  45118. }
  45119. }
  45120. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45121. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  45122. return false;
  45123. }
  45124. }
  45125. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45126. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  45127. return false;
  45128. }
  45129. }
  45130. var reflectionTexture = this._getReflectionTexture();
  45131. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45132. if (!reflectionTexture.isReadyOrNotBlocking()) {
  45133. return false;
  45134. }
  45135. }
  45136. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45137. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  45138. return false;
  45139. }
  45140. }
  45141. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45142. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  45143. return false;
  45144. }
  45145. }
  45146. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45147. if (this._metallicTexture) {
  45148. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  45149. return false;
  45150. }
  45151. }
  45152. else if (this._reflectivityTexture) {
  45153. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  45154. return false;
  45155. }
  45156. }
  45157. if (this._microSurfaceTexture) {
  45158. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  45159. return false;
  45160. }
  45161. }
  45162. }
  45163. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45164. // Bump texture cannot be not blocking.
  45165. if (!this._bumpTexture.isReady()) {
  45166. return false;
  45167. }
  45168. }
  45169. var refractionTexture = this._getRefractionTexture();
  45170. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45171. if (!refractionTexture.isReadyOrNotBlocking()) {
  45172. return false;
  45173. }
  45174. }
  45175. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45176. // This is blocking.
  45177. if (!this._environmentBRDFTexture.isReady()) {
  45178. return false;
  45179. }
  45180. }
  45181. }
  45182. }
  45183. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  45184. if (!this._imageProcessingConfiguration.isReady()) {
  45185. return false;
  45186. }
  45187. }
  45188. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45189. mesh.createNormals(true);
  45190. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  45191. }
  45192. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  45193. if (effect) {
  45194. scene.resetCachedMaterial();
  45195. subMesh.setEffect(effect, defines);
  45196. this.buildUniformLayout();
  45197. }
  45198. if (!subMesh.effect || !subMesh.effect.isReady()) {
  45199. return false;
  45200. }
  45201. defines._renderId = scene.getRenderId();
  45202. this._wasPreviouslyReady = true;
  45203. return true;
  45204. };
  45205. /**
  45206. * Specifies if the material uses metallic roughness workflow.
  45207. * @returns boolean specifiying if the material uses metallic roughness workflow.
  45208. */
  45209. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  45210. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  45211. return true;
  45212. }
  45213. return false;
  45214. };
  45215. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  45216. if (onCompiled === void 0) { onCompiled = null; }
  45217. if (onError === void 0) { onError = null; }
  45218. if (useInstances === void 0) { useInstances = null; }
  45219. if (useClipPlane === void 0) { useClipPlane = null; }
  45220. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  45221. if (!defines.isDirty) {
  45222. return null;
  45223. }
  45224. defines.markAsProcessed();
  45225. var scene = this.getScene();
  45226. var engine = scene.getEngine();
  45227. // Fallbacks
  45228. var fallbacks = new BABYLON.EffectFallbacks();
  45229. var fallbackRank = 0;
  45230. if (defines.USESPHERICALINVERTEX) {
  45231. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  45232. }
  45233. if (defines.FOG) {
  45234. fallbacks.addFallback(fallbackRank, "FOG");
  45235. }
  45236. if (defines.SPECULARAA) {
  45237. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  45238. }
  45239. if (defines.POINTSIZE) {
  45240. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  45241. }
  45242. if (defines.LOGARITHMICDEPTH) {
  45243. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  45244. }
  45245. if (defines.PARALLAX) {
  45246. fallbacks.addFallback(fallbackRank, "PARALLAX");
  45247. }
  45248. if (defines.PARALLAXOCCLUSION) {
  45249. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  45250. }
  45251. if (defines.ENVIRONMENTBRDF) {
  45252. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  45253. }
  45254. if (defines.TANGENT) {
  45255. fallbacks.addFallback(fallbackRank++, "TANGENT");
  45256. }
  45257. if (defines.BUMP) {
  45258. fallbacks.addFallback(fallbackRank++, "BUMP");
  45259. }
  45260. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  45261. if (defines.SPECULARTERM) {
  45262. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  45263. }
  45264. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  45265. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  45266. }
  45267. if (defines.LIGHTMAP) {
  45268. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  45269. }
  45270. if (defines.NORMAL) {
  45271. fallbacks.addFallback(fallbackRank++, "NORMAL");
  45272. }
  45273. if (defines.AMBIENT) {
  45274. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  45275. }
  45276. if (defines.EMISSIVE) {
  45277. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  45278. }
  45279. if (defines.VERTEXCOLOR) {
  45280. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  45281. }
  45282. if (defines.NUM_BONE_INFLUENCERS > 0) {
  45283. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  45284. }
  45285. if (defines.MORPHTARGETS) {
  45286. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  45287. }
  45288. //Attributes
  45289. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45290. if (defines.NORMAL) {
  45291. attribs.push(BABYLON.VertexBuffer.NormalKind);
  45292. }
  45293. if (defines.TANGENT) {
  45294. attribs.push(BABYLON.VertexBuffer.TangentKind);
  45295. }
  45296. if (defines.UV1) {
  45297. attribs.push(BABYLON.VertexBuffer.UVKind);
  45298. }
  45299. if (defines.UV2) {
  45300. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45301. }
  45302. if (defines.VERTEXCOLOR) {
  45303. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45304. }
  45305. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  45306. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  45307. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  45308. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45309. "vFogInfos", "vFogColor", "pointSize",
  45310. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  45311. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45312. "mBones",
  45313. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45314. "vLightingIntensity",
  45315. "logarithmicDepthConstant",
  45316. "vSphericalX", "vSphericalY", "vSphericalZ",
  45317. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45318. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45319. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  45320. "vTangentSpaceParams"
  45321. ];
  45322. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  45323. "bumpSampler", "lightmapSampler", "opacitySampler",
  45324. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  45325. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  45326. "microSurfaceSampler", "environmentBrdfSampler"];
  45327. var uniformBuffers = ["Material", "Scene"];
  45328. if (BABYLON.ImageProcessingConfiguration) {
  45329. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  45330. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  45331. }
  45332. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  45333. uniformsNames: uniforms,
  45334. uniformBuffersNames: uniformBuffers,
  45335. samplers: samplers,
  45336. defines: defines,
  45337. maxSimultaneousLights: this._maxSimultaneousLights
  45338. });
  45339. var join = defines.toString();
  45340. return engine.createEffect("pbr", {
  45341. attributes: attribs,
  45342. uniformsNames: uniforms,
  45343. uniformBuffersNames: uniformBuffers,
  45344. samplers: samplers,
  45345. defines: join,
  45346. fallbacks: fallbacks,
  45347. onCompiled: onCompiled,
  45348. onError: onError,
  45349. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  45350. }, engine);
  45351. };
  45352. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  45353. if (useInstances === void 0) { useInstances = null; }
  45354. if (useClipPlane === void 0) { useClipPlane = null; }
  45355. var scene = this.getScene();
  45356. var engine = scene.getEngine();
  45357. // Lights
  45358. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  45359. defines._needNormals = true;
  45360. // Textures
  45361. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  45362. if (defines._areTexturesDirty) {
  45363. defines._needUVs = false;
  45364. if (scene.texturesEnabled) {
  45365. if (scene.getEngine().getCaps().textureLOD) {
  45366. defines.LODBASEDMICROSFURACE = true;
  45367. }
  45368. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45369. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45370. }
  45371. else {
  45372. defines.ALBEDO = false;
  45373. }
  45374. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45375. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45376. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45377. }
  45378. else {
  45379. defines.AMBIENT = false;
  45380. }
  45381. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45382. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45383. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45384. }
  45385. else {
  45386. defines.OPACITY = false;
  45387. }
  45388. var reflectionTexture = this._getReflectionTexture();
  45389. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45390. defines.REFLECTION = true;
  45391. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45392. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  45393. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45394. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45395. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45396. defines.INVERTCUBICMAP = true;
  45397. }
  45398. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45399. switch (reflectionTexture.coordinatesMode) {
  45400. case BABYLON.Texture.EXPLICIT_MODE:
  45401. defines.REFLECTIONMAP_EXPLICIT = true;
  45402. break;
  45403. case BABYLON.Texture.PLANAR_MODE:
  45404. defines.REFLECTIONMAP_PLANAR = true;
  45405. break;
  45406. case BABYLON.Texture.PROJECTION_MODE:
  45407. defines.REFLECTIONMAP_PROJECTION = true;
  45408. break;
  45409. case BABYLON.Texture.SKYBOX_MODE:
  45410. defines.REFLECTIONMAP_SKYBOX = true;
  45411. break;
  45412. case BABYLON.Texture.SPHERICAL_MODE:
  45413. defines.REFLECTIONMAP_SPHERICAL = true;
  45414. break;
  45415. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45416. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45417. break;
  45418. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45419. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45420. break;
  45421. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45422. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45423. break;
  45424. case BABYLON.Texture.CUBIC_MODE:
  45425. case BABYLON.Texture.INVCUBIC_MODE:
  45426. default:
  45427. defines.REFLECTIONMAP_CUBIC = true;
  45428. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45429. break;
  45430. }
  45431. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45432. if (reflectionTexture.sphericalPolynomial) {
  45433. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45434. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45435. defines.USESPHERICALINVERTEX = false;
  45436. }
  45437. else {
  45438. defines.USESPHERICALINVERTEX = true;
  45439. }
  45440. }
  45441. }
  45442. else {
  45443. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  45444. }
  45445. }
  45446. else {
  45447. defines.REFLECTION = false;
  45448. defines.REFLECTIONMAP_3D = false;
  45449. defines.REFLECTIONMAP_SPHERICAL = false;
  45450. defines.REFLECTIONMAP_PLANAR = false;
  45451. defines.REFLECTIONMAP_CUBIC = false;
  45452. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45453. defines.REFLECTIONMAP_PROJECTION = false;
  45454. defines.REFLECTIONMAP_SKYBOX = false;
  45455. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  45456. defines.REFLECTIONMAP_EXPLICIT = false;
  45457. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45458. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45459. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45460. defines.INVERTCUBICMAP = false;
  45461. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45462. defines.USESPHERICALINVERTEX = false;
  45463. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45464. defines.LODINREFLECTIONALPHA = false;
  45465. defines.GAMMAREFLECTION = false;
  45466. defines.RGBDREFLECTION = false;
  45467. }
  45468. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45469. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45470. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45471. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45472. }
  45473. else {
  45474. defines.LIGHTMAP = false;
  45475. }
  45476. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45477. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45478. }
  45479. else {
  45480. defines.EMISSIVE = false;
  45481. }
  45482. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45483. if (this._metallicTexture) {
  45484. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45485. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45486. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45487. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45488. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45489. }
  45490. else if (this._reflectivityTexture) {
  45491. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45492. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45493. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45494. }
  45495. else {
  45496. defines.REFLECTIVITY = false;
  45497. }
  45498. if (this._microSurfaceTexture) {
  45499. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45500. }
  45501. else {
  45502. defines.MICROSURFACEMAP = false;
  45503. }
  45504. }
  45505. else {
  45506. defines.REFLECTIVITY = false;
  45507. defines.MICROSURFACEMAP = false;
  45508. }
  45509. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45510. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45511. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45512. defines.PARALLAX = true;
  45513. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45514. }
  45515. else {
  45516. defines.PARALLAX = false;
  45517. }
  45518. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45519. }
  45520. else {
  45521. defines.BUMP = false;
  45522. }
  45523. var refractionTexture = this._getRefractionTexture();
  45524. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45525. defines.REFRACTION = true;
  45526. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45527. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45528. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  45529. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45530. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45531. if (this._linkRefractionWithTransparency) {
  45532. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45533. }
  45534. }
  45535. else {
  45536. defines.REFRACTION = false;
  45537. }
  45538. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45539. defines.ENVIRONMENTBRDF = true;
  45540. }
  45541. else {
  45542. defines.ENVIRONMENTBRDF = false;
  45543. }
  45544. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45545. defines.ALPHAFROMALBEDO = true;
  45546. }
  45547. else {
  45548. defines.ALPHAFROMALBEDO = false;
  45549. }
  45550. }
  45551. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45552. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  45553. defines.USEPHYSICALLIGHTFALLOFF = false;
  45554. defines.USEGLTFLIGHTFALLOFF = false;
  45555. }
  45556. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  45557. defines.USEPHYSICALLIGHTFALLOFF = false;
  45558. defines.USEGLTFLIGHTFALLOFF = true;
  45559. }
  45560. else {
  45561. defines.USEPHYSICALLIGHTFALLOFF = true;
  45562. defines.USEGLTFLIGHTFALLOFF = false;
  45563. }
  45564. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45565. if (!this.backFaceCulling && this._twoSidedLighting) {
  45566. defines.TWOSIDEDLIGHTING = true;
  45567. }
  45568. else {
  45569. defines.TWOSIDEDLIGHTING = false;
  45570. }
  45571. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45572. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45573. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45574. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45575. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45576. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45577. }
  45578. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  45579. this._imageProcessingConfiguration.prepareDefines(defines);
  45580. }
  45581. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45582. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45583. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45584. // Misc.
  45585. if (defines._areMiscDirty) {
  45586. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45587. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45588. }
  45589. // Values that need to be evaluated on every frame
  45590. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45591. // Attribs
  45592. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45593. };
  45594. /**
  45595. * Force shader compilation
  45596. */
  45597. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45598. var _this = this;
  45599. var localOptions = __assign({ clipPlane: false }, options);
  45600. var defines = new PBRMaterialDefines();
  45601. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45602. if (effect.isReady()) {
  45603. if (onCompiled) {
  45604. onCompiled(this);
  45605. }
  45606. }
  45607. else {
  45608. effect.onCompileObservable.add(function () {
  45609. if (onCompiled) {
  45610. onCompiled(_this);
  45611. }
  45612. });
  45613. }
  45614. };
  45615. /**
  45616. * Initializes the uniform buffer layout for the shader.
  45617. */
  45618. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45619. // Order is important !
  45620. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45621. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  45622. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45623. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45624. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45625. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45626. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45627. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45628. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45629. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45630. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45631. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45632. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45633. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45634. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45635. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45636. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45637. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45638. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45639. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45640. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45641. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45642. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45643. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45644. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45645. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45646. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45647. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45648. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45649. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45650. this._uniformBuffer.addUniform("pointSize", 1);
  45651. this._uniformBuffer.create();
  45652. };
  45653. /**
  45654. * Unbinds the textures.
  45655. */
  45656. PBRBaseMaterial.prototype.unbind = function () {
  45657. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45658. this._uniformBuffer.setTexture("reflectionSampler", null);
  45659. }
  45660. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45661. this._uniformBuffer.setTexture("refractionSampler", null);
  45662. }
  45663. _super.prototype.unbind.call(this);
  45664. };
  45665. /**
  45666. * Binds the submesh data.
  45667. * @param world - The world matrix.
  45668. * @param mesh - The BJS mesh.
  45669. * @param subMesh - A submesh of the BJS mesh.
  45670. */
  45671. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45672. var scene = this.getScene();
  45673. var defines = subMesh._materialDefines;
  45674. if (!defines) {
  45675. return;
  45676. }
  45677. var effect = subMesh.effect;
  45678. if (!effect) {
  45679. return;
  45680. }
  45681. this._activeEffect = effect;
  45682. // Matrices
  45683. this.bindOnlyWorldMatrix(world);
  45684. // Normal Matrix
  45685. if (defines.OBJECTSPACE_NORMALMAP) {
  45686. world.toNormalMatrix(this._normalMatrix);
  45687. this.bindOnlyNormalMatrix(this._normalMatrix);
  45688. }
  45689. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45690. // Bones
  45691. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45692. var reflectionTexture = null;
  45693. if (mustRebind) {
  45694. this._uniformBuffer.bindToEffect(effect, "Material");
  45695. this.bindViewProjection(effect);
  45696. reflectionTexture = this._getReflectionTexture();
  45697. var refractionTexture = this._getRefractionTexture();
  45698. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45699. // Texture uniforms
  45700. if (scene.texturesEnabled) {
  45701. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45702. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45703. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45704. }
  45705. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45706. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  45707. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45708. }
  45709. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45710. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45711. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45712. }
  45713. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45714. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45715. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45716. if (reflectionTexture.boundingBoxSize) {
  45717. var cubeTexture = reflectionTexture;
  45718. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45719. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45720. }
  45721. var polynomials = reflectionTexture.sphericalPolynomial;
  45722. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45723. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45724. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45725. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45726. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45727. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45728. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45729. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45730. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45731. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45732. }
  45733. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45734. }
  45735. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45736. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45737. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45738. }
  45739. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45740. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45741. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45742. }
  45743. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45744. if (this._metallicTexture) {
  45745. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45746. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45747. }
  45748. else if (this._reflectivityTexture) {
  45749. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45750. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45751. }
  45752. if (this._microSurfaceTexture) {
  45753. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45754. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45755. }
  45756. }
  45757. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45758. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45759. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45760. if (scene._mirroredCameraPosition) {
  45761. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45762. }
  45763. else {
  45764. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45765. }
  45766. }
  45767. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45768. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45769. var depth = 1.0;
  45770. if (!refractionTexture.isCube) {
  45771. if (refractionTexture.depth) {
  45772. depth = refractionTexture.depth;
  45773. }
  45774. }
  45775. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45776. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45777. }
  45778. }
  45779. // Point size
  45780. if (this.pointsCloud) {
  45781. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45782. }
  45783. // Colors
  45784. if (defines.METALLICWORKFLOW) {
  45785. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45786. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45787. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45788. }
  45789. else {
  45790. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45791. }
  45792. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45793. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45794. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45795. // Misc
  45796. this._lightingInfos.x = this._directIntensity;
  45797. this._lightingInfos.y = this._emissiveIntensity;
  45798. this._lightingInfos.z = this._environmentIntensity;
  45799. this._lightingInfos.w = this._specularIntensity;
  45800. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45801. }
  45802. // Textures
  45803. if (scene.texturesEnabled) {
  45804. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45805. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45806. }
  45807. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45808. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45809. }
  45810. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45811. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45812. }
  45813. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45814. if (defines.LODBASEDMICROSFURACE) {
  45815. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45816. }
  45817. else {
  45818. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45819. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45820. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45821. }
  45822. }
  45823. if (defines.ENVIRONMENTBRDF) {
  45824. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45825. }
  45826. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45827. if (defines.LODBASEDMICROSFURACE) {
  45828. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45829. }
  45830. else {
  45831. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45832. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45833. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45834. }
  45835. }
  45836. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45837. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45838. }
  45839. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45840. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45841. }
  45842. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45843. if (this._metallicTexture) {
  45844. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45845. }
  45846. else if (this._reflectivityTexture) {
  45847. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45848. }
  45849. if (this._microSurfaceTexture) {
  45850. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45851. }
  45852. }
  45853. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45854. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45855. }
  45856. }
  45857. // Clip plane
  45858. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45859. // Colors
  45860. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45861. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45862. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45863. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45864. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45865. }
  45866. if (mustRebind || !this.isFrozen) {
  45867. // Lights
  45868. if (scene.lightsEnabled && !this._disableLighting) {
  45869. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  45870. }
  45871. // View
  45872. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45873. this.bindView(effect);
  45874. }
  45875. // Fog
  45876. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  45877. // Morph targets
  45878. if (defines.NUM_MORPH_INFLUENCERS) {
  45879. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45880. }
  45881. // image processing
  45882. this._imageProcessingConfiguration.bind(this._activeEffect);
  45883. // Log. depth
  45884. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45885. }
  45886. this._uniformBuffer.update();
  45887. this._afterBind(mesh, this._activeEffect);
  45888. };
  45889. /**
  45890. * Returns the animatable textures.
  45891. * @returns - Array of animatable textures.
  45892. */
  45893. PBRBaseMaterial.prototype.getAnimatables = function () {
  45894. var results = [];
  45895. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45896. results.push(this._albedoTexture);
  45897. }
  45898. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45899. results.push(this._ambientTexture);
  45900. }
  45901. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45902. results.push(this._opacityTexture);
  45903. }
  45904. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45905. results.push(this._reflectionTexture);
  45906. }
  45907. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45908. results.push(this._emissiveTexture);
  45909. }
  45910. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45911. results.push(this._metallicTexture);
  45912. }
  45913. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45914. results.push(this._reflectivityTexture);
  45915. }
  45916. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45917. results.push(this._bumpTexture);
  45918. }
  45919. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45920. results.push(this._lightmapTexture);
  45921. }
  45922. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45923. results.push(this._refractionTexture);
  45924. }
  45925. return results;
  45926. };
  45927. /**
  45928. * Returns the texture used for reflections.
  45929. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45930. */
  45931. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45932. if (this._reflectionTexture) {
  45933. return this._reflectionTexture;
  45934. }
  45935. return this.getScene().environmentTexture;
  45936. };
  45937. /**
  45938. * Returns the texture used for refraction or null if none is used.
  45939. * @returns - Refection texture if present. If no refraction texture and refraction
  45940. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45941. */
  45942. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45943. if (this._refractionTexture) {
  45944. return this._refractionTexture;
  45945. }
  45946. if (this._linkRefractionWithTransparency) {
  45947. return this.getScene().environmentTexture;
  45948. }
  45949. return null;
  45950. };
  45951. /**
  45952. * Disposes the resources of the material.
  45953. * @param forceDisposeEffect - Forces the disposal of effects.
  45954. * @param forceDisposeTextures - Forces the disposal of all textures.
  45955. */
  45956. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45957. if (forceDisposeTextures) {
  45958. if (this._albedoTexture) {
  45959. this._albedoTexture.dispose();
  45960. }
  45961. if (this._ambientTexture) {
  45962. this._ambientTexture.dispose();
  45963. }
  45964. if (this._opacityTexture) {
  45965. this._opacityTexture.dispose();
  45966. }
  45967. if (this._reflectionTexture) {
  45968. this._reflectionTexture.dispose();
  45969. }
  45970. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45971. this._environmentBRDFTexture.dispose();
  45972. }
  45973. if (this._emissiveTexture) {
  45974. this._emissiveTexture.dispose();
  45975. }
  45976. if (this._metallicTexture) {
  45977. this._metallicTexture.dispose();
  45978. }
  45979. if (this._reflectivityTexture) {
  45980. this._reflectivityTexture.dispose();
  45981. }
  45982. if (this._bumpTexture) {
  45983. this._bumpTexture.dispose();
  45984. }
  45985. if (this._lightmapTexture) {
  45986. this._lightmapTexture.dispose();
  45987. }
  45988. if (this._refractionTexture) {
  45989. this._refractionTexture.dispose();
  45990. }
  45991. }
  45992. this._renderTargets.dispose();
  45993. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45994. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45995. }
  45996. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45997. };
  45998. /**
  45999. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  46000. */
  46001. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  46002. /**
  46003. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  46004. * to enhance interoperability with other engines.
  46005. */
  46006. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  46007. /**
  46008. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  46009. * to enhance interoperability with other materials.
  46010. */
  46011. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  46012. /**
  46013. * Stores the reflectivity values based on metallic roughness workflow.
  46014. */
  46015. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  46016. __decorate([
  46017. BABYLON.serializeAsImageProcessingConfiguration()
  46018. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  46019. __decorate([
  46020. BABYLON.serialize()
  46021. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  46022. __decorate([
  46023. BABYLON.serialize()
  46024. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  46025. return PBRBaseMaterial;
  46026. }(BABYLON.PushMaterial));
  46027. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  46028. })(BABYLON || (BABYLON = {}));
  46029. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  46030. var BABYLON;
  46031. (function (BABYLON) {
  46032. /**
  46033. * The Physically based simple base material of BJS.
  46034. *
  46035. * This enables better naming and convention enforcements on top of the pbrMaterial.
  46036. * It is used as the base class for both the specGloss and metalRough conventions.
  46037. */
  46038. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  46039. __extends(PBRBaseSimpleMaterial, _super);
  46040. /**
  46041. * Instantiates a new PBRMaterial instance.
  46042. *
  46043. * @param name The material name
  46044. * @param scene The scene the material will be use in.
  46045. */
  46046. function PBRBaseSimpleMaterial(name, scene) {
  46047. var _this = _super.call(this, name, scene) || this;
  46048. /**
  46049. * Number of Simultaneous lights allowed on the material.
  46050. */
  46051. _this.maxSimultaneousLights = 4;
  46052. /**
  46053. * If sets to true, disables all the lights affecting the material.
  46054. */
  46055. _this.disableLighting = false;
  46056. /**
  46057. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46058. */
  46059. _this.invertNormalMapX = false;
  46060. /**
  46061. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46062. */
  46063. _this.invertNormalMapY = false;
  46064. /**
  46065. * Emissivie color used to self-illuminate the model.
  46066. */
  46067. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46068. /**
  46069. * Occlusion Channel Strenght.
  46070. */
  46071. _this.occlusionStrength = 1.0;
  46072. /**
  46073. * If true, the light map contains occlusion information instead of lighting info.
  46074. */
  46075. _this.useLightmapAsShadowmap = false;
  46076. _this._useAlphaFromAlbedoTexture = true;
  46077. _this._useAmbientInGrayScale = true;
  46078. return _this;
  46079. }
  46080. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  46081. /**
  46082. * Gets the current double sided mode.
  46083. */
  46084. get: function () {
  46085. return this._twoSidedLighting;
  46086. },
  46087. /**
  46088. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46089. */
  46090. set: function (value) {
  46091. if (this._twoSidedLighting === value) {
  46092. return;
  46093. }
  46094. this._twoSidedLighting = value;
  46095. this.backFaceCulling = !value;
  46096. this._markAllSubMeshesAsTexturesDirty();
  46097. },
  46098. enumerable: true,
  46099. configurable: true
  46100. });
  46101. /**
  46102. * Return the active textures of the material.
  46103. */
  46104. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  46105. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46106. if (this.environmentTexture) {
  46107. activeTextures.push(this.environmentTexture);
  46108. }
  46109. if (this.normalTexture) {
  46110. activeTextures.push(this.normalTexture);
  46111. }
  46112. if (this.emissiveTexture) {
  46113. activeTextures.push(this.emissiveTexture);
  46114. }
  46115. if (this.occlusionTexture) {
  46116. activeTextures.push(this.occlusionTexture);
  46117. }
  46118. if (this.lightmapTexture) {
  46119. activeTextures.push(this.lightmapTexture);
  46120. }
  46121. return activeTextures;
  46122. };
  46123. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  46124. if (_super.prototype.hasTexture.call(this, texture)) {
  46125. return true;
  46126. }
  46127. if (this.lightmapTexture === texture) {
  46128. return true;
  46129. }
  46130. return false;
  46131. };
  46132. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  46133. return "PBRBaseSimpleMaterial";
  46134. };
  46135. __decorate([
  46136. BABYLON.serialize(),
  46137. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46138. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  46139. __decorate([
  46140. BABYLON.serialize(),
  46141. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46142. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  46143. __decorate([
  46144. BABYLON.serializeAsTexture(),
  46145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  46146. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  46147. __decorate([
  46148. BABYLON.serialize(),
  46149. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46150. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  46151. __decorate([
  46152. BABYLON.serialize(),
  46153. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46154. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  46155. __decorate([
  46156. BABYLON.serializeAsTexture(),
  46157. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  46158. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  46159. __decorate([
  46160. BABYLON.serializeAsColor3("emissive"),
  46161. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46162. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  46163. __decorate([
  46164. BABYLON.serializeAsTexture(),
  46165. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46166. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  46167. __decorate([
  46168. BABYLON.serialize(),
  46169. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  46170. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  46171. __decorate([
  46172. BABYLON.serializeAsTexture(),
  46173. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  46174. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  46175. __decorate([
  46176. BABYLON.serialize(),
  46177. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  46178. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  46179. __decorate([
  46180. BABYLON.serialize()
  46181. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  46182. __decorate([
  46183. BABYLON.serializeAsTexture(),
  46184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46185. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  46186. __decorate([
  46187. BABYLON.serialize(),
  46188. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46189. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46190. return PBRBaseSimpleMaterial;
  46191. }(BABYLON.PBRBaseMaterial));
  46192. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  46193. })(BABYLON || (BABYLON = {}));
  46194. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  46195. var BABYLON;
  46196. (function (BABYLON) {
  46197. /**
  46198. * The Physically based material of BJS.
  46199. *
  46200. * This offers the main features of a standard PBR material.
  46201. * For more information, please refer to the documentation :
  46202. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  46203. */
  46204. var PBRMaterial = /** @class */ (function (_super) {
  46205. __extends(PBRMaterial, _super);
  46206. /**
  46207. * Instantiates a new PBRMaterial instance.
  46208. *
  46209. * @param name The material name
  46210. * @param scene The scene the material will be use in.
  46211. */
  46212. function PBRMaterial(name, scene) {
  46213. var _this = _super.call(this, name, scene) || this;
  46214. /**
  46215. * Intensity of the direct lights e.g. the four lights available in your scene.
  46216. * This impacts both the direct diffuse and specular highlights.
  46217. */
  46218. _this.directIntensity = 1.0;
  46219. /**
  46220. * Intensity of the emissive part of the material.
  46221. * This helps controlling the emissive effect without modifying the emissive color.
  46222. */
  46223. _this.emissiveIntensity = 1.0;
  46224. /**
  46225. * Intensity of the environment e.g. how much the environment will light the object
  46226. * either through harmonics for rough material or through the refelction for shiny ones.
  46227. */
  46228. _this.environmentIntensity = 1.0;
  46229. /**
  46230. * This is a special control allowing the reduction of the specular highlights coming from the
  46231. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  46232. */
  46233. _this.specularIntensity = 1.0;
  46234. /**
  46235. * Debug Control allowing disabling the bump map on this material.
  46236. */
  46237. _this.disableBumpMap = false;
  46238. /**
  46239. * AKA Occlusion Texture Intensity in other nomenclature.
  46240. */
  46241. _this.ambientTextureStrength = 1.0;
  46242. /**
  46243. * Defines how much the AO map is occluding the analytical lights (point spot...).
  46244. * 1 means it completely occludes it
  46245. * 0 mean it has no impact
  46246. */
  46247. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  46248. /**
  46249. * The color of a material in ambient lighting.
  46250. */
  46251. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  46252. /**
  46253. * AKA Diffuse Color in other nomenclature.
  46254. */
  46255. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  46256. /**
  46257. * AKA Specular Color in other nomenclature.
  46258. */
  46259. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  46260. /**
  46261. * The color reflected from the material.
  46262. */
  46263. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  46264. /**
  46265. * The color emitted from the material.
  46266. */
  46267. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46268. /**
  46269. * AKA Glossiness in other nomenclature.
  46270. */
  46271. _this.microSurface = 1.0;
  46272. /**
  46273. * source material index of refraction (IOR)' / 'destination material IOR.
  46274. */
  46275. _this.indexOfRefraction = 0.66;
  46276. /**
  46277. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  46278. */
  46279. _this.invertRefractionY = false;
  46280. /**
  46281. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  46282. * Materials half opaque for instance using refraction could benefit from this control.
  46283. */
  46284. _this.linkRefractionWithTransparency = false;
  46285. /**
  46286. * If true, the light map contains occlusion information instead of lighting info.
  46287. */
  46288. _this.useLightmapAsShadowmap = false;
  46289. /**
  46290. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  46291. */
  46292. _this.useAlphaFromAlbedoTexture = false;
  46293. /**
  46294. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  46295. */
  46296. _this.forceAlphaTest = false;
  46297. /**
  46298. * Defines the alpha limits in alpha test mode.
  46299. */
  46300. _this.alphaCutOff = 0.4;
  46301. /**
  46302. * Specifies that the material will keep the specular highlights over a transparent surface (only the most limunous ones).
  46303. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  46304. */
  46305. _this.useSpecularOverAlpha = true;
  46306. /**
  46307. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  46308. */
  46309. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  46310. /**
  46311. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  46312. */
  46313. _this.useRoughnessFromMetallicTextureAlpha = true;
  46314. /**
  46315. * Specifies if the metallic texture contains the roughness information in its green channel.
  46316. */
  46317. _this.useRoughnessFromMetallicTextureGreen = false;
  46318. /**
  46319. * Specifies if the metallic texture contains the metallness information in its blue channel.
  46320. */
  46321. _this.useMetallnessFromMetallicTextureBlue = false;
  46322. /**
  46323. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  46324. */
  46325. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  46326. /**
  46327. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  46328. */
  46329. _this.useAmbientInGrayScale = false;
  46330. /**
  46331. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  46332. * The material will try to infer what glossiness each pixel should be.
  46333. */
  46334. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  46335. /**
  46336. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  46337. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  46338. */
  46339. _this.useRadianceOverAlpha = true;
  46340. /**
  46341. * Allows using an object space normal map (instead of tangent space).
  46342. */
  46343. _this.useObjectSpaceNormalMap = false;
  46344. /**
  46345. * Allows using the bump map in parallax mode.
  46346. */
  46347. _this.useParallax = false;
  46348. /**
  46349. * Allows using the bump map in parallax occlusion mode.
  46350. */
  46351. _this.useParallaxOcclusion = false;
  46352. /**
  46353. * Controls the scale bias of the parallax mode.
  46354. */
  46355. _this.parallaxScaleBias = 0.05;
  46356. /**
  46357. * If sets to true, disables all the lights affecting the material.
  46358. */
  46359. _this.disableLighting = false;
  46360. /**
  46361. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46362. */
  46363. _this.forceIrradianceInFragment = false;
  46364. /**
  46365. * Number of Simultaneous lights allowed on the material.
  46366. */
  46367. _this.maxSimultaneousLights = 4;
  46368. /**
  46369. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46370. */
  46371. _this.invertNormalMapX = false;
  46372. /**
  46373. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46374. */
  46375. _this.invertNormalMapY = false;
  46376. /**
  46377. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46378. */
  46379. _this.twoSidedLighting = false;
  46380. /**
  46381. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46382. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46383. */
  46384. _this.useAlphaFresnel = false;
  46385. /**
  46386. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46387. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46388. */
  46389. _this.useLinearAlphaFresnel = false;
  46390. /**
  46391. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46392. * And/Or occlude the blended part.
  46393. */
  46394. _this.environmentBRDFTexture = null;
  46395. /**
  46396. * Force normal to face away from face.
  46397. */
  46398. _this.forceNormalForward = false;
  46399. /**
  46400. * Enables specular anti aliasing in the PBR shader.
  46401. * It will both interacts on the Geometry for analytical and IBL lighting.
  46402. * It also prefilter the roughness map based on the bump values.
  46403. */
  46404. _this.enableSpecularAntiAliasing = false;
  46405. /**
  46406. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46407. * makes the reflect vector face the model (under horizon).
  46408. */
  46409. _this.useHorizonOcclusion = true;
  46410. /**
  46411. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46412. * too much the area relying on ambient texture to define their ambient occlusion.
  46413. */
  46414. _this.useRadianceOcclusion = true;
  46415. /**
  46416. * If set to true, no lighting calculations will be applied.
  46417. */
  46418. _this.unlit = false;
  46419. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46420. return _this;
  46421. }
  46422. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  46423. /**
  46424. * BJS is using an harcoded light falloff based on a manually sets up range.
  46425. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46426. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46427. */
  46428. get: function () {
  46429. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  46430. },
  46431. /**
  46432. * BJS is using an harcoded light falloff based on a manually sets up range.
  46433. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46434. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46435. */
  46436. set: function (value) {
  46437. if (value !== this.usePhysicalLightFalloff) {
  46438. // Ensure the effect will be rebuilt.
  46439. this._markAllSubMeshesAsTexturesDirty();
  46440. if (value) {
  46441. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  46442. }
  46443. else {
  46444. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  46445. }
  46446. }
  46447. },
  46448. enumerable: true,
  46449. configurable: true
  46450. });
  46451. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  46452. /**
  46453. * In order to support the falloff compatibility with gltf, a special mode has been added
  46454. * to reproduce the gltf light falloff.
  46455. */
  46456. get: function () {
  46457. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  46458. },
  46459. /**
  46460. * In order to support the falloff compatibility with gltf, a special mode has been added
  46461. * to reproduce the gltf light falloff.
  46462. */
  46463. set: function (value) {
  46464. if (value !== this.useGLTFLightFalloff) {
  46465. // Ensure the effect will be rebuilt.
  46466. this._markAllSubMeshesAsTexturesDirty();
  46467. if (value) {
  46468. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  46469. }
  46470. else {
  46471. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  46472. }
  46473. }
  46474. },
  46475. enumerable: true,
  46476. configurable: true
  46477. });
  46478. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46479. /**
  46480. * Gets the image processing configuration used either in this material.
  46481. */
  46482. get: function () {
  46483. return this._imageProcessingConfiguration;
  46484. },
  46485. /**
  46486. * Sets the Default image processing configuration used either in the this material.
  46487. *
  46488. * If sets to null, the scene one is in use.
  46489. */
  46490. set: function (value) {
  46491. this._attachImageProcessingConfiguration(value);
  46492. // Ensure the effect will be rebuilt.
  46493. this._markAllSubMeshesAsTexturesDirty();
  46494. },
  46495. enumerable: true,
  46496. configurable: true
  46497. });
  46498. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46499. /**
  46500. * Gets wether the color curves effect is enabled.
  46501. */
  46502. get: function () {
  46503. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46504. },
  46505. /**
  46506. * Sets wether the color curves effect is enabled.
  46507. */
  46508. set: function (value) {
  46509. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46510. },
  46511. enumerable: true,
  46512. configurable: true
  46513. });
  46514. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46515. /**
  46516. * Gets wether the color grading effect is enabled.
  46517. */
  46518. get: function () {
  46519. return this.imageProcessingConfiguration.colorGradingEnabled;
  46520. },
  46521. /**
  46522. * Gets wether the color grading effect is enabled.
  46523. */
  46524. set: function (value) {
  46525. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46526. },
  46527. enumerable: true,
  46528. configurable: true
  46529. });
  46530. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46531. /**
  46532. * Gets wether tonemapping is enabled or not.
  46533. */
  46534. get: function () {
  46535. return this._imageProcessingConfiguration.toneMappingEnabled;
  46536. },
  46537. /**
  46538. * Sets wether tonemapping is enabled or not
  46539. */
  46540. set: function (value) {
  46541. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46542. },
  46543. enumerable: true,
  46544. configurable: true
  46545. });
  46546. ;
  46547. ;
  46548. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46549. /**
  46550. * The camera exposure used on this material.
  46551. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46552. * This corresponds to a photographic exposure.
  46553. */
  46554. get: function () {
  46555. return this._imageProcessingConfiguration.exposure;
  46556. },
  46557. /**
  46558. * The camera exposure used on this material.
  46559. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46560. * This corresponds to a photographic exposure.
  46561. */
  46562. set: function (value) {
  46563. this._imageProcessingConfiguration.exposure = value;
  46564. },
  46565. enumerable: true,
  46566. configurable: true
  46567. });
  46568. ;
  46569. ;
  46570. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46571. /**
  46572. * Gets The camera contrast used on this material.
  46573. */
  46574. get: function () {
  46575. return this._imageProcessingConfiguration.contrast;
  46576. },
  46577. /**
  46578. * Sets The camera contrast used on this material.
  46579. */
  46580. set: function (value) {
  46581. this._imageProcessingConfiguration.contrast = value;
  46582. },
  46583. enumerable: true,
  46584. configurable: true
  46585. });
  46586. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46587. /**
  46588. * Gets the Color Grading 2D Lookup Texture.
  46589. */
  46590. get: function () {
  46591. return this._imageProcessingConfiguration.colorGradingTexture;
  46592. },
  46593. /**
  46594. * Sets the Color Grading 2D Lookup Texture.
  46595. */
  46596. set: function (value) {
  46597. this._imageProcessingConfiguration.colorGradingTexture = value;
  46598. },
  46599. enumerable: true,
  46600. configurable: true
  46601. });
  46602. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46603. /**
  46604. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46605. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46606. * 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;
  46607. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46608. */
  46609. get: function () {
  46610. return this._imageProcessingConfiguration.colorCurves;
  46611. },
  46612. /**
  46613. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46614. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46615. * 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;
  46616. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46617. */
  46618. set: function (value) {
  46619. this._imageProcessingConfiguration.colorCurves = value;
  46620. },
  46621. enumerable: true,
  46622. configurable: true
  46623. });
  46624. /**
  46625. * Returns the name of this material class.
  46626. */
  46627. PBRMaterial.prototype.getClassName = function () {
  46628. return "PBRMaterial";
  46629. };
  46630. /**
  46631. * Returns an array of the actively used textures.
  46632. * @returns - Array of BaseTextures
  46633. */
  46634. PBRMaterial.prototype.getActiveTextures = function () {
  46635. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46636. if (this._albedoTexture) {
  46637. activeTextures.push(this._albedoTexture);
  46638. }
  46639. if (this._ambientTexture) {
  46640. activeTextures.push(this._ambientTexture);
  46641. }
  46642. if (this._opacityTexture) {
  46643. activeTextures.push(this._opacityTexture);
  46644. }
  46645. if (this._reflectionTexture) {
  46646. activeTextures.push(this._reflectionTexture);
  46647. }
  46648. if (this._emissiveTexture) {
  46649. activeTextures.push(this._emissiveTexture);
  46650. }
  46651. if (this._reflectivityTexture) {
  46652. activeTextures.push(this._reflectivityTexture);
  46653. }
  46654. if (this._metallicTexture) {
  46655. activeTextures.push(this._metallicTexture);
  46656. }
  46657. if (this._microSurfaceTexture) {
  46658. activeTextures.push(this._microSurfaceTexture);
  46659. }
  46660. if (this._bumpTexture) {
  46661. activeTextures.push(this._bumpTexture);
  46662. }
  46663. if (this._lightmapTexture) {
  46664. activeTextures.push(this._lightmapTexture);
  46665. }
  46666. if (this._refractionTexture) {
  46667. activeTextures.push(this._refractionTexture);
  46668. }
  46669. return activeTextures;
  46670. };
  46671. /**
  46672. * Checks to see if a texture is used in the material.
  46673. * @param texture - Base texture to use.
  46674. * @returns - Boolean specifying if a texture is used in the material.
  46675. */
  46676. PBRMaterial.prototype.hasTexture = function (texture) {
  46677. if (_super.prototype.hasTexture.call(this, texture)) {
  46678. return true;
  46679. }
  46680. if (this._albedoTexture === texture) {
  46681. return true;
  46682. }
  46683. if (this._ambientTexture === texture) {
  46684. return true;
  46685. }
  46686. if (this._opacityTexture === texture) {
  46687. return true;
  46688. }
  46689. if (this._reflectionTexture === texture) {
  46690. return true;
  46691. }
  46692. if (this._reflectivityTexture === texture) {
  46693. return true;
  46694. }
  46695. if (this._metallicTexture === texture) {
  46696. return true;
  46697. }
  46698. if (this._microSurfaceTexture === texture) {
  46699. return true;
  46700. }
  46701. if (this._bumpTexture === texture) {
  46702. return true;
  46703. }
  46704. if (this._lightmapTexture === texture) {
  46705. return true;
  46706. }
  46707. if (this._refractionTexture === texture) {
  46708. return true;
  46709. }
  46710. return false;
  46711. };
  46712. /**
  46713. * Makes a duplicate of the current material.
  46714. * @param name - name to use for the new material.
  46715. */
  46716. PBRMaterial.prototype.clone = function (name) {
  46717. var _this = this;
  46718. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46719. clone.id = name;
  46720. clone.name = name;
  46721. return clone;
  46722. };
  46723. /**
  46724. * Serializes this PBR Material.
  46725. * @returns - An object with the serialized material.
  46726. */
  46727. PBRMaterial.prototype.serialize = function () {
  46728. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46729. serializationObject.customType = "BABYLON.PBRMaterial";
  46730. return serializationObject;
  46731. };
  46732. // Statics
  46733. /**
  46734. * Parses a PBR Material from a serialized object.
  46735. * @param source - Serialized object.
  46736. * @param scene - BJS scene instance.
  46737. * @param rootUrl - url for the scene object
  46738. * @returns - PBRMaterial
  46739. */
  46740. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46741. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46742. };
  46743. /**
  46744. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  46745. */
  46746. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  46747. /**
  46748. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46749. */
  46750. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  46751. /**
  46752. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46753. */
  46754. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  46755. /**
  46756. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46757. * They are also discarded below the alpha cutoff threshold to improve performances.
  46758. */
  46759. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46760. /**
  46761. * Defines the default value of how much AO map is occluding the analytical lights
  46762. * (point spot...).
  46763. */
  46764. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  46765. __decorate([
  46766. BABYLON.serialize(),
  46767. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46768. ], PBRMaterial.prototype, "directIntensity", void 0);
  46769. __decorate([
  46770. BABYLON.serialize(),
  46771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46772. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46773. __decorate([
  46774. BABYLON.serialize(),
  46775. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46776. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46777. __decorate([
  46778. BABYLON.serialize(),
  46779. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46780. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46781. __decorate([
  46782. BABYLON.serialize(),
  46783. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46784. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46785. __decorate([
  46786. BABYLON.serializeAsTexture(),
  46787. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46788. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46789. __decorate([
  46790. BABYLON.serializeAsTexture(),
  46791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46792. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46793. __decorate([
  46794. BABYLON.serialize(),
  46795. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46796. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46797. __decorate([
  46798. BABYLON.serialize(),
  46799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46800. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  46801. __decorate([
  46802. BABYLON.serializeAsTexture(),
  46803. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46804. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46805. __decorate([
  46806. BABYLON.serializeAsTexture(),
  46807. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46808. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46809. __decorate([
  46810. BABYLON.serializeAsTexture(),
  46811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46812. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46813. __decorate([
  46814. BABYLON.serializeAsTexture(),
  46815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46816. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46817. __decorate([
  46818. BABYLON.serializeAsTexture(),
  46819. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46820. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46821. __decorate([
  46822. BABYLON.serialize(),
  46823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46824. ], PBRMaterial.prototype, "metallic", void 0);
  46825. __decorate([
  46826. BABYLON.serialize(),
  46827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46828. ], PBRMaterial.prototype, "roughness", void 0);
  46829. __decorate([
  46830. BABYLON.serializeAsTexture(),
  46831. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46832. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46833. __decorate([
  46834. BABYLON.serializeAsTexture(),
  46835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46836. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46837. __decorate([
  46838. BABYLON.serializeAsTexture(),
  46839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46840. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46841. __decorate([
  46842. BABYLON.serializeAsTexture(),
  46843. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46844. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46845. __decorate([
  46846. BABYLON.serializeAsColor3("ambient"),
  46847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46848. ], PBRMaterial.prototype, "ambientColor", void 0);
  46849. __decorate([
  46850. BABYLON.serializeAsColor3("albedo"),
  46851. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46852. ], PBRMaterial.prototype, "albedoColor", void 0);
  46853. __decorate([
  46854. BABYLON.serializeAsColor3("reflectivity"),
  46855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46856. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46857. __decorate([
  46858. BABYLON.serializeAsColor3("reflection"),
  46859. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46860. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46861. __decorate([
  46862. BABYLON.serializeAsColor3("emissive"),
  46863. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46864. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46865. __decorate([
  46866. BABYLON.serialize(),
  46867. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46868. ], PBRMaterial.prototype, "microSurface", void 0);
  46869. __decorate([
  46870. BABYLON.serialize(),
  46871. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46872. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46873. __decorate([
  46874. BABYLON.serialize(),
  46875. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46876. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46877. __decorate([
  46878. BABYLON.serialize(),
  46879. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46880. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46881. __decorate([
  46882. BABYLON.serialize(),
  46883. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46884. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46885. __decorate([
  46886. BABYLON.serialize(),
  46887. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46888. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46889. __decorate([
  46890. BABYLON.serialize(),
  46891. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46892. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46893. __decorate([
  46894. BABYLON.serialize(),
  46895. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46896. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46897. __decorate([
  46898. BABYLON.serialize(),
  46899. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46900. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46901. __decorate([
  46902. BABYLON.serialize(),
  46903. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46904. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46905. __decorate([
  46906. BABYLON.serialize(),
  46907. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46908. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46909. __decorate([
  46910. BABYLON.serialize(),
  46911. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46912. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46913. __decorate([
  46914. BABYLON.serialize(),
  46915. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46916. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46917. __decorate([
  46918. BABYLON.serialize(),
  46919. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46920. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46921. __decorate([
  46922. BABYLON.serialize(),
  46923. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46924. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46925. __decorate([
  46926. BABYLON.serialize(),
  46927. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46928. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46929. __decorate([
  46930. BABYLON.serialize()
  46931. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  46932. __decorate([
  46933. BABYLON.serialize()
  46934. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  46935. __decorate([
  46936. BABYLON.serialize(),
  46937. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46938. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46939. __decorate([
  46940. BABYLON.serialize(),
  46941. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46942. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46943. __decorate([
  46944. BABYLON.serialize(),
  46945. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46946. ], PBRMaterial.prototype, "useParallax", void 0);
  46947. __decorate([
  46948. BABYLON.serialize(),
  46949. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46950. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46951. __decorate([
  46952. BABYLON.serialize(),
  46953. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46954. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46955. __decorate([
  46956. BABYLON.serialize(),
  46957. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46958. ], PBRMaterial.prototype, "disableLighting", void 0);
  46959. __decorate([
  46960. BABYLON.serialize(),
  46961. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46962. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46963. __decorate([
  46964. BABYLON.serialize(),
  46965. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46966. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46967. __decorate([
  46968. BABYLON.serialize(),
  46969. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46970. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46971. __decorate([
  46972. BABYLON.serialize(),
  46973. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46974. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46975. __decorate([
  46976. BABYLON.serialize(),
  46977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46978. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46979. __decorate([
  46980. BABYLON.serialize(),
  46981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46982. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46983. __decorate([
  46984. BABYLON.serialize(),
  46985. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46986. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46987. __decorate([
  46988. BABYLON.serializeAsTexture(),
  46989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46990. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46991. __decorate([
  46992. BABYLON.serialize(),
  46993. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46994. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46995. __decorate([
  46996. BABYLON.serialize(),
  46997. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46998. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46999. __decorate([
  47000. BABYLON.serialize(),
  47001. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47002. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  47003. __decorate([
  47004. BABYLON.serialize(),
  47005. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47006. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  47007. __decorate([
  47008. BABYLON.serialize(),
  47009. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  47010. ], PBRMaterial.prototype, "unlit", void 0);
  47011. return PBRMaterial;
  47012. }(BABYLON.PBRBaseMaterial));
  47013. BABYLON.PBRMaterial = PBRMaterial;
  47014. })(BABYLON || (BABYLON = {}));
  47015. //# sourceMappingURL=babylon.pbrMaterial.js.map
  47016. var BABYLON;
  47017. (function (BABYLON) {
  47018. /**
  47019. * The PBR material of BJS following the metal roughness convention.
  47020. *
  47021. * This fits to the PBR convention in the GLTF definition:
  47022. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  47023. */
  47024. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  47025. __extends(PBRMetallicRoughnessMaterial, _super);
  47026. /**
  47027. * Instantiates a new PBRMetalRoughnessMaterial instance.
  47028. *
  47029. * @param name The material name
  47030. * @param scene The scene the material will be use in.
  47031. */
  47032. function PBRMetallicRoughnessMaterial(name, scene) {
  47033. var _this = _super.call(this, name, scene) || this;
  47034. _this._useRoughnessFromMetallicTextureAlpha = false;
  47035. _this._useRoughnessFromMetallicTextureGreen = true;
  47036. _this._useMetallnessFromMetallicTextureBlue = true;
  47037. _this.metallic = 1.0;
  47038. _this.roughness = 1.0;
  47039. return _this;
  47040. }
  47041. /**
  47042. * Return the currrent class name of the material.
  47043. */
  47044. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  47045. return "PBRMetallicRoughnessMaterial";
  47046. };
  47047. /**
  47048. * Return the active textures of the material.
  47049. */
  47050. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  47051. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47052. if (this.baseTexture) {
  47053. activeTextures.push(this.baseTexture);
  47054. }
  47055. if (this.metallicRoughnessTexture) {
  47056. activeTextures.push(this.metallicRoughnessTexture);
  47057. }
  47058. return activeTextures;
  47059. };
  47060. /**
  47061. * Checks to see if a texture is used in the material.
  47062. * @param texture - Base texture to use.
  47063. * @returns - Boolean specifying if a texture is used in the material.
  47064. */
  47065. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  47066. if (_super.prototype.hasTexture.call(this, texture)) {
  47067. return true;
  47068. }
  47069. if (this.baseTexture === texture) {
  47070. return true;
  47071. }
  47072. if (this.metallicRoughnessTexture === texture) {
  47073. return true;
  47074. }
  47075. return false;
  47076. };
  47077. /**
  47078. * Makes a duplicate of the current material.
  47079. * @param name - name to use for the new material.
  47080. */
  47081. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  47082. var _this = this;
  47083. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  47084. clone.id = name;
  47085. clone.name = name;
  47086. return clone;
  47087. };
  47088. /**
  47089. * Serialize the material to a parsable JSON object.
  47090. */
  47091. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  47092. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47093. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  47094. return serializationObject;
  47095. };
  47096. /**
  47097. * Parses a JSON object correponding to the serialize function.
  47098. */
  47099. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  47100. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  47101. };
  47102. __decorate([
  47103. BABYLON.serializeAsColor3(),
  47104. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47105. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  47106. __decorate([
  47107. BABYLON.serializeAsTexture(),
  47108. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47109. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  47110. __decorate([
  47111. BABYLON.serialize(),
  47112. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47113. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  47114. __decorate([
  47115. BABYLON.serialize(),
  47116. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47117. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  47118. __decorate([
  47119. BABYLON.serializeAsTexture(),
  47120. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  47121. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  47122. return PBRMetallicRoughnessMaterial;
  47123. }(BABYLON.PBRBaseSimpleMaterial));
  47124. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  47125. })(BABYLON || (BABYLON = {}));
  47126. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  47127. var BABYLON;
  47128. (function (BABYLON) {
  47129. /**
  47130. * The PBR material of BJS following the specular glossiness convention.
  47131. *
  47132. * This fits to the PBR convention in the GLTF definition:
  47133. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  47134. */
  47135. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  47136. __extends(PBRSpecularGlossinessMaterial, _super);
  47137. /**
  47138. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  47139. *
  47140. * @param name The material name
  47141. * @param scene The scene the material will be use in.
  47142. */
  47143. function PBRSpecularGlossinessMaterial(name, scene) {
  47144. var _this = _super.call(this, name, scene) || this;
  47145. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  47146. return _this;
  47147. }
  47148. /**
  47149. * Return the currrent class name of the material.
  47150. */
  47151. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  47152. return "PBRSpecularGlossinessMaterial";
  47153. };
  47154. /**
  47155. * Return the active textures of the material.
  47156. */
  47157. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  47158. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47159. if (this.diffuseTexture) {
  47160. activeTextures.push(this.diffuseTexture);
  47161. }
  47162. if (this.specularGlossinessTexture) {
  47163. activeTextures.push(this.specularGlossinessTexture);
  47164. }
  47165. return activeTextures;
  47166. };
  47167. /**
  47168. * Checks to see if a texture is used in the material.
  47169. * @param texture - Base texture to use.
  47170. * @returns - Boolean specifying if a texture is used in the material.
  47171. */
  47172. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  47173. if (_super.prototype.hasTexture.call(this, texture)) {
  47174. return true;
  47175. }
  47176. if (this.diffuseTexture === texture) {
  47177. return true;
  47178. }
  47179. if (this.specularGlossinessTexture === texture) {
  47180. return true;
  47181. }
  47182. return false;
  47183. };
  47184. /**
  47185. * Makes a duplicate of the current material.
  47186. * @param name - name to use for the new material.
  47187. */
  47188. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  47189. var _this = this;
  47190. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  47191. clone.id = name;
  47192. clone.name = name;
  47193. return clone;
  47194. };
  47195. /**
  47196. * Serialize the material to a parsable JSON object.
  47197. */
  47198. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  47199. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47200. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  47201. return serializationObject;
  47202. };
  47203. /**
  47204. * Parses a JSON object correponding to the serialize function.
  47205. */
  47206. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  47207. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  47208. };
  47209. __decorate([
  47210. BABYLON.serializeAsColor3("diffuse"),
  47211. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47212. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  47213. __decorate([
  47214. BABYLON.serializeAsTexture(),
  47215. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47216. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  47217. __decorate([
  47218. BABYLON.serializeAsColor3("specular"),
  47219. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  47220. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  47221. __decorate([
  47222. BABYLON.serialize(),
  47223. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  47224. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  47225. __decorate([
  47226. BABYLON.serializeAsTexture(),
  47227. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  47228. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  47229. return PBRSpecularGlossinessMaterial;
  47230. }(BABYLON.PBRBaseSimpleMaterial));
  47231. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  47232. })(BABYLON || (BABYLON = {}));
  47233. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  47234. var BABYLON;
  47235. (function (BABYLON) {
  47236. /**
  47237. * This is a list of all the different input types that are available in the application.
  47238. * Fo instance: ArcRotateCameraGamepadInput...
  47239. */
  47240. BABYLON.CameraInputTypes = {};
  47241. /**
  47242. * This represents the input manager used within a camera.
  47243. * It helps dealing with all the different kind of input attached to a camera.
  47244. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47245. */
  47246. var CameraInputsManager = /** @class */ (function () {
  47247. /**
  47248. * Instantiate a new Camera Input Manager.
  47249. * @param camera Defines the camera the input manager blongs to
  47250. */
  47251. function CameraInputsManager(camera) {
  47252. this.attached = {};
  47253. this.camera = camera;
  47254. this.checkInputs = function () { };
  47255. }
  47256. /**
  47257. * Add an input method to a camera
  47258. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47259. * @param input camera input method
  47260. */
  47261. CameraInputsManager.prototype.add = function (input) {
  47262. var type = input.getSimpleName();
  47263. if (this.attached[type]) {
  47264. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  47265. return;
  47266. }
  47267. this.attached[type] = input;
  47268. input.camera = this.camera;
  47269. //for checkInputs, we are dynamically creating a function
  47270. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  47271. if (input.checkInputs) {
  47272. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47273. }
  47274. if (this.attachedElement) {
  47275. input.attachControl(this.attachedElement);
  47276. }
  47277. };
  47278. /**
  47279. * Remove a specific input method from a camera
  47280. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  47281. * @param inputToRemove camera input method
  47282. */
  47283. CameraInputsManager.prototype.remove = function (inputToRemove) {
  47284. for (var cam in this.attached) {
  47285. var input = this.attached[cam];
  47286. if (input === inputToRemove) {
  47287. input.detachControl(this.attachedElement);
  47288. input.camera = null;
  47289. delete this.attached[cam];
  47290. this.rebuildInputCheck();
  47291. }
  47292. }
  47293. };
  47294. /**
  47295. * Remove a specific input type from a camera
  47296. * example: camera.inputs.remove("ArcRotateCameraGamepadInput");
  47297. * @param inputType the type of the input to remove
  47298. */
  47299. CameraInputsManager.prototype.removeByType = function (inputType) {
  47300. for (var cam in this.attached) {
  47301. var input = this.attached[cam];
  47302. if (input.getClassName() === inputType) {
  47303. input.detachControl(this.attachedElement);
  47304. input.camera = null;
  47305. delete this.attached[cam];
  47306. this.rebuildInputCheck();
  47307. }
  47308. }
  47309. };
  47310. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  47311. var current = this.checkInputs;
  47312. return function () {
  47313. current();
  47314. fn();
  47315. };
  47316. };
  47317. /**
  47318. * Attach the input controls to the currently attached dom element to listen the events from.
  47319. * @param input Defines the input to attach
  47320. */
  47321. CameraInputsManager.prototype.attachInput = function (input) {
  47322. if (this.attachedElement) {
  47323. input.attachControl(this.attachedElement, this.noPreventDefault);
  47324. }
  47325. };
  47326. /**
  47327. * Attach the current manager inputs controls to a specific dom element to listen the events from.
  47328. * @param element Defines the dom element to collect the events from
  47329. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47330. */
  47331. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  47332. if (noPreventDefault === void 0) { noPreventDefault = false; }
  47333. if (this.attachedElement) {
  47334. return;
  47335. }
  47336. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  47337. this.attachedElement = element;
  47338. this.noPreventDefault = noPreventDefault;
  47339. for (var cam in this.attached) {
  47340. this.attached[cam].attachControl(element, noPreventDefault);
  47341. }
  47342. };
  47343. /**
  47344. * Detach the current manager inputs controls from a specific dom element.
  47345. * @param element Defines the dom element to collect the events from
  47346. * @param disconnect Defines whether the input should be removed from the current list of attached inputs
  47347. */
  47348. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  47349. if (disconnect === void 0) { disconnect = false; }
  47350. if (this.attachedElement !== element) {
  47351. return;
  47352. }
  47353. for (var cam in this.attached) {
  47354. this.attached[cam].detachControl(element);
  47355. if (disconnect) {
  47356. this.attached[cam].camera = null;
  47357. }
  47358. }
  47359. this.attachedElement = null;
  47360. };
  47361. /**
  47362. * Rebuild the dynamic inputCheck function from the current list of
  47363. * defined inputs in the manager.
  47364. */
  47365. CameraInputsManager.prototype.rebuildInputCheck = function () {
  47366. this.checkInputs = function () { };
  47367. for (var cam in this.attached) {
  47368. var input = this.attached[cam];
  47369. if (input.checkInputs) {
  47370. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47371. }
  47372. }
  47373. };
  47374. /**
  47375. * Remove all attached input methods from a camera
  47376. */
  47377. CameraInputsManager.prototype.clear = function () {
  47378. if (this.attachedElement) {
  47379. this.detachElement(this.attachedElement, true);
  47380. }
  47381. this.attached = {};
  47382. this.attachedElement = null;
  47383. this.checkInputs = function () { };
  47384. };
  47385. /**
  47386. * Serialize the current input manager attached to a camera.
  47387. * This ensures than once parsed,
  47388. * the input associated to the camera will be identical to the current ones
  47389. * @param serializedCamera Defines the camera serialization JSON the input serialization should write to
  47390. */
  47391. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  47392. var inputs = {};
  47393. for (var cam in this.attached) {
  47394. var input = this.attached[cam];
  47395. var res = BABYLON.SerializationHelper.Serialize(input);
  47396. inputs[input.getClassName()] = res;
  47397. }
  47398. serializedCamera.inputsmgr = inputs;
  47399. };
  47400. /**
  47401. * Parses an input manager serialized JSON to restore the previous list of inputs
  47402. * and states associated to a camera.
  47403. * @param parsedCamera Defines the JSON to parse
  47404. */
  47405. CameraInputsManager.prototype.parse = function (parsedCamera) {
  47406. var parsedInputs = parsedCamera.inputsmgr;
  47407. if (parsedInputs) {
  47408. this.clear();
  47409. for (var n in parsedInputs) {
  47410. var construct = BABYLON.CameraInputTypes[n];
  47411. if (construct) {
  47412. var parsedinput = parsedInputs[n];
  47413. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  47414. this.add(input);
  47415. }
  47416. }
  47417. }
  47418. else {
  47419. //2016-03-08 this part is for managing backward compatibility
  47420. for (var n in this.attached) {
  47421. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  47422. if (construct) {
  47423. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  47424. this.remove(this.attached[n]);
  47425. this.add(input);
  47426. }
  47427. }
  47428. }
  47429. };
  47430. return CameraInputsManager;
  47431. }());
  47432. BABYLON.CameraInputsManager = CameraInputsManager;
  47433. })(BABYLON || (BABYLON = {}));
  47434. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  47435. var BABYLON;
  47436. (function (BABYLON) {
  47437. /**
  47438. * A target camera takes a mesh or position as a target and continues to look at it while it moves.
  47439. * This is the base of the follow, arc rotate cameras and Free camera
  47440. * @see http://doc.babylonjs.com/features/cameras
  47441. */
  47442. var TargetCamera = /** @class */ (function (_super) {
  47443. __extends(TargetCamera, _super);
  47444. /**
  47445. * Instantiates a target camera that takes a meshor position as a target and continues to look at it while it moves.
  47446. * This is the base of the follow, arc rotate cameras and Free camera
  47447. * @see http://doc.babylonjs.com/features/cameras
  47448. * @param name Defines the name of the camera in the scene
  47449. * @param position Defines the start position of the camera in the scene
  47450. * @param scene Defines the scene the camera belongs to
  47451. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  47452. */
  47453. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47454. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47455. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47456. /**
  47457. * Define the current direction the camera is moving to
  47458. */
  47459. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47460. /**
  47461. * Define the current rotation the camera is rotating to
  47462. */
  47463. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  47464. /**
  47465. * Define the current rotation of the camera
  47466. */
  47467. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  47468. /**
  47469. * Define the current speed of the camera
  47470. */
  47471. _this.speed = 2.0;
  47472. /**
  47473. * Add cconstraint to the camera to prevent it to move freely in all directions and
  47474. * around all axis.
  47475. */
  47476. _this.noRotationConstraint = false;
  47477. /**
  47478. * Define the current target of the camera as an object or a position.
  47479. */
  47480. _this.lockedTarget = null;
  47481. /** @hidden */
  47482. _this._currentTarget = BABYLON.Vector3.Zero();
  47483. /** @hidden */
  47484. _this._viewMatrix = BABYLON.Matrix.Zero();
  47485. /** @hidden */
  47486. _this._camMatrix = BABYLON.Matrix.Zero();
  47487. /** @hidden */
  47488. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  47489. /** @hidden */
  47490. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  47491. /** @hidden */
  47492. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  47493. /** @hidden */
  47494. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  47495. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  47496. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  47497. _this._defaultUp = BABYLON.Vector3.Up();
  47498. _this._cachedRotationZ = 0;
  47499. return _this;
  47500. }
  47501. /**
  47502. * Gets the position in front of the camera at a given distance.
  47503. * @param distance The distance from the camera we want the position to be
  47504. * @returns the position
  47505. */
  47506. TargetCamera.prototype.getFrontPosition = function (distance) {
  47507. this.getWorldMatrix();
  47508. var direction = this.getTarget().subtract(this.position);
  47509. direction.normalize();
  47510. direction.scaleInPlace(distance);
  47511. return this.globalPosition.add(direction);
  47512. };
  47513. /** @hidden */
  47514. TargetCamera.prototype._getLockedTargetPosition = function () {
  47515. if (!this.lockedTarget) {
  47516. return null;
  47517. }
  47518. if (this.lockedTarget.absolutePosition) {
  47519. this.lockedTarget.computeWorldMatrix();
  47520. }
  47521. return this.lockedTarget.absolutePosition || this.lockedTarget;
  47522. };
  47523. /**
  47524. * Store current camera state of the camera (fov, position, rotation, etc..)
  47525. * @returns the camera
  47526. */
  47527. TargetCamera.prototype.storeState = function () {
  47528. this._storedPosition = this.position.clone();
  47529. this._storedRotation = this.rotation.clone();
  47530. if (this.rotationQuaternion) {
  47531. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  47532. }
  47533. return _super.prototype.storeState.call(this);
  47534. };
  47535. /**
  47536. * Restored camera state. You must call storeState() first
  47537. * @returns whether it was successful or not
  47538. * @hidden
  47539. */
  47540. TargetCamera.prototype._restoreStateValues = function () {
  47541. if (!_super.prototype._restoreStateValues.call(this)) {
  47542. return false;
  47543. }
  47544. this.position = this._storedPosition.clone();
  47545. this.rotation = this._storedRotation.clone();
  47546. if (this.rotationQuaternion) {
  47547. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  47548. }
  47549. this.cameraDirection.copyFromFloats(0, 0, 0);
  47550. this.cameraRotation.copyFromFloats(0, 0);
  47551. return true;
  47552. };
  47553. /** @hidden */
  47554. TargetCamera.prototype._initCache = function () {
  47555. _super.prototype._initCache.call(this);
  47556. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47557. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47558. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47559. };
  47560. /** @hidden */
  47561. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  47562. if (!ignoreParentClass) {
  47563. _super.prototype._updateCache.call(this);
  47564. }
  47565. var lockedTargetPosition = this._getLockedTargetPosition();
  47566. if (!lockedTargetPosition) {
  47567. this._cache.lockedTarget = null;
  47568. }
  47569. else {
  47570. if (!this._cache.lockedTarget) {
  47571. this._cache.lockedTarget = lockedTargetPosition.clone();
  47572. }
  47573. else {
  47574. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  47575. }
  47576. }
  47577. this._cache.rotation.copyFrom(this.rotation);
  47578. if (this.rotationQuaternion)
  47579. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47580. };
  47581. // Synchronized
  47582. /** @hidden */
  47583. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  47584. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  47585. return false;
  47586. }
  47587. var lockedTargetPosition = this._getLockedTargetPosition();
  47588. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  47589. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  47590. };
  47591. // Methods
  47592. /** @hidden */
  47593. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  47594. var engine = this.getEngine();
  47595. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  47596. };
  47597. // Target
  47598. /** @hidden */
  47599. TargetCamera.prototype.setTarget = function (target) {
  47600. this.upVector.normalize();
  47601. if (this.position.z === target.z) {
  47602. this.position.z += BABYLON.Epsilon;
  47603. }
  47604. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  47605. this._camMatrix.invert();
  47606. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  47607. var vDir = target.subtract(this.position);
  47608. if (vDir.x >= 0.0) {
  47609. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  47610. }
  47611. else {
  47612. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47613. }
  47614. this.rotation.z = 0;
  47615. if (isNaN(this.rotation.x)) {
  47616. this.rotation.x = 0;
  47617. }
  47618. if (isNaN(this.rotation.y)) {
  47619. this.rotation.y = 0;
  47620. }
  47621. if (isNaN(this.rotation.z)) {
  47622. this.rotation.z = 0;
  47623. }
  47624. if (this.rotationQuaternion) {
  47625. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47626. }
  47627. };
  47628. /**
  47629. * Return the current target position of the camera. This value is expressed in local space.
  47630. * @returns the target position
  47631. */
  47632. TargetCamera.prototype.getTarget = function () {
  47633. return this._currentTarget;
  47634. };
  47635. /** @hidden */
  47636. TargetCamera.prototype._decideIfNeedsToMove = function () {
  47637. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47638. };
  47639. /** @hidden */
  47640. TargetCamera.prototype._updatePosition = function () {
  47641. if (this.parent) {
  47642. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  47643. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  47644. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  47645. return;
  47646. }
  47647. this.position.addInPlace(this.cameraDirection);
  47648. };
  47649. /** @hidden */
  47650. TargetCamera.prototype._checkInputs = function () {
  47651. var needToMove = this._decideIfNeedsToMove();
  47652. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  47653. // Move
  47654. if (needToMove) {
  47655. this._updatePosition();
  47656. }
  47657. // Rotate
  47658. if (needToRotate) {
  47659. this.rotation.x += this.cameraRotation.x;
  47660. this.rotation.y += this.cameraRotation.y;
  47661. //rotate, if quaternion is set and rotation was used
  47662. if (this.rotationQuaternion) {
  47663. var len = this.rotation.lengthSquared();
  47664. if (len) {
  47665. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47666. }
  47667. }
  47668. if (!this.noRotationConstraint) {
  47669. var limit = (Math.PI / 2) * 0.95;
  47670. if (this.rotation.x > limit)
  47671. this.rotation.x = limit;
  47672. if (this.rotation.x < -limit)
  47673. this.rotation.x = -limit;
  47674. }
  47675. }
  47676. // Inertia
  47677. if (needToMove) {
  47678. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47679. this.cameraDirection.x = 0;
  47680. }
  47681. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47682. this.cameraDirection.y = 0;
  47683. }
  47684. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47685. this.cameraDirection.z = 0;
  47686. }
  47687. this.cameraDirection.scaleInPlace(this.inertia);
  47688. }
  47689. if (needToRotate) {
  47690. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47691. this.cameraRotation.x = 0;
  47692. }
  47693. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47694. this.cameraRotation.y = 0;
  47695. }
  47696. this.cameraRotation.scaleInPlace(this.inertia);
  47697. }
  47698. _super.prototype._checkInputs.call(this);
  47699. };
  47700. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47701. if (this.rotationQuaternion) {
  47702. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47703. }
  47704. else {
  47705. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47706. }
  47707. };
  47708. /**
  47709. * 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)
  47710. * @returns the current camera
  47711. */
  47712. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  47713. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  47714. return this;
  47715. };
  47716. /** @hidden */
  47717. TargetCamera.prototype._getViewMatrix = function () {
  47718. if (this.lockedTarget) {
  47719. this.setTarget(this._getLockedTargetPosition());
  47720. }
  47721. // Compute
  47722. this._updateCameraRotationMatrix();
  47723. // Apply the changed rotation to the upVector.
  47724. if (this._cachedRotationZ != this.rotation.z) {
  47725. this._rotateUpVectorWithCameraRotationMatrix();
  47726. this._cachedRotationZ = this.rotation.z;
  47727. }
  47728. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47729. // Computing target and final matrix
  47730. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47731. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  47732. return this._viewMatrix;
  47733. };
  47734. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47735. if (this.parent) {
  47736. var parentWorldMatrix = this.parent.getWorldMatrix();
  47737. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  47738. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47739. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47740. this._markSyncedWithParent();
  47741. }
  47742. else {
  47743. this._globalPosition.copyFrom(position);
  47744. this._globalCurrentTarget.copyFrom(target);
  47745. this._globalCurrentUpVector.copyFrom(up);
  47746. }
  47747. if (this.getScene().useRightHandedSystem) {
  47748. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47749. }
  47750. else {
  47751. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47752. }
  47753. };
  47754. /**
  47755. * @hidden
  47756. */
  47757. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47758. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47759. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47760. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47761. if (!this.rotationQuaternion) {
  47762. this.rotationQuaternion = new BABYLON.Quaternion();
  47763. }
  47764. rigCamera._cameraRigParams = {};
  47765. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47766. }
  47767. return rigCamera;
  47768. }
  47769. return null;
  47770. };
  47771. /**
  47772. * @hidden
  47773. */
  47774. TargetCamera.prototype._updateRigCameras = function () {
  47775. var camLeft = this._rigCameras[0];
  47776. var camRight = this._rigCameras[1];
  47777. switch (this.cameraRigMode) {
  47778. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47779. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47780. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47781. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47782. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47783. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47784. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47785. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47786. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47787. camLeft.setTarget(this.getTarget());
  47788. camRight.setTarget(this.getTarget());
  47789. break;
  47790. case BABYLON.Camera.RIG_MODE_VR:
  47791. if (camLeft.rotationQuaternion) {
  47792. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47793. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47794. }
  47795. else {
  47796. camLeft.rotation.copyFrom(this.rotation);
  47797. camRight.rotation.copyFrom(this.rotation);
  47798. }
  47799. camLeft.position.copyFrom(this.position);
  47800. camRight.position.copyFrom(this.position);
  47801. break;
  47802. }
  47803. _super.prototype._updateRigCameras.call(this);
  47804. };
  47805. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47806. if (!this._rigCamTransformMatrix) {
  47807. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47808. }
  47809. var target = this.getTarget();
  47810. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47811. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47812. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47813. };
  47814. /**
  47815. * Gets the current object class name.
  47816. * @return the class name
  47817. */
  47818. TargetCamera.prototype.getClassName = function () {
  47819. return "TargetCamera";
  47820. };
  47821. __decorate([
  47822. BABYLON.serializeAsVector3()
  47823. ], TargetCamera.prototype, "rotation", void 0);
  47824. __decorate([
  47825. BABYLON.serialize()
  47826. ], TargetCamera.prototype, "speed", void 0);
  47827. __decorate([
  47828. BABYLON.serializeAsMeshReference("lockedTargetId")
  47829. ], TargetCamera.prototype, "lockedTarget", void 0);
  47830. return TargetCamera;
  47831. }(BABYLON.Camera));
  47832. BABYLON.TargetCamera = TargetCamera;
  47833. })(BABYLON || (BABYLON = {}));
  47834. //# sourceMappingURL=babylon.targetCamera.js.map
  47835. var BABYLON;
  47836. (function (BABYLON) {
  47837. /**
  47838. * Manage the mouse inputs to control the movement of a free camera.
  47839. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47840. */
  47841. var FreeCameraMouseInput = /** @class */ (function () {
  47842. /**
  47843. * Manage the mouse inputs to control the movement of a free camera.
  47844. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47845. * @param touchEnabled Defines if touch is enabled or not
  47846. */
  47847. function FreeCameraMouseInput(
  47848. /**
  47849. * Define if touch is enabled in the mouse input
  47850. */
  47851. touchEnabled) {
  47852. if (touchEnabled === void 0) { touchEnabled = true; }
  47853. this.touchEnabled = touchEnabled;
  47854. /**
  47855. * Defines the buttons associated with the input to handle camera move.
  47856. */
  47857. this.buttons = [0, 1, 2];
  47858. /**
  47859. * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.
  47860. */
  47861. this.angularSensibility = 2000.0;
  47862. this.previousPosition = null;
  47863. }
  47864. /**
  47865. * Attach the input controls to a specific dom element to get the input from.
  47866. * @param element Defines the element the controls should be listened from
  47867. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47868. */
  47869. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47870. var _this = this;
  47871. var engine = this.camera.getEngine();
  47872. if (!this._pointerInput) {
  47873. this._pointerInput = function (p, s) {
  47874. var evt = p.event;
  47875. if (engine.isInVRExclusivePointerMode) {
  47876. return;
  47877. }
  47878. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47879. return;
  47880. }
  47881. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47882. return;
  47883. }
  47884. var srcElement = (evt.srcElement || evt.target);
  47885. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47886. try {
  47887. srcElement.setPointerCapture(evt.pointerId);
  47888. }
  47889. catch (e) {
  47890. //Nothing to do with the error. Execution will continue.
  47891. }
  47892. _this.previousPosition = {
  47893. x: evt.clientX,
  47894. y: evt.clientY
  47895. };
  47896. if (!noPreventDefault) {
  47897. evt.preventDefault();
  47898. element.focus();
  47899. }
  47900. }
  47901. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47902. try {
  47903. srcElement.releasePointerCapture(evt.pointerId);
  47904. }
  47905. catch (e) {
  47906. //Nothing to do with the error.
  47907. }
  47908. _this.previousPosition = null;
  47909. if (!noPreventDefault) {
  47910. evt.preventDefault();
  47911. }
  47912. }
  47913. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47914. if (!_this.previousPosition || engine.isPointerLock) {
  47915. return;
  47916. }
  47917. var offsetX = evt.clientX - _this.previousPosition.x;
  47918. if (_this.camera.getScene().useRightHandedSystem)
  47919. offsetX *= -1;
  47920. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47921. offsetX *= -1;
  47922. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47923. var offsetY = evt.clientY - _this.previousPosition.y;
  47924. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47925. _this.previousPosition = {
  47926. x: evt.clientX,
  47927. y: evt.clientY
  47928. };
  47929. if (!noPreventDefault) {
  47930. evt.preventDefault();
  47931. }
  47932. }
  47933. };
  47934. }
  47935. this._onMouseMove = function (evt) {
  47936. if (!engine.isPointerLock) {
  47937. return;
  47938. }
  47939. if (engine.isInVRExclusivePointerMode) {
  47940. return;
  47941. }
  47942. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47943. if (_this.camera.getScene().useRightHandedSystem)
  47944. offsetX *= -1;
  47945. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47946. offsetX *= -1;
  47947. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47948. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47949. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47950. _this.previousPosition = null;
  47951. if (!noPreventDefault) {
  47952. evt.preventDefault();
  47953. }
  47954. };
  47955. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47956. element.addEventListener("mousemove", this._onMouseMove, false);
  47957. };
  47958. /**
  47959. * Detach the current controls from the specified dom element.
  47960. * @param element Defines the element to stop listening the inputs from
  47961. */
  47962. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47963. if (this._observer && element) {
  47964. this.camera.getScene().onPointerObservable.remove(this._observer);
  47965. if (this._onMouseMove) {
  47966. element.removeEventListener("mousemove", this._onMouseMove);
  47967. }
  47968. this._observer = null;
  47969. this._onMouseMove = null;
  47970. this.previousPosition = null;
  47971. }
  47972. };
  47973. /**
  47974. * Gets the class name of the current intput.
  47975. * @returns the class name
  47976. */
  47977. FreeCameraMouseInput.prototype.getClassName = function () {
  47978. return "FreeCameraMouseInput";
  47979. };
  47980. /**
  47981. * Get the friendly name associated with the input class.
  47982. * @returns the input friendly name
  47983. */
  47984. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47985. return "mouse";
  47986. };
  47987. __decorate([
  47988. BABYLON.serialize()
  47989. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47990. __decorate([
  47991. BABYLON.serialize()
  47992. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47993. return FreeCameraMouseInput;
  47994. }());
  47995. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47996. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47997. })(BABYLON || (BABYLON = {}));
  47998. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47999. var BABYLON;
  48000. (function (BABYLON) {
  48001. /**
  48002. * Manage the keyboard inputs to control the movement of a free camera.
  48003. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48004. */
  48005. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  48006. function FreeCameraKeyboardMoveInput() {
  48007. /**
  48008. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  48009. */
  48010. this.keysUp = [38];
  48011. /**
  48012. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  48013. */
  48014. this.keysDown = [40];
  48015. /**
  48016. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  48017. */
  48018. this.keysLeft = [37];
  48019. /**
  48020. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  48021. */
  48022. this.keysRight = [39];
  48023. this._keys = new Array();
  48024. }
  48025. /**
  48026. * Attach the input controls to a specific dom element to get the input from.
  48027. * @param element Defines the element the controls should be listened from
  48028. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48029. */
  48030. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48031. var _this = this;
  48032. if (this._onCanvasBlurObserver) {
  48033. return;
  48034. }
  48035. this._scene = this.camera.getScene();
  48036. this._engine = this._scene.getEngine();
  48037. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48038. _this._keys = [];
  48039. });
  48040. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48041. var evt = info.event;
  48042. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48043. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48044. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48045. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48046. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  48047. var index = _this._keys.indexOf(evt.keyCode);
  48048. if (index === -1) {
  48049. _this._keys.push(evt.keyCode);
  48050. }
  48051. if (!noPreventDefault) {
  48052. evt.preventDefault();
  48053. }
  48054. }
  48055. }
  48056. else {
  48057. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48058. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48059. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48060. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  48061. var index = _this._keys.indexOf(evt.keyCode);
  48062. if (index >= 0) {
  48063. _this._keys.splice(index, 1);
  48064. }
  48065. if (!noPreventDefault) {
  48066. evt.preventDefault();
  48067. }
  48068. }
  48069. }
  48070. });
  48071. };
  48072. /**
  48073. * Detach the current controls from the specified dom element.
  48074. * @param element Defines the element to stop listening the inputs from
  48075. */
  48076. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48077. if (this._scene) {
  48078. if (this._onKeyboardObserver) {
  48079. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48080. }
  48081. if (this._onCanvasBlurObserver) {
  48082. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48083. }
  48084. this._onKeyboardObserver = null;
  48085. this._onCanvasBlurObserver = null;
  48086. }
  48087. this._keys = [];
  48088. };
  48089. /**
  48090. * Update the current camera state depending on the inputs that have been used this frame.
  48091. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  48092. */
  48093. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48094. if (this._onKeyboardObserver) {
  48095. var camera = this.camera;
  48096. // Keyboard
  48097. for (var index = 0; index < this._keys.length; index++) {
  48098. var keyCode = this._keys[index];
  48099. var speed = camera._computeLocalCameraSpeed();
  48100. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48101. camera._localDirection.copyFromFloats(-speed, 0, 0);
  48102. }
  48103. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48104. camera._localDirection.copyFromFloats(0, 0, speed);
  48105. }
  48106. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48107. camera._localDirection.copyFromFloats(speed, 0, 0);
  48108. }
  48109. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48110. camera._localDirection.copyFromFloats(0, 0, -speed);
  48111. }
  48112. if (camera.getScene().useRightHandedSystem) {
  48113. camera._localDirection.z *= -1;
  48114. }
  48115. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  48116. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  48117. camera.cameraDirection.addInPlace(camera._transformedDirection);
  48118. }
  48119. }
  48120. };
  48121. /**
  48122. * Gets the class name of the current intput.
  48123. * @returns the class name
  48124. */
  48125. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  48126. return "FreeCameraKeyboardMoveInput";
  48127. };
  48128. /** @hidden */
  48129. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  48130. this._keys = [];
  48131. };
  48132. /**
  48133. * Get the friendly name associated with the input class.
  48134. * @returns the input friendly name
  48135. */
  48136. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48137. return "keyboard";
  48138. };
  48139. __decorate([
  48140. BABYLON.serialize()
  48141. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48142. __decorate([
  48143. BABYLON.serialize()
  48144. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48145. __decorate([
  48146. BABYLON.serialize()
  48147. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48148. __decorate([
  48149. BABYLON.serialize()
  48150. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48151. return FreeCameraKeyboardMoveInput;
  48152. }());
  48153. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  48154. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  48155. })(BABYLON || (BABYLON = {}));
  48156. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  48157. var BABYLON;
  48158. (function (BABYLON) {
  48159. /**
  48160. * Default Inputs manager for the FreeCamera.
  48161. * It groups all the default supported inputs for ease of use.
  48162. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48163. */
  48164. var FreeCameraInputsManager = /** @class */ (function (_super) {
  48165. __extends(FreeCameraInputsManager, _super);
  48166. /**
  48167. * Instantiates a new FreeCameraInputsManager.
  48168. * @param camera Defines the camera the inputs belong to
  48169. */
  48170. function FreeCameraInputsManager(camera) {
  48171. return _super.call(this, camera) || this;
  48172. }
  48173. /**
  48174. * Add keyboard input support to the input manager.
  48175. * @returns the current input manager
  48176. */
  48177. FreeCameraInputsManager.prototype.addKeyboard = function () {
  48178. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  48179. return this;
  48180. };
  48181. /**
  48182. * Add mouse input support to the input manager.
  48183. * @returns the current input manager
  48184. */
  48185. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  48186. if (touchEnabled === void 0) { touchEnabled = true; }
  48187. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  48188. return this;
  48189. };
  48190. /**
  48191. * Add orientation input support to the input manager.
  48192. * @returns the current input manager
  48193. */
  48194. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  48195. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  48196. return this;
  48197. };
  48198. /**
  48199. * Add touch input support to the input manager.
  48200. * @returns the current input manager
  48201. */
  48202. FreeCameraInputsManager.prototype.addTouch = function () {
  48203. this.add(new BABYLON.FreeCameraTouchInput());
  48204. return this;
  48205. };
  48206. /**
  48207. * Add virtual joystick input support to the input manager.
  48208. * @returns the current input manager
  48209. */
  48210. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  48211. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  48212. return this;
  48213. };
  48214. return FreeCameraInputsManager;
  48215. }(BABYLON.CameraInputsManager));
  48216. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  48217. })(BABYLON || (BABYLON = {}));
  48218. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  48219. var BABYLON;
  48220. (function (BABYLON) {
  48221. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  48222. // Forcing to use the Universal camera
  48223. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  48224. });
  48225. /**
  48226. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  48227. * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad.
  48228. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  48229. */
  48230. var FreeCamera = /** @class */ (function (_super) {
  48231. __extends(FreeCamera, _super);
  48232. /**
  48233. * Instantiates a Free Camera.
  48234. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  48235. * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera.
  48236. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  48237. * @param name Define the name of the camera in the scene
  48238. * @param position Define the start position of the camera in the scene
  48239. * @param scene Define the scene the camera belongs to
  48240. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  48241. */
  48242. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  48243. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48244. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  48245. /**
  48246. * Define the collision ellipsoid of the camera.
  48247. * This is helpful to simulate a camera body like the player body around the camera
  48248. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  48249. */
  48250. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  48251. /**
  48252. * Define an offset for the position of the ellipsoid around the camera.
  48253. * This can be helpful to determine the center of the body near the gravity center of the body
  48254. * instead of its head.
  48255. */
  48256. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  48257. /**
  48258. * Enable or disable collisions of the camera with the rest of the scene objects.
  48259. */
  48260. _this.checkCollisions = false;
  48261. /**
  48262. * Enable or disable gravity on the camera.
  48263. */
  48264. _this.applyGravity = false;
  48265. _this._needMoveForGravity = false;
  48266. _this._oldPosition = BABYLON.Vector3.Zero();
  48267. _this._diffPosition = BABYLON.Vector3.Zero();
  48268. _this._newPosition = BABYLON.Vector3.Zero();
  48269. // Collisions
  48270. _this._collisionMask = -1;
  48271. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48272. if (collidedMesh === void 0) { collidedMesh = null; }
  48273. //TODO move this to the collision coordinator!
  48274. if (_this.getScene().workerCollisions)
  48275. newPosition.multiplyInPlace(_this._collider._radius);
  48276. var updatePosition = function (newPos) {
  48277. _this._newPosition.copyFrom(newPos);
  48278. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  48279. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  48280. _this.position.addInPlace(_this._diffPosition);
  48281. if (_this.onCollide && collidedMesh) {
  48282. _this.onCollide(collidedMesh);
  48283. }
  48284. }
  48285. };
  48286. updatePosition(newPosition);
  48287. };
  48288. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  48289. _this.inputs.addKeyboard().addMouse();
  48290. return _this;
  48291. }
  48292. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  48293. /**
  48294. * Gets the input sensibility for a mouse input. (default is 2000.0)
  48295. * Higher values reduce sensitivity.
  48296. */
  48297. get: function () {
  48298. var mouse = this.inputs.attached["mouse"];
  48299. if (mouse)
  48300. return mouse.angularSensibility;
  48301. return 0;
  48302. },
  48303. /**
  48304. * Sets the input sensibility for a mouse input. (default is 2000.0)
  48305. * Higher values reduce sensitivity.
  48306. */
  48307. set: function (value) {
  48308. var mouse = this.inputs.attached["mouse"];
  48309. if (mouse)
  48310. mouse.angularSensibility = value;
  48311. },
  48312. enumerable: true,
  48313. configurable: true
  48314. });
  48315. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  48316. /**
  48317. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  48318. */
  48319. get: function () {
  48320. var keyboard = this.inputs.attached["keyboard"];
  48321. if (keyboard)
  48322. return keyboard.keysUp;
  48323. return [];
  48324. },
  48325. set: function (value) {
  48326. var keyboard = this.inputs.attached["keyboard"];
  48327. if (keyboard)
  48328. keyboard.keysUp = value;
  48329. },
  48330. enumerable: true,
  48331. configurable: true
  48332. });
  48333. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  48334. /**
  48335. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  48336. */
  48337. get: function () {
  48338. var keyboard = this.inputs.attached["keyboard"];
  48339. if (keyboard)
  48340. return keyboard.keysDown;
  48341. return [];
  48342. },
  48343. set: function (value) {
  48344. var keyboard = this.inputs.attached["keyboard"];
  48345. if (keyboard)
  48346. keyboard.keysDown = value;
  48347. },
  48348. enumerable: true,
  48349. configurable: true
  48350. });
  48351. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  48352. /**
  48353. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  48354. */
  48355. get: function () {
  48356. var keyboard = this.inputs.attached["keyboard"];
  48357. if (keyboard)
  48358. return keyboard.keysLeft;
  48359. return [];
  48360. },
  48361. set: function (value) {
  48362. var keyboard = this.inputs.attached["keyboard"];
  48363. if (keyboard)
  48364. keyboard.keysLeft = value;
  48365. },
  48366. enumerable: true,
  48367. configurable: true
  48368. });
  48369. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  48370. /**
  48371. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  48372. */
  48373. get: function () {
  48374. var keyboard = this.inputs.attached["keyboard"];
  48375. if (keyboard)
  48376. return keyboard.keysRight;
  48377. return [];
  48378. },
  48379. set: function (value) {
  48380. var keyboard = this.inputs.attached["keyboard"];
  48381. if (keyboard)
  48382. keyboard.keysRight = value;
  48383. },
  48384. enumerable: true,
  48385. configurable: true
  48386. });
  48387. /**
  48388. * Attached controls to the current camera.
  48389. * @param element Defines the element the controls should be listened from
  48390. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48391. */
  48392. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  48393. this.inputs.attachElement(element, noPreventDefault);
  48394. };
  48395. /**
  48396. * Detach the current controls from the camera.
  48397. * The camera will stop reacting to inputs.
  48398. * @param element Defines the element to stop listening the inputs from
  48399. */
  48400. FreeCamera.prototype.detachControl = function (element) {
  48401. this.inputs.detachElement(element);
  48402. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  48403. this.cameraRotation = new BABYLON.Vector2(0, 0);
  48404. };
  48405. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  48406. /**
  48407. * Define a collision mask to limit the list of object the camera can collide with
  48408. */
  48409. get: function () {
  48410. return this._collisionMask;
  48411. },
  48412. set: function (mask) {
  48413. this._collisionMask = !isNaN(mask) ? mask : -1;
  48414. },
  48415. enumerable: true,
  48416. configurable: true
  48417. });
  48418. /** @hidden */
  48419. FreeCamera.prototype._collideWithWorld = function (displacement) {
  48420. var globalPosition;
  48421. if (this.parent) {
  48422. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  48423. }
  48424. else {
  48425. globalPosition = this.position;
  48426. }
  48427. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  48428. this._oldPosition.addInPlace(this.ellipsoidOffset);
  48429. if (!this._collider) {
  48430. this._collider = new BABYLON.Collider();
  48431. }
  48432. this._collider._radius = this.ellipsoid;
  48433. this._collider.collisionMask = this._collisionMask;
  48434. //no need for clone, as long as gravity is not on.
  48435. var actualDisplacement = displacement;
  48436. //add gravity to the direction to prevent the dual-collision checking
  48437. if (this.applyGravity) {
  48438. //this prevents mending with cameraDirection, a global variable of the free camera class.
  48439. actualDisplacement = displacement.add(this.getScene().gravity);
  48440. }
  48441. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48442. };
  48443. /** @hidden */
  48444. FreeCamera.prototype._checkInputs = function () {
  48445. if (!this._localDirection) {
  48446. this._localDirection = BABYLON.Vector3.Zero();
  48447. this._transformedDirection = BABYLON.Vector3.Zero();
  48448. }
  48449. this.inputs.checkInputs();
  48450. _super.prototype._checkInputs.call(this);
  48451. };
  48452. /** @hidden */
  48453. FreeCamera.prototype._decideIfNeedsToMove = function () {
  48454. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  48455. };
  48456. /** @hidden */
  48457. FreeCamera.prototype._updatePosition = function () {
  48458. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  48459. this._collideWithWorld(this.cameraDirection);
  48460. }
  48461. else {
  48462. _super.prototype._updatePosition.call(this);
  48463. }
  48464. };
  48465. /**
  48466. * Destroy the camera and release the current resources hold by it.
  48467. */
  48468. FreeCamera.prototype.dispose = function () {
  48469. this.inputs.clear();
  48470. _super.prototype.dispose.call(this);
  48471. };
  48472. /**
  48473. * Gets the current object class name.
  48474. * @return the class name
  48475. */
  48476. FreeCamera.prototype.getClassName = function () {
  48477. return "FreeCamera";
  48478. };
  48479. __decorate([
  48480. BABYLON.serializeAsVector3()
  48481. ], FreeCamera.prototype, "ellipsoid", void 0);
  48482. __decorate([
  48483. BABYLON.serializeAsVector3()
  48484. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  48485. __decorate([
  48486. BABYLON.serialize()
  48487. ], FreeCamera.prototype, "checkCollisions", void 0);
  48488. __decorate([
  48489. BABYLON.serialize()
  48490. ], FreeCamera.prototype, "applyGravity", void 0);
  48491. return FreeCamera;
  48492. }(BABYLON.TargetCamera));
  48493. BABYLON.FreeCamera = FreeCamera;
  48494. })(BABYLON || (BABYLON = {}));
  48495. //# sourceMappingURL=babylon.freeCamera.js.map
  48496. var BABYLON;
  48497. (function (BABYLON) {
  48498. /**
  48499. * Manage the keyboard inputs to control the movement of an arc rotate camera.
  48500. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48501. */
  48502. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  48503. function ArcRotateCameraKeyboardMoveInput() {
  48504. /**
  48505. * Defines the list of key codes associated with the up action (increase alpha)
  48506. */
  48507. this.keysUp = [38];
  48508. /**
  48509. * Defines the list of key codes associated with the down action (decrease alpha)
  48510. */
  48511. this.keysDown = [40];
  48512. /**
  48513. * Defines the list of key codes associated with the left action (increase beta)
  48514. */
  48515. this.keysLeft = [37];
  48516. /**
  48517. * Defines the list of key codes associated with the right action (decrease beta)
  48518. */
  48519. this.keysRight = [39];
  48520. /**
  48521. * Defines the list of key codes associated with the reset action.
  48522. * Those keys reset the camera to its last stored state (with the method camera.storeState())
  48523. */
  48524. this.keysReset = [220];
  48525. /**
  48526. * Defines the panning sensibility of the inputs.
  48527. * (How fast is the camera paning)
  48528. */
  48529. this.panningSensibility = 50.0;
  48530. /**
  48531. * Defines the zooming sensibility of the inputs.
  48532. * (How fast is the camera zooming)
  48533. */
  48534. this.zoomingSensibility = 25.0;
  48535. /**
  48536. * Defines wether maintaining the alt key down switch the movement mode from
  48537. * orientation to zoom.
  48538. */
  48539. this.useAltToZoom = true;
  48540. /**
  48541. * Rotation speed of the camera
  48542. */
  48543. this.angularSpeed = 0.01;
  48544. this._keys = new Array();
  48545. }
  48546. /**
  48547. * Attach the input controls to a specific dom element to get the input from.
  48548. * @param element Defines the element the controls should be listened from
  48549. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48550. */
  48551. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48552. var _this = this;
  48553. if (this._onCanvasBlurObserver) {
  48554. return;
  48555. }
  48556. this._scene = this.camera.getScene();
  48557. this._engine = this._scene.getEngine();
  48558. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48559. _this._keys = [];
  48560. });
  48561. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48562. var evt = info.event;
  48563. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48564. _this._ctrlPressed = evt.ctrlKey;
  48565. _this._altPressed = evt.altKey;
  48566. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48567. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48568. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48569. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48570. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48571. var index = _this._keys.indexOf(evt.keyCode);
  48572. if (index === -1) {
  48573. _this._keys.push(evt.keyCode);
  48574. }
  48575. if (evt.preventDefault) {
  48576. if (!noPreventDefault) {
  48577. evt.preventDefault();
  48578. }
  48579. }
  48580. }
  48581. }
  48582. else {
  48583. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48584. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48585. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48586. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48587. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48588. var index = _this._keys.indexOf(evt.keyCode);
  48589. if (index >= 0) {
  48590. _this._keys.splice(index, 1);
  48591. }
  48592. if (evt.preventDefault) {
  48593. if (!noPreventDefault) {
  48594. evt.preventDefault();
  48595. }
  48596. }
  48597. }
  48598. }
  48599. });
  48600. };
  48601. /**
  48602. * Detach the current controls from the specified dom element.
  48603. * @param element Defines the element to stop listening the inputs from
  48604. */
  48605. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48606. if (this._scene) {
  48607. if (this._onKeyboardObserver) {
  48608. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48609. }
  48610. if (this._onCanvasBlurObserver) {
  48611. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48612. }
  48613. this._onKeyboardObserver = null;
  48614. this._onCanvasBlurObserver = null;
  48615. }
  48616. this._keys = [];
  48617. };
  48618. /**
  48619. * Update the current camera state depending on the inputs that have been used this frame.
  48620. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  48621. */
  48622. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48623. if (this._onKeyboardObserver) {
  48624. var camera = this.camera;
  48625. for (var index = 0; index < this._keys.length; index++) {
  48626. var keyCode = this._keys[index];
  48627. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48628. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48629. camera.inertialPanningX -= 1 / this.panningSensibility;
  48630. }
  48631. else {
  48632. camera.inertialAlphaOffset -= this.angularSpeed;
  48633. }
  48634. }
  48635. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48636. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48637. camera.inertialPanningY += 1 / this.panningSensibility;
  48638. }
  48639. else if (this._altPressed && this.useAltToZoom) {
  48640. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  48641. }
  48642. else {
  48643. camera.inertialBetaOffset -= this.angularSpeed;
  48644. }
  48645. }
  48646. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48647. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48648. camera.inertialPanningX += 1 / this.panningSensibility;
  48649. }
  48650. else {
  48651. camera.inertialAlphaOffset += this.angularSpeed;
  48652. }
  48653. }
  48654. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48655. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48656. camera.inertialPanningY -= 1 / this.panningSensibility;
  48657. }
  48658. else if (this._altPressed && this.useAltToZoom) {
  48659. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  48660. }
  48661. else {
  48662. camera.inertialBetaOffset += this.angularSpeed;
  48663. }
  48664. }
  48665. else if (this.keysReset.indexOf(keyCode) !== -1) {
  48666. if (camera.useInputToRestoreState) {
  48667. camera.restoreState();
  48668. }
  48669. }
  48670. }
  48671. }
  48672. };
  48673. /**
  48674. * Gets the class name of the current intput.
  48675. * @returns the class name
  48676. */
  48677. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  48678. return "ArcRotateCameraKeyboardMoveInput";
  48679. };
  48680. /**
  48681. * Get the friendly name associated with the input class.
  48682. * @returns the input friendly name
  48683. */
  48684. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48685. return "keyboard";
  48686. };
  48687. __decorate([
  48688. BABYLON.serialize()
  48689. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48690. __decorate([
  48691. BABYLON.serialize()
  48692. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48693. __decorate([
  48694. BABYLON.serialize()
  48695. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48696. __decorate([
  48697. BABYLON.serialize()
  48698. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48699. __decorate([
  48700. BABYLON.serialize()
  48701. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  48702. __decorate([
  48703. BABYLON.serialize()
  48704. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  48705. __decorate([
  48706. BABYLON.serialize()
  48707. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  48708. __decorate([
  48709. BABYLON.serialize()
  48710. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  48711. __decorate([
  48712. BABYLON.serialize()
  48713. ], ArcRotateCameraKeyboardMoveInput.prototype, "angularSpeed", void 0);
  48714. return ArcRotateCameraKeyboardMoveInput;
  48715. }());
  48716. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  48717. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  48718. })(BABYLON || (BABYLON = {}));
  48719. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  48720. var BABYLON;
  48721. (function (BABYLON) {
  48722. /**
  48723. * Manage the mouse wheel inputs to control an arc rotate camera.
  48724. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48725. */
  48726. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  48727. function ArcRotateCameraMouseWheelInput() {
  48728. /**
  48729. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  48730. */
  48731. this.wheelPrecision = 3.0;
  48732. /**
  48733. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  48734. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  48735. */
  48736. this.wheelDeltaPercentage = 0;
  48737. }
  48738. /**
  48739. * Attach the input controls to a specific dom element to get the input from.
  48740. * @param element Defines the element the controls should be listened from
  48741. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48742. */
  48743. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  48744. var _this = this;
  48745. this._wheel = function (p, s) {
  48746. //sanity check - this should be a PointerWheel event.
  48747. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  48748. return;
  48749. var event = p.event;
  48750. var delta = 0;
  48751. if (event.wheelDelta) {
  48752. if (_this.wheelDeltaPercentage) {
  48753. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  48754. if (event.wheelDelta > 0) {
  48755. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  48756. }
  48757. else {
  48758. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  48759. }
  48760. }
  48761. else {
  48762. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  48763. }
  48764. }
  48765. else if (event.detail) {
  48766. delta = -event.detail / _this.wheelPrecision;
  48767. }
  48768. if (delta)
  48769. _this.camera.inertialRadiusOffset += delta;
  48770. if (event.preventDefault) {
  48771. if (!noPreventDefault) {
  48772. event.preventDefault();
  48773. }
  48774. }
  48775. };
  48776. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  48777. };
  48778. /**
  48779. * Detach the current controls from the specified dom element.
  48780. * @param element Defines the element to stop listening the inputs from
  48781. */
  48782. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  48783. if (this._observer && element) {
  48784. this.camera.getScene().onPointerObservable.remove(this._observer);
  48785. this._observer = null;
  48786. this._wheel = null;
  48787. }
  48788. };
  48789. /**
  48790. * Gets the class name of the current intput.
  48791. * @returns the class name
  48792. */
  48793. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  48794. return "ArcRotateCameraMouseWheelInput";
  48795. };
  48796. /**
  48797. * Get the friendly name associated with the input class.
  48798. * @returns the input friendly name
  48799. */
  48800. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  48801. return "mousewheel";
  48802. };
  48803. __decorate([
  48804. BABYLON.serialize()
  48805. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  48806. __decorate([
  48807. BABYLON.serialize()
  48808. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  48809. return ArcRotateCameraMouseWheelInput;
  48810. }());
  48811. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  48812. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  48813. })(BABYLON || (BABYLON = {}));
  48814. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  48815. var BABYLON;
  48816. (function (BABYLON) {
  48817. /**
  48818. * Manage the pointers inputs to control an arc rotate camera.
  48819. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48820. */
  48821. var ArcRotateCameraPointersInput = /** @class */ (function () {
  48822. function ArcRotateCameraPointersInput() {
  48823. /**
  48824. * Defines the buttons associated with the input to handle camera move.
  48825. */
  48826. this.buttons = [0, 1, 2];
  48827. /**
  48828. * Defines the pointer angular sensibility along the X axis or how fast is the camera rotating.
  48829. */
  48830. this.angularSensibilityX = 1000.0;
  48831. /**
  48832. * Defines the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  48833. */
  48834. this.angularSensibilityY = 1000.0;
  48835. /**
  48836. * Defines the pointer pinch precision or how fast is the camera zooming.
  48837. */
  48838. this.pinchPrecision = 12.0;
  48839. /**
  48840. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  48841. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48842. */
  48843. this.pinchDeltaPercentage = 0;
  48844. /**
  48845. * Defines the pointer panning sensibility or how fast is the camera moving.
  48846. */
  48847. this.panningSensibility = 1000.0;
  48848. /**
  48849. * Defines whether panning (2 fingers swipe) is enabled through multitouch.
  48850. */
  48851. this.multiTouchPanning = true;
  48852. /**
  48853. * Defines whether panning is enabled for both pan (2 fingers swipe) and zoom (pinch) through multitouch.
  48854. */
  48855. this.multiTouchPanAndZoom = true;
  48856. /**
  48857. * Revers pinch action direction.
  48858. */
  48859. this.pinchInwards = true;
  48860. this._isPanClick = false;
  48861. }
  48862. /**
  48863. * Attach the input controls to a specific dom element to get the input from.
  48864. * @param element Defines the element the controls should be listened from
  48865. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48866. */
  48867. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  48868. var _this = this;
  48869. var engine = this.camera.getEngine();
  48870. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  48871. var pointA = null;
  48872. var pointB = null;
  48873. var previousPinchSquaredDistance = 0;
  48874. var initialDistance = 0;
  48875. var twoFingerActivityCount = 0;
  48876. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  48877. this._pointerInput = function (p, s) {
  48878. var evt = p.event;
  48879. var isTouch = p.event.pointerType === "touch";
  48880. if (engine.isInVRExclusivePointerMode) {
  48881. return;
  48882. }
  48883. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48884. return;
  48885. }
  48886. var srcElement = (evt.srcElement || evt.target);
  48887. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48888. try {
  48889. srcElement.setPointerCapture(evt.pointerId);
  48890. }
  48891. catch (e) {
  48892. //Nothing to do with the error. Execution will continue.
  48893. }
  48894. // Manage panning with pan button click
  48895. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  48896. // manage pointers
  48897. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  48898. if (pointA === null) {
  48899. pointA = cacheSoloPointer;
  48900. }
  48901. else if (pointB === null) {
  48902. pointB = cacheSoloPointer;
  48903. }
  48904. if (!noPreventDefault) {
  48905. evt.preventDefault();
  48906. element.focus();
  48907. }
  48908. }
  48909. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  48910. if (_this.camera.useInputToRestoreState) {
  48911. _this.camera.restoreState();
  48912. }
  48913. }
  48914. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48915. try {
  48916. srcElement.releasePointerCapture(evt.pointerId);
  48917. }
  48918. catch (e) {
  48919. //Nothing to do with the error.
  48920. }
  48921. cacheSoloPointer = null;
  48922. previousPinchSquaredDistance = 0;
  48923. previousMultiTouchPanPosition.isPaning = false;
  48924. previousMultiTouchPanPosition.isPinching = false;
  48925. twoFingerActivityCount = 0;
  48926. initialDistance = 0;
  48927. if (!isTouch) {
  48928. pointB = null; // Mouse and pen are mono pointer
  48929. }
  48930. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48931. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48932. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48933. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48934. if (engine._badOS) {
  48935. pointA = pointB = null;
  48936. }
  48937. else {
  48938. //only remove the impacted pointer in case of multitouch allowing on most
  48939. //platforms switching from rotate to zoom and pan seamlessly.
  48940. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48941. pointA = pointB;
  48942. pointB = null;
  48943. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48944. }
  48945. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48946. pointB = null;
  48947. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48948. }
  48949. else {
  48950. pointA = pointB = null;
  48951. }
  48952. }
  48953. if (!noPreventDefault) {
  48954. evt.preventDefault();
  48955. }
  48956. }
  48957. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48958. if (!noPreventDefault) {
  48959. evt.preventDefault();
  48960. }
  48961. // One button down
  48962. if (pointA && pointB === null && cacheSoloPointer) {
  48963. if (_this.panningSensibility !== 0 &&
  48964. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48965. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48966. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48967. }
  48968. else {
  48969. var offsetX = evt.clientX - cacheSoloPointer.x;
  48970. var offsetY = evt.clientY - cacheSoloPointer.y;
  48971. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48972. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48973. }
  48974. cacheSoloPointer.x = evt.clientX;
  48975. cacheSoloPointer.y = evt.clientY;
  48976. }
  48977. // Two buttons down: pinch/pan
  48978. else if (pointA && pointB) {
  48979. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48980. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48981. ed.x = evt.clientX;
  48982. ed.y = evt.clientY;
  48983. var direction = _this.pinchInwards ? 1 : -1;
  48984. var distX = pointA.x - pointB.x;
  48985. var distY = pointA.y - pointB.y;
  48986. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48987. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48988. if (previousPinchSquaredDistance === 0) {
  48989. initialDistance = pinchDistance;
  48990. previousPinchSquaredDistance = pinchSquaredDistance;
  48991. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48992. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48993. return;
  48994. }
  48995. if (_this.multiTouchPanAndZoom) {
  48996. if (_this.pinchDeltaPercentage) {
  48997. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48998. }
  48999. else {
  49000. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  49001. (_this.pinchPrecision *
  49002. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  49003. direction);
  49004. }
  49005. if (_this.panningSensibility !== 0) {
  49006. var pointersCenterX = (pointA.x + pointB.x) / 2;
  49007. var pointersCenterY = (pointA.y + pointB.y) / 2;
  49008. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  49009. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  49010. previousMultiTouchPanPosition.x = pointersCenterX;
  49011. previousMultiTouchPanPosition.y = pointersCenterY;
  49012. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  49013. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  49014. }
  49015. }
  49016. else {
  49017. twoFingerActivityCount++;
  49018. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  49019. if (_this.pinchDeltaPercentage) {
  49020. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  49021. }
  49022. else {
  49023. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  49024. (_this.pinchPrecision *
  49025. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  49026. direction);
  49027. }
  49028. previousMultiTouchPanPosition.isPaning = false;
  49029. previousMultiTouchPanPosition.isPinching = true;
  49030. }
  49031. else {
  49032. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  49033. if (!previousMultiTouchPanPosition.isPaning) {
  49034. previousMultiTouchPanPosition.isPaning = true;
  49035. previousMultiTouchPanPosition.isPinching = false;
  49036. previousMultiTouchPanPosition.x = ed.x;
  49037. previousMultiTouchPanPosition.y = ed.y;
  49038. return;
  49039. }
  49040. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  49041. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  49042. }
  49043. }
  49044. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  49045. previousMultiTouchPanPosition.x = ed.x;
  49046. previousMultiTouchPanPosition.y = ed.y;
  49047. }
  49048. }
  49049. previousPinchSquaredDistance = pinchSquaredDistance;
  49050. }
  49051. }
  49052. };
  49053. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  49054. this._onContextMenu = function (evt) {
  49055. evt.preventDefault();
  49056. };
  49057. if (!this.camera._useCtrlForPanning) {
  49058. element.addEventListener("contextmenu", this._onContextMenu, false);
  49059. }
  49060. this._onLostFocus = function () {
  49061. //this._keys = [];
  49062. pointA = pointB = null;
  49063. previousPinchSquaredDistance = 0;
  49064. previousMultiTouchPanPosition.isPaning = false;
  49065. previousMultiTouchPanPosition.isPinching = false;
  49066. twoFingerActivityCount = 0;
  49067. cacheSoloPointer = null;
  49068. initialDistance = 0;
  49069. };
  49070. this._onMouseMove = function (evt) {
  49071. if (!engine.isPointerLock) {
  49072. return;
  49073. }
  49074. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  49075. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  49076. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  49077. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  49078. if (!noPreventDefault) {
  49079. evt.preventDefault();
  49080. }
  49081. };
  49082. this._onGestureStart = function (e) {
  49083. if (window.MSGesture === undefined) {
  49084. return;
  49085. }
  49086. if (!_this._MSGestureHandler) {
  49087. _this._MSGestureHandler = new MSGesture();
  49088. _this._MSGestureHandler.target = element;
  49089. }
  49090. _this._MSGestureHandler.addPointer(e.pointerId);
  49091. };
  49092. this._onGesture = function (e) {
  49093. _this.camera.radius *= e.scale;
  49094. if (e.preventDefault) {
  49095. if (!noPreventDefault) {
  49096. e.stopPropagation();
  49097. e.preventDefault();
  49098. }
  49099. }
  49100. };
  49101. element.addEventListener("mousemove", this._onMouseMove, false);
  49102. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  49103. element.addEventListener("MSGestureChange", this._onGesture, false);
  49104. BABYLON.Tools.RegisterTopRootEvents([
  49105. { name: "blur", handler: this._onLostFocus }
  49106. ]);
  49107. };
  49108. /**
  49109. * Detach the current controls from the specified dom element.
  49110. * @param element Defines the element to stop listening the inputs from
  49111. */
  49112. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  49113. if (this._onLostFocus) {
  49114. BABYLON.Tools.UnregisterTopRootEvents([
  49115. { name: "blur", handler: this._onLostFocus }
  49116. ]);
  49117. }
  49118. if (element && this._observer) {
  49119. this.camera.getScene().onPointerObservable.remove(this._observer);
  49120. this._observer = null;
  49121. if (this._onContextMenu) {
  49122. element.removeEventListener("contextmenu", this._onContextMenu);
  49123. }
  49124. if (this._onMouseMove) {
  49125. element.removeEventListener("mousemove", this._onMouseMove);
  49126. }
  49127. if (this._onGestureStart) {
  49128. element.removeEventListener("MSPointerDown", this._onGestureStart);
  49129. }
  49130. if (this._onGesture) {
  49131. element.removeEventListener("MSGestureChange", this._onGesture);
  49132. }
  49133. this._isPanClick = false;
  49134. this.pinchInwards = true;
  49135. this._onMouseMove = null;
  49136. this._onGestureStart = null;
  49137. this._onGesture = null;
  49138. this._MSGestureHandler = null;
  49139. this._onLostFocus = null;
  49140. this._onContextMenu = null;
  49141. }
  49142. };
  49143. /**
  49144. * Gets the class name of the current intput.
  49145. * @returns the class name
  49146. */
  49147. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  49148. return "ArcRotateCameraPointersInput";
  49149. };
  49150. /**
  49151. * Get the friendly name associated with the input class.
  49152. * @returns the input friendly name
  49153. */
  49154. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  49155. return "pointers";
  49156. };
  49157. __decorate([
  49158. BABYLON.serialize()
  49159. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  49160. __decorate([
  49161. BABYLON.serialize()
  49162. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  49163. __decorate([
  49164. BABYLON.serialize()
  49165. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  49166. __decorate([
  49167. BABYLON.serialize()
  49168. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  49169. __decorate([
  49170. BABYLON.serialize()
  49171. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  49172. __decorate([
  49173. BABYLON.serialize()
  49174. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  49175. __decorate([
  49176. BABYLON.serialize()
  49177. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  49178. __decorate([
  49179. BABYLON.serialize()
  49180. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  49181. return ArcRotateCameraPointersInput;
  49182. }());
  49183. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  49184. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  49185. })(BABYLON || (BABYLON = {}));
  49186. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  49187. var BABYLON;
  49188. (function (BABYLON) {
  49189. /**
  49190. * Default Inputs manager for the ArcRotateCamera.
  49191. * It groups all the default supported inputs for ease of use.
  49192. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49193. */
  49194. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  49195. __extends(ArcRotateCameraInputsManager, _super);
  49196. /**
  49197. * Instantiates a new ArcRotateCameraInputsManager.
  49198. * @param camera Defines the camera the inputs belong to
  49199. */
  49200. function ArcRotateCameraInputsManager(camera) {
  49201. return _super.call(this, camera) || this;
  49202. }
  49203. /**
  49204. * Add mouse wheel input support to the input manager.
  49205. * @returns the current input manager
  49206. */
  49207. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  49208. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  49209. return this;
  49210. };
  49211. /**
  49212. * Add pointers input support to the input manager.
  49213. * @returns the current input manager
  49214. */
  49215. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  49216. this.add(new BABYLON.ArcRotateCameraPointersInput());
  49217. return this;
  49218. };
  49219. /**
  49220. * Add keyboard input support to the input manager.
  49221. * @returns the current input manager
  49222. */
  49223. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  49224. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  49225. return this;
  49226. };
  49227. /**
  49228. * Add orientation input support to the input manager.
  49229. * @returns the current input manager
  49230. */
  49231. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  49232. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  49233. return this;
  49234. };
  49235. return ArcRotateCameraInputsManager;
  49236. }(BABYLON.CameraInputsManager));
  49237. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  49238. })(BABYLON || (BABYLON = {}));
  49239. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  49240. var BABYLON;
  49241. (function (BABYLON) {
  49242. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  49243. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  49244. });
  49245. /**
  49246. * This represents an orbital type of camera.
  49247. *
  49248. * This camera always points towards a given target position and can be rotated around that target with the target as the centre of rotation. It can be controlled with cursors and mouse, or with touch events.
  49249. * Think of this camera as one orbiting its target position, or more imaginatively as a spy satellite orbiting the earth. Its position relative to the target (earth) can be set by three parameters, alpha (radians) the longitudinal rotation, beta (radians) the latitudinal rotation and radius the distance from the target position.
  49250. * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera
  49251. */
  49252. var ArcRotateCamera = /** @class */ (function (_super) {
  49253. __extends(ArcRotateCamera, _super);
  49254. /**
  49255. * Instantiates a new ArcRotateCamera in a given scene
  49256. * @param name Defines the name of the camera
  49257. * @param alpha Defines the camera rotation along the logitudinal axis
  49258. * @param beta Defines the camera rotation along the latitudinal axis
  49259. * @param radius Defines the camera distance from its target
  49260. * @param target Defines the camera target
  49261. * @param scene Defines the scene the camera belongs to
  49262. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  49263. */
  49264. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  49265. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  49266. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  49267. /**
  49268. * Current inertia value on the longitudinal axis.
  49269. * The bigger this number the longer it will take for the camera to stop.
  49270. */
  49271. _this.inertialAlphaOffset = 0;
  49272. /**
  49273. * Current inertia value on the latitudinal axis.
  49274. * The bigger this number the longer it will take for the camera to stop.
  49275. */
  49276. _this.inertialBetaOffset = 0;
  49277. /**
  49278. * Current inertia value on the radius axis.
  49279. * The bigger this number the longer it will take for the camera to stop.
  49280. */
  49281. _this.inertialRadiusOffset = 0;
  49282. /**
  49283. * Minimum allowed angle on the longitudinal axis.
  49284. * This can help limiting how the Camera is able to move in the scene.
  49285. */
  49286. _this.lowerAlphaLimit = null;
  49287. /**
  49288. * Maximum allowed angle on the longitudinal axis.
  49289. * This can help limiting how the Camera is able to move in the scene.
  49290. */
  49291. _this.upperAlphaLimit = null;
  49292. /**
  49293. * Minimum allowed angle on the latitudinal axis.
  49294. * This can help limiting how the Camera is able to move in the scene.
  49295. */
  49296. _this.lowerBetaLimit = 0.01;
  49297. /**
  49298. * Maximum allowed angle on the latitudinal axis.
  49299. * This can help limiting how the Camera is able to move in the scene.
  49300. */
  49301. _this.upperBetaLimit = Math.PI;
  49302. /**
  49303. * Minimum allowed distance of the camera to the target (The camera can not get closer).
  49304. * This can help limiting how the Camera is able to move in the scene.
  49305. */
  49306. _this.lowerRadiusLimit = null;
  49307. /**
  49308. * Maximum allowed distance of the camera to the target (The camera can not get further).
  49309. * This can help limiting how the Camera is able to move in the scene.
  49310. */
  49311. _this.upperRadiusLimit = null;
  49312. /**
  49313. * Defines the current inertia value used during panning of the camera along the X axis.
  49314. */
  49315. _this.inertialPanningX = 0;
  49316. /**
  49317. * Defines the current inertia value used during panning of the camera along the Y axis.
  49318. */
  49319. _this.inertialPanningY = 0;
  49320. /**
  49321. * Defines the distance used to consider the camera in pan mode vs pinch/zoom.
  49322. * Basically if your fingers moves away from more than this distance you will be considered
  49323. * in pinch mode.
  49324. */
  49325. _this.pinchToPanMaxDistance = 20;
  49326. /**
  49327. * Defines the maximum distance the camera can pan.
  49328. * This could help keeping the cammera always in your scene.
  49329. */
  49330. _this.panningDistanceLimit = null;
  49331. /**
  49332. * Defines the target of the camera before paning.
  49333. */
  49334. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  49335. /**
  49336. * Defines the value of the inertia used during panning.
  49337. * 0 would mean stop inertia and one would mean no decelleration at all.
  49338. */
  49339. _this.panningInertia = 0.9;
  49340. //-- end properties for backward compatibility for inputs
  49341. /**
  49342. * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function)
  49343. */
  49344. _this.zoomOnFactor = 1;
  49345. /**
  49346. * Defines a screen offset for the camera position.
  49347. */
  49348. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  49349. /**
  49350. * Allows the camera to be completely reversed.
  49351. * If false the camera can not arrive upside down.
  49352. */
  49353. _this.allowUpsideDown = true;
  49354. /**
  49355. * Define if double tap/click is used to restore the previously saved state of the camera.
  49356. */
  49357. _this.useInputToRestoreState = true;
  49358. /** @hidden */
  49359. _this._viewMatrix = new BABYLON.Matrix();
  49360. /**
  49361. * Defines the allowed panning axis.
  49362. */
  49363. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  49364. /**
  49365. * Observable triggered when the mesh target has been changed on the camera.
  49366. */
  49367. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  49368. /**
  49369. * Defines whether the camera should check collision with the objects oh the scene.
  49370. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this
  49371. */
  49372. _this.checkCollisions = false;
  49373. /**
  49374. * Defines the collision radius of the camera.
  49375. * This simulates a sphere around the camera.
  49376. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  49377. */
  49378. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  49379. _this._previousPosition = BABYLON.Vector3.Zero();
  49380. _this._collisionVelocity = BABYLON.Vector3.Zero();
  49381. _this._newPosition = BABYLON.Vector3.Zero();
  49382. _this._computationVector = BABYLON.Vector3.Zero();
  49383. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  49384. if (collidedMesh === void 0) { collidedMesh = null; }
  49385. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  49386. newPosition.multiplyInPlace(_this._collider._radius);
  49387. }
  49388. if (!collidedMesh) {
  49389. _this._previousPosition.copyFrom(_this.position);
  49390. }
  49391. else {
  49392. _this.setPosition(newPosition);
  49393. if (_this.onCollide) {
  49394. _this.onCollide(collidedMesh);
  49395. }
  49396. }
  49397. // Recompute because of constraints
  49398. var cosa = Math.cos(_this.alpha);
  49399. var sina = Math.sin(_this.alpha);
  49400. var cosb = Math.cos(_this.beta);
  49401. var sinb = Math.sin(_this.beta);
  49402. if (sinb === 0) {
  49403. sinb = 0.0001;
  49404. }
  49405. var target = _this._getTargetPosition();
  49406. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  49407. target.addToRef(_this._computationVector, _this._newPosition);
  49408. _this.position.copyFrom(_this._newPosition);
  49409. var up = _this.upVector;
  49410. if (_this.allowUpsideDown && _this.beta < 0) {
  49411. up = up.clone();
  49412. up = up.negate();
  49413. }
  49414. _this._computeViewMatrix(_this.position, target, up);
  49415. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  49416. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  49417. _this._collisionTriggered = false;
  49418. };
  49419. _this._target = BABYLON.Vector3.Zero();
  49420. if (target) {
  49421. _this.setTarget(target);
  49422. }
  49423. _this.alpha = alpha;
  49424. _this.beta = beta;
  49425. _this.radius = radius;
  49426. _this.getViewMatrix();
  49427. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  49428. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  49429. return _this;
  49430. }
  49431. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  49432. /**
  49433. * Defines the target point of the camera.
  49434. * The camera looks towards it form the radius distance.
  49435. */
  49436. get: function () {
  49437. return this._target;
  49438. },
  49439. set: function (value) {
  49440. this.setTarget(value);
  49441. },
  49442. enumerable: true,
  49443. configurable: true
  49444. });
  49445. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  49446. //-- begin properties for backward compatibility for inputs
  49447. /**
  49448. * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
  49449. */
  49450. get: function () {
  49451. var pointers = this.inputs.attached["pointers"];
  49452. if (pointers)
  49453. return pointers.angularSensibilityX;
  49454. return 0;
  49455. },
  49456. set: function (value) {
  49457. var pointers = this.inputs.attached["pointers"];
  49458. if (pointers) {
  49459. pointers.angularSensibilityX = value;
  49460. }
  49461. },
  49462. enumerable: true,
  49463. configurable: true
  49464. });
  49465. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  49466. /**
  49467. * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  49468. */
  49469. get: function () {
  49470. var pointers = this.inputs.attached["pointers"];
  49471. if (pointers)
  49472. return pointers.angularSensibilityY;
  49473. return 0;
  49474. },
  49475. set: function (value) {
  49476. var pointers = this.inputs.attached["pointers"];
  49477. if (pointers) {
  49478. pointers.angularSensibilityY = value;
  49479. }
  49480. },
  49481. enumerable: true,
  49482. configurable: true
  49483. });
  49484. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  49485. /**
  49486. * Gets or Set the pointer pinch precision or how fast is the camera zooming.
  49487. */
  49488. get: function () {
  49489. var pointers = this.inputs.attached["pointers"];
  49490. if (pointers)
  49491. return pointers.pinchPrecision;
  49492. return 0;
  49493. },
  49494. set: function (value) {
  49495. var pointers = this.inputs.attached["pointers"];
  49496. if (pointers) {
  49497. pointers.pinchPrecision = value;
  49498. }
  49499. },
  49500. enumerable: true,
  49501. configurable: true
  49502. });
  49503. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  49504. /**
  49505. * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
  49506. * It will be used instead of pinchDeltaPrecision if different from 0.
  49507. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  49508. */
  49509. get: function () {
  49510. var pointers = this.inputs.attached["pointers"];
  49511. if (pointers)
  49512. return pointers.pinchDeltaPercentage;
  49513. return 0;
  49514. },
  49515. set: function (value) {
  49516. var pointers = this.inputs.attached["pointers"];
  49517. if (pointers) {
  49518. pointers.pinchDeltaPercentage = value;
  49519. }
  49520. },
  49521. enumerable: true,
  49522. configurable: true
  49523. });
  49524. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  49525. /**
  49526. * Gets or Set the pointer panning sensibility or how fast is the camera moving.
  49527. */
  49528. get: function () {
  49529. var pointers = this.inputs.attached["pointers"];
  49530. if (pointers)
  49531. return pointers.panningSensibility;
  49532. return 0;
  49533. },
  49534. set: function (value) {
  49535. var pointers = this.inputs.attached["pointers"];
  49536. if (pointers) {
  49537. pointers.panningSensibility = value;
  49538. }
  49539. },
  49540. enumerable: true,
  49541. configurable: true
  49542. });
  49543. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  49544. /**
  49545. * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
  49546. */
  49547. get: function () {
  49548. var keyboard = this.inputs.attached["keyboard"];
  49549. if (keyboard)
  49550. return keyboard.keysUp;
  49551. return [];
  49552. },
  49553. set: function (value) {
  49554. var keyboard = this.inputs.attached["keyboard"];
  49555. if (keyboard)
  49556. keyboard.keysUp = value;
  49557. },
  49558. enumerable: true,
  49559. configurable: true
  49560. });
  49561. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  49562. /**
  49563. * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
  49564. */
  49565. get: function () {
  49566. var keyboard = this.inputs.attached["keyboard"];
  49567. if (keyboard)
  49568. return keyboard.keysDown;
  49569. return [];
  49570. },
  49571. set: function (value) {
  49572. var keyboard = this.inputs.attached["keyboard"];
  49573. if (keyboard)
  49574. keyboard.keysDown = value;
  49575. },
  49576. enumerable: true,
  49577. configurable: true
  49578. });
  49579. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  49580. /**
  49581. * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
  49582. */
  49583. get: function () {
  49584. var keyboard = this.inputs.attached["keyboard"];
  49585. if (keyboard)
  49586. return keyboard.keysLeft;
  49587. return [];
  49588. },
  49589. set: function (value) {
  49590. var keyboard = this.inputs.attached["keyboard"];
  49591. if (keyboard)
  49592. keyboard.keysLeft = value;
  49593. },
  49594. enumerable: true,
  49595. configurable: true
  49596. });
  49597. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  49598. /**
  49599. * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
  49600. */
  49601. get: function () {
  49602. var keyboard = this.inputs.attached["keyboard"];
  49603. if (keyboard)
  49604. return keyboard.keysRight;
  49605. return [];
  49606. },
  49607. set: function (value) {
  49608. var keyboard = this.inputs.attached["keyboard"];
  49609. if (keyboard)
  49610. keyboard.keysRight = value;
  49611. },
  49612. enumerable: true,
  49613. configurable: true
  49614. });
  49615. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  49616. /**
  49617. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  49618. */
  49619. get: function () {
  49620. var mousewheel = this.inputs.attached["mousewheel"];
  49621. if (mousewheel)
  49622. return mousewheel.wheelPrecision;
  49623. return 0;
  49624. },
  49625. set: function (value) {
  49626. var mousewheel = this.inputs.attached["mousewheel"];
  49627. if (mousewheel)
  49628. mousewheel.wheelPrecision = value;
  49629. },
  49630. enumerable: true,
  49631. configurable: true
  49632. });
  49633. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  49634. /**
  49635. * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
  49636. * It will be used instead of pinchDeltaPrecision if different from 0.
  49637. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  49638. */
  49639. get: function () {
  49640. var mousewheel = this.inputs.attached["mousewheel"];
  49641. if (mousewheel)
  49642. return mousewheel.wheelDeltaPercentage;
  49643. return 0;
  49644. },
  49645. set: function (value) {
  49646. var mousewheel = this.inputs.attached["mousewheel"];
  49647. if (mousewheel)
  49648. mousewheel.wheelDeltaPercentage = value;
  49649. },
  49650. enumerable: true,
  49651. configurable: true
  49652. });
  49653. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  49654. /**
  49655. * Gets the bouncing behavior of the camera if it has been enabled.
  49656. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  49657. */
  49658. get: function () {
  49659. return this._bouncingBehavior;
  49660. },
  49661. enumerable: true,
  49662. configurable: true
  49663. });
  49664. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  49665. /**
  49666. * Defines if the bouncing behavior of the camera is enabled on the camera.
  49667. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  49668. */
  49669. get: function () {
  49670. return this._bouncingBehavior != null;
  49671. },
  49672. set: function (value) {
  49673. if (value === this.useBouncingBehavior) {
  49674. return;
  49675. }
  49676. if (value) {
  49677. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  49678. this.addBehavior(this._bouncingBehavior);
  49679. }
  49680. else if (this._bouncingBehavior) {
  49681. this.removeBehavior(this._bouncingBehavior);
  49682. this._bouncingBehavior = null;
  49683. }
  49684. },
  49685. enumerable: true,
  49686. configurable: true
  49687. });
  49688. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  49689. /**
  49690. * Gets the framing behavior of the camera if it has been enabled.
  49691. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  49692. */
  49693. get: function () {
  49694. return this._framingBehavior;
  49695. },
  49696. enumerable: true,
  49697. configurable: true
  49698. });
  49699. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  49700. /**
  49701. * Defines if the framing behavior of the camera is enabled on the camera.
  49702. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  49703. */
  49704. get: function () {
  49705. return this._framingBehavior != null;
  49706. },
  49707. set: function (value) {
  49708. if (value === this.useFramingBehavior) {
  49709. return;
  49710. }
  49711. if (value) {
  49712. this._framingBehavior = new BABYLON.FramingBehavior();
  49713. this.addBehavior(this._framingBehavior);
  49714. }
  49715. else if (this._framingBehavior) {
  49716. this.removeBehavior(this._framingBehavior);
  49717. this._framingBehavior = null;
  49718. }
  49719. },
  49720. enumerable: true,
  49721. configurable: true
  49722. });
  49723. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  49724. /**
  49725. * Gets the auto rotation behavior of the camera if it has been enabled.
  49726. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  49727. */
  49728. get: function () {
  49729. return this._autoRotationBehavior;
  49730. },
  49731. enumerable: true,
  49732. configurable: true
  49733. });
  49734. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  49735. /**
  49736. * Defines if the auto rotation behavior of the camera is enabled on the camera.
  49737. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  49738. */
  49739. get: function () {
  49740. return this._autoRotationBehavior != null;
  49741. },
  49742. set: function (value) {
  49743. if (value === this.useAutoRotationBehavior) {
  49744. return;
  49745. }
  49746. if (value) {
  49747. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  49748. this.addBehavior(this._autoRotationBehavior);
  49749. }
  49750. else if (this._autoRotationBehavior) {
  49751. this.removeBehavior(this._autoRotationBehavior);
  49752. this._autoRotationBehavior = null;
  49753. }
  49754. },
  49755. enumerable: true,
  49756. configurable: true
  49757. });
  49758. // Cache
  49759. /** @hidden */
  49760. ArcRotateCamera.prototype._initCache = function () {
  49761. _super.prototype._initCache.call(this);
  49762. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  49763. this._cache.alpha = undefined;
  49764. this._cache.beta = undefined;
  49765. this._cache.radius = undefined;
  49766. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  49767. };
  49768. /** @hidden */
  49769. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  49770. if (!ignoreParentClass) {
  49771. _super.prototype._updateCache.call(this);
  49772. }
  49773. this._cache._target.copyFrom(this._getTargetPosition());
  49774. this._cache.alpha = this.alpha;
  49775. this._cache.beta = this.beta;
  49776. this._cache.radius = this.radius;
  49777. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  49778. };
  49779. ArcRotateCamera.prototype._getTargetPosition = function () {
  49780. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  49781. var pos = this._targetHost.getAbsolutePosition();
  49782. if (this._targetBoundingCenter) {
  49783. pos.addToRef(this._targetBoundingCenter, this._target);
  49784. }
  49785. else {
  49786. this._target.copyFrom(pos);
  49787. }
  49788. }
  49789. var lockedTargetPosition = this._getLockedTargetPosition();
  49790. if (lockedTargetPosition) {
  49791. return lockedTargetPosition;
  49792. }
  49793. return this._target;
  49794. };
  49795. /**
  49796. * Stores the current state of the camera (alpha, beta, radius and target)
  49797. * @returns the camera itself
  49798. */
  49799. ArcRotateCamera.prototype.storeState = function () {
  49800. this._storedAlpha = this.alpha;
  49801. this._storedBeta = this.beta;
  49802. this._storedRadius = this.radius;
  49803. this._storedTarget = this._getTargetPosition().clone();
  49804. return _super.prototype.storeState.call(this);
  49805. };
  49806. /**
  49807. * @hidden
  49808. * Restored camera state. You must call storeState() first
  49809. */
  49810. ArcRotateCamera.prototype._restoreStateValues = function () {
  49811. if (!_super.prototype._restoreStateValues.call(this)) {
  49812. return false;
  49813. }
  49814. this.alpha = this._storedAlpha;
  49815. this.beta = this._storedBeta;
  49816. this.radius = this._storedRadius;
  49817. this.setTarget(this._storedTarget.clone());
  49818. this.inertialAlphaOffset = 0;
  49819. this.inertialBetaOffset = 0;
  49820. this.inertialRadiusOffset = 0;
  49821. this.inertialPanningX = 0;
  49822. this.inertialPanningY = 0;
  49823. return true;
  49824. };
  49825. // Synchronized
  49826. /** @hidden */
  49827. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  49828. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  49829. return false;
  49830. return this._cache._target.equals(this._getTargetPosition())
  49831. && this._cache.alpha === this.alpha
  49832. && this._cache.beta === this.beta
  49833. && this._cache.radius === this.radius
  49834. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  49835. };
  49836. /**
  49837. * Attached controls to the current camera.
  49838. * @param element Defines the element the controls should be listened from
  49839. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49840. * @param useCtrlForPanning Defines whether ctrl is used for paning within the controls
  49841. * @param panningMouseButton Defines whether panning is allowed through mouse click button
  49842. */
  49843. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  49844. var _this = this;
  49845. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  49846. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  49847. this._useCtrlForPanning = useCtrlForPanning;
  49848. this._panningMouseButton = panningMouseButton;
  49849. this.inputs.attachElement(element, noPreventDefault);
  49850. this._reset = function () {
  49851. _this.inertialAlphaOffset = 0;
  49852. _this.inertialBetaOffset = 0;
  49853. _this.inertialRadiusOffset = 0;
  49854. _this.inertialPanningX = 0;
  49855. _this.inertialPanningY = 0;
  49856. };
  49857. };
  49858. /**
  49859. * Detach the current controls from the camera.
  49860. * The camera will stop reacting to inputs.
  49861. * @param element Defines the element to stop listening the inputs from
  49862. */
  49863. ArcRotateCamera.prototype.detachControl = function (element) {
  49864. this.inputs.detachElement(element);
  49865. if (this._reset) {
  49866. this._reset();
  49867. }
  49868. };
  49869. /** @hidden */
  49870. ArcRotateCamera.prototype._checkInputs = function () {
  49871. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  49872. if (this._collisionTriggered) {
  49873. return;
  49874. }
  49875. this.inputs.checkInputs();
  49876. // Inertia
  49877. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  49878. var inertialAlphaOffset = this.inertialAlphaOffset;
  49879. if (this.beta <= 0)
  49880. inertialAlphaOffset *= -1;
  49881. if (this.getScene().useRightHandedSystem)
  49882. inertialAlphaOffset *= -1;
  49883. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  49884. inertialAlphaOffset *= -1;
  49885. this.alpha += inertialAlphaOffset;
  49886. this.beta += this.inertialBetaOffset;
  49887. this.radius -= this.inertialRadiusOffset;
  49888. this.inertialAlphaOffset *= this.inertia;
  49889. this.inertialBetaOffset *= this.inertia;
  49890. this.inertialRadiusOffset *= this.inertia;
  49891. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  49892. this.inertialAlphaOffset = 0;
  49893. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  49894. this.inertialBetaOffset = 0;
  49895. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  49896. this.inertialRadiusOffset = 0;
  49897. }
  49898. // Panning inertia
  49899. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  49900. if (!this._localDirection) {
  49901. this._localDirection = BABYLON.Vector3.Zero();
  49902. this._transformedDirection = BABYLON.Vector3.Zero();
  49903. }
  49904. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  49905. this._localDirection.multiplyInPlace(this.panningAxis);
  49906. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  49907. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  49908. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  49909. if (!this.panningAxis.y) {
  49910. this._transformedDirection.y = 0;
  49911. }
  49912. if (!this._targetHost) {
  49913. if (this.panningDistanceLimit) {
  49914. this._transformedDirection.addInPlace(this._target);
  49915. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  49916. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  49917. this._target.copyFrom(this._transformedDirection);
  49918. }
  49919. }
  49920. else {
  49921. this._target.addInPlace(this._transformedDirection);
  49922. }
  49923. }
  49924. this.inertialPanningX *= this.panningInertia;
  49925. this.inertialPanningY *= this.panningInertia;
  49926. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  49927. this.inertialPanningX = 0;
  49928. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  49929. this.inertialPanningY = 0;
  49930. }
  49931. // Limits
  49932. this._checkLimits();
  49933. _super.prototype._checkInputs.call(this);
  49934. };
  49935. ArcRotateCamera.prototype._checkLimits = function () {
  49936. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  49937. if (this.allowUpsideDown && this.beta > Math.PI) {
  49938. this.beta = this.beta - (2 * Math.PI);
  49939. }
  49940. }
  49941. else {
  49942. if (this.beta < this.lowerBetaLimit) {
  49943. this.beta = this.lowerBetaLimit;
  49944. }
  49945. }
  49946. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  49947. if (this.allowUpsideDown && this.beta < -Math.PI) {
  49948. this.beta = this.beta + (2 * Math.PI);
  49949. }
  49950. }
  49951. else {
  49952. if (this.beta > this.upperBetaLimit) {
  49953. this.beta = this.upperBetaLimit;
  49954. }
  49955. }
  49956. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  49957. this.alpha = this.lowerAlphaLimit;
  49958. }
  49959. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  49960. this.alpha = this.upperAlphaLimit;
  49961. }
  49962. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  49963. this.radius = this.lowerRadiusLimit;
  49964. }
  49965. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  49966. this.radius = this.upperRadiusLimit;
  49967. }
  49968. };
  49969. /**
  49970. * Rebuilds angles (alpha, beta) and radius from the give position and target.
  49971. */
  49972. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  49973. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  49974. this.radius = this._computationVector.length();
  49975. if (this.radius === 0) {
  49976. this.radius = 0.0001; // Just to avoid division by zero
  49977. }
  49978. // Alpha
  49979. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  49980. if (this._computationVector.z < 0) {
  49981. this.alpha = 2 * Math.PI - this.alpha;
  49982. }
  49983. // Beta
  49984. this.beta = Math.acos(this._computationVector.y / this.radius);
  49985. this._checkLimits();
  49986. };
  49987. /**
  49988. * Use a position to define the current camera related information like aplha, beta and radius
  49989. * @param position Defines the position to set the camera at
  49990. */
  49991. ArcRotateCamera.prototype.setPosition = function (position) {
  49992. if (this.position.equals(position)) {
  49993. return;
  49994. }
  49995. this.position.copyFrom(position);
  49996. this.rebuildAnglesAndRadius();
  49997. };
  49998. /**
  49999. * Defines the target the camera should look at.
  50000. * This will automatically adapt alpha beta and radius to fit within the new target.
  50001. * @param target Defines the new target as a Vector or a mesh
  50002. * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center
  50003. * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
  50004. */
  50005. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  50006. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  50007. if (allowSamePosition === void 0) { allowSamePosition = false; }
  50008. if (target.getBoundingInfo) {
  50009. if (toBoundingCenter) {
  50010. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  50011. }
  50012. else {
  50013. this._targetBoundingCenter = null;
  50014. }
  50015. this._targetHost = target;
  50016. this._target = this._getTargetPosition();
  50017. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  50018. }
  50019. else {
  50020. var newTarget = target;
  50021. var currentTarget = this._getTargetPosition();
  50022. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  50023. return;
  50024. }
  50025. this._targetHost = null;
  50026. this._target = newTarget;
  50027. this._targetBoundingCenter = null;
  50028. this.onMeshTargetChangedObservable.notifyObservers(null);
  50029. }
  50030. this.rebuildAnglesAndRadius();
  50031. };
  50032. /** @hidden */
  50033. ArcRotateCamera.prototype._getViewMatrix = function () {
  50034. // Compute
  50035. var cosa = Math.cos(this.alpha);
  50036. var sina = Math.sin(this.alpha);
  50037. var cosb = Math.cos(this.beta);
  50038. var sinb = Math.sin(this.beta);
  50039. if (sinb === 0) {
  50040. sinb = 0.0001;
  50041. }
  50042. var target = this._getTargetPosition();
  50043. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  50044. target.addToRef(this._computationVector, this._newPosition);
  50045. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  50046. if (!this._collider) {
  50047. this._collider = new BABYLON.Collider();
  50048. }
  50049. this._collider._radius = this.collisionRadius;
  50050. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  50051. this._collisionTriggered = true;
  50052. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  50053. }
  50054. else {
  50055. this.position.copyFrom(this._newPosition);
  50056. var up = this.upVector;
  50057. if (this.allowUpsideDown && sinb < 0) {
  50058. up = up.clone();
  50059. up = up.negate();
  50060. }
  50061. this._computeViewMatrix(this.position, target, up);
  50062. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  50063. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  50064. }
  50065. this._currentTarget = target;
  50066. return this._viewMatrix;
  50067. };
  50068. /**
  50069. * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
  50070. * @param meshes Defines the mesh to zoom on
  50071. * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)
  50072. */
  50073. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  50074. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  50075. meshes = meshes || this.getScene().meshes;
  50076. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  50077. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  50078. this.radius = distance * this.zoomOnFactor;
  50079. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  50080. };
  50081. /**
  50082. * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
  50083. * The target will be changed but the radius
  50084. * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
  50085. * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)
  50086. */
  50087. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  50088. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  50089. var meshesOrMinMaxVector;
  50090. var distance;
  50091. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  50092. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  50093. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  50094. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  50095. }
  50096. else { //minMaxVector and distance
  50097. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  50098. meshesOrMinMaxVector = minMaxVectorAndDistance;
  50099. distance = minMaxVectorAndDistance.distance;
  50100. }
  50101. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  50102. if (!doNotUpdateMaxZ) {
  50103. this.maxZ = distance * 2;
  50104. }
  50105. };
  50106. /**
  50107. * @override
  50108. * Override Camera.createRigCamera
  50109. */
  50110. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  50111. var alphaShift = 0;
  50112. switch (this.cameraRigMode) {
  50113. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  50114. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  50115. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  50116. case BABYLON.Camera.RIG_MODE_VR:
  50117. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  50118. break;
  50119. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  50120. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  50121. break;
  50122. }
  50123. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  50124. rigCam._cameraRigParams = {};
  50125. return rigCam;
  50126. };
  50127. /**
  50128. * @hidden
  50129. * @override
  50130. * Override Camera._updateRigCameras
  50131. */
  50132. ArcRotateCamera.prototype._updateRigCameras = function () {
  50133. var camLeft = this._rigCameras[0];
  50134. var camRight = this._rigCameras[1];
  50135. camLeft.beta = camRight.beta = this.beta;
  50136. camLeft.radius = camRight.radius = this.radius;
  50137. switch (this.cameraRigMode) {
  50138. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  50139. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  50140. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  50141. case BABYLON.Camera.RIG_MODE_VR:
  50142. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  50143. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  50144. break;
  50145. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  50146. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  50147. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  50148. break;
  50149. }
  50150. _super.prototype._updateRigCameras.call(this);
  50151. };
  50152. /**
  50153. * Destroy the camera and release the current resources hold by it.
  50154. */
  50155. ArcRotateCamera.prototype.dispose = function () {
  50156. this.inputs.clear();
  50157. _super.prototype.dispose.call(this);
  50158. };
  50159. /**
  50160. * Gets the current object class name.
  50161. * @return the class name
  50162. */
  50163. ArcRotateCamera.prototype.getClassName = function () {
  50164. return "ArcRotateCamera";
  50165. };
  50166. __decorate([
  50167. BABYLON.serialize()
  50168. ], ArcRotateCamera.prototype, "alpha", void 0);
  50169. __decorate([
  50170. BABYLON.serialize()
  50171. ], ArcRotateCamera.prototype, "beta", void 0);
  50172. __decorate([
  50173. BABYLON.serialize()
  50174. ], ArcRotateCamera.prototype, "radius", void 0);
  50175. __decorate([
  50176. BABYLON.serializeAsVector3("target")
  50177. ], ArcRotateCamera.prototype, "_target", void 0);
  50178. __decorate([
  50179. BABYLON.serialize()
  50180. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  50181. __decorate([
  50182. BABYLON.serialize()
  50183. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  50184. __decorate([
  50185. BABYLON.serialize()
  50186. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  50187. __decorate([
  50188. BABYLON.serialize()
  50189. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  50190. __decorate([
  50191. BABYLON.serialize()
  50192. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  50193. __decorate([
  50194. BABYLON.serialize()
  50195. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  50196. __decorate([
  50197. BABYLON.serialize()
  50198. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  50199. __decorate([
  50200. BABYLON.serialize()
  50201. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  50202. __decorate([
  50203. BABYLON.serialize()
  50204. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  50205. __decorate([
  50206. BABYLON.serialize()
  50207. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  50208. __decorate([
  50209. BABYLON.serialize()
  50210. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  50211. __decorate([
  50212. BABYLON.serialize()
  50213. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  50214. __decorate([
  50215. BABYLON.serialize()
  50216. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  50217. __decorate([
  50218. BABYLON.serializeAsVector3()
  50219. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  50220. __decorate([
  50221. BABYLON.serialize()
  50222. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  50223. __decorate([
  50224. BABYLON.serialize()
  50225. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  50226. __decorate([
  50227. BABYLON.serialize()
  50228. ], ArcRotateCamera.prototype, "targetScreenOffset", void 0);
  50229. __decorate([
  50230. BABYLON.serialize()
  50231. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  50232. __decorate([
  50233. BABYLON.serialize()
  50234. ], ArcRotateCamera.prototype, "useInputToRestoreState", void 0);
  50235. return ArcRotateCamera;
  50236. }(BABYLON.TargetCamera));
  50237. BABYLON.ArcRotateCamera = ArcRotateCamera;
  50238. })(BABYLON || (BABYLON = {}));
  50239. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  50240. var BABYLON;
  50241. (function (BABYLON) {
  50242. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  50243. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  50244. });
  50245. /**
  50246. * The HemisphericLight simulates the ambient environment light,
  50247. * so the passed direction is the light reflection direction, not the incoming direction.
  50248. */
  50249. var HemisphericLight = /** @class */ (function (_super) {
  50250. __extends(HemisphericLight, _super);
  50251. /**
  50252. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  50253. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  50254. * The HemisphericLight can't cast shadows.
  50255. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50256. * @param name The friendly name of the light
  50257. * @param direction The direction of the light reflection
  50258. * @param scene The scene the light belongs to
  50259. */
  50260. function HemisphericLight(name, direction, scene) {
  50261. var _this = _super.call(this, name, scene) || this;
  50262. /**
  50263. * The groundColor is the light in the opposite direction to the one specified during creation.
  50264. * 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.
  50265. */
  50266. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  50267. _this.direction = direction || BABYLON.Vector3.Up();
  50268. return _this;
  50269. }
  50270. HemisphericLight.prototype._buildUniformLayout = function () {
  50271. this._uniformBuffer.addUniform("vLightData", 4);
  50272. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50273. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50274. this._uniformBuffer.addUniform("vLightGround", 3);
  50275. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50276. this._uniformBuffer.addUniform("depthValues", 2);
  50277. this._uniformBuffer.create();
  50278. };
  50279. /**
  50280. * Returns the string "HemisphericLight".
  50281. * @return The class name
  50282. */
  50283. HemisphericLight.prototype.getClassName = function () {
  50284. return "HemisphericLight";
  50285. };
  50286. /**
  50287. * Sets the HemisphericLight direction towards the passed target (Vector3).
  50288. * Returns the updated direction.
  50289. * @param target The target the direction should point to
  50290. * @return The computed direction
  50291. */
  50292. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  50293. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  50294. return this.direction;
  50295. };
  50296. /**
  50297. * Returns the shadow generator associated to the light.
  50298. * @returns Always null for hemispheric lights because it does not support shadows.
  50299. */
  50300. HemisphericLight.prototype.getShadowGenerator = function () {
  50301. return null;
  50302. };
  50303. /**
  50304. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  50305. * @param effect The effect to update
  50306. * @param lightIndex The index of the light in the effect to update
  50307. * @returns The hemispheric light
  50308. */
  50309. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  50310. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50311. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  50312. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  50313. return this;
  50314. };
  50315. /**
  50316. * Computes the world matrix of the node
  50317. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  50318. * @param useWasUpdatedFlag defines a reserved property
  50319. * @returns the world matrix
  50320. */
  50321. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  50322. if (!this._worldMatrix) {
  50323. this._worldMatrix = BABYLON.Matrix.Identity();
  50324. }
  50325. return this._worldMatrix;
  50326. };
  50327. /**
  50328. * Returns the integer 3.
  50329. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50330. */
  50331. HemisphericLight.prototype.getTypeID = function () {
  50332. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  50333. };
  50334. /**
  50335. * Prepares the list of defines specific to the light type.
  50336. * @param defines the list of defines
  50337. * @param lightIndex defines the index of the light for the effect
  50338. */
  50339. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50340. defines["HEMILIGHT" + lightIndex] = true;
  50341. };
  50342. __decorate([
  50343. BABYLON.serializeAsColor3()
  50344. ], HemisphericLight.prototype, "groundColor", void 0);
  50345. __decorate([
  50346. BABYLON.serializeAsVector3()
  50347. ], HemisphericLight.prototype, "direction", void 0);
  50348. return HemisphericLight;
  50349. }(BABYLON.Light));
  50350. BABYLON.HemisphericLight = HemisphericLight;
  50351. })(BABYLON || (BABYLON = {}));
  50352. //# sourceMappingURL=babylon.hemisphericLight.js.map
  50353. var BABYLON;
  50354. (function (BABYLON) {
  50355. /**
  50356. * Base implementation IShadowLight
  50357. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  50358. */
  50359. var ShadowLight = /** @class */ (function (_super) {
  50360. __extends(ShadowLight, _super);
  50361. function ShadowLight() {
  50362. var _this = _super !== null && _super.apply(this, arguments) || this;
  50363. _this._needProjectionMatrixCompute = true;
  50364. return _this;
  50365. }
  50366. ShadowLight.prototype._setPosition = function (value) {
  50367. this._position = value;
  50368. };
  50369. Object.defineProperty(ShadowLight.prototype, "position", {
  50370. /**
  50371. * Sets the position the shadow will be casted from. Also use as the light position for both
  50372. * point and spot lights.
  50373. */
  50374. get: function () {
  50375. return this._position;
  50376. },
  50377. /**
  50378. * Sets the position the shadow will be casted from. Also use as the light position for both
  50379. * point and spot lights.
  50380. */
  50381. set: function (value) {
  50382. this._setPosition(value);
  50383. },
  50384. enumerable: true,
  50385. configurable: true
  50386. });
  50387. ShadowLight.prototype._setDirection = function (value) {
  50388. this._direction = value;
  50389. };
  50390. Object.defineProperty(ShadowLight.prototype, "direction", {
  50391. /**
  50392. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  50393. * Also use as the light direction on spot and directional lights.
  50394. */
  50395. get: function () {
  50396. return this._direction;
  50397. },
  50398. /**
  50399. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  50400. * Also use as the light direction on spot and directional lights.
  50401. */
  50402. set: function (value) {
  50403. this._setDirection(value);
  50404. },
  50405. enumerable: true,
  50406. configurable: true
  50407. });
  50408. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  50409. /**
  50410. * Gets the shadow projection clipping minimum z value.
  50411. */
  50412. get: function () {
  50413. return this._shadowMinZ;
  50414. },
  50415. /**
  50416. * Sets the shadow projection clipping minimum z value.
  50417. */
  50418. set: function (value) {
  50419. this._shadowMinZ = value;
  50420. this.forceProjectionMatrixCompute();
  50421. },
  50422. enumerable: true,
  50423. configurable: true
  50424. });
  50425. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  50426. /**
  50427. * Sets the shadow projection clipping maximum z value.
  50428. */
  50429. get: function () {
  50430. return this._shadowMaxZ;
  50431. },
  50432. /**
  50433. * Gets the shadow projection clipping maximum z value.
  50434. */
  50435. set: function (value) {
  50436. this._shadowMaxZ = value;
  50437. this.forceProjectionMatrixCompute();
  50438. },
  50439. enumerable: true,
  50440. configurable: true
  50441. });
  50442. /**
  50443. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  50444. * @returns true if the information has been computed, false if it does not need to (no parenting)
  50445. */
  50446. ShadowLight.prototype.computeTransformedInformation = function () {
  50447. if (this.parent && this.parent.getWorldMatrix) {
  50448. if (!this.transformedPosition) {
  50449. this.transformedPosition = BABYLON.Vector3.Zero();
  50450. }
  50451. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  50452. // In case the direction is present.
  50453. if (this.direction) {
  50454. if (!this.transformedDirection) {
  50455. this.transformedDirection = BABYLON.Vector3.Zero();
  50456. }
  50457. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  50458. }
  50459. return true;
  50460. }
  50461. return false;
  50462. };
  50463. /**
  50464. * Return the depth scale used for the shadow map.
  50465. * @returns the depth scale.
  50466. */
  50467. ShadowLight.prototype.getDepthScale = function () {
  50468. return 50.0;
  50469. };
  50470. /**
  50471. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  50472. * @param faceIndex The index of the face we are computed the direction to generate shadow
  50473. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  50474. */
  50475. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  50476. return this.transformedDirection ? this.transformedDirection : this.direction;
  50477. };
  50478. /**
  50479. * Returns the ShadowLight absolute position in the World.
  50480. * @returns the position vector in world space
  50481. */
  50482. ShadowLight.prototype.getAbsolutePosition = function () {
  50483. return this.transformedPosition ? this.transformedPosition : this.position;
  50484. };
  50485. /**
  50486. * Sets the ShadowLight direction toward the passed target.
  50487. * @param target The point tot target in local space
  50488. * @returns the updated ShadowLight direction
  50489. */
  50490. ShadowLight.prototype.setDirectionToTarget = function (target) {
  50491. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  50492. return this.direction;
  50493. };
  50494. /**
  50495. * Returns the light rotation in euler definition.
  50496. * @returns the x y z rotation in local space.
  50497. */
  50498. ShadowLight.prototype.getRotation = function () {
  50499. this.direction.normalize();
  50500. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  50501. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  50502. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  50503. };
  50504. /**
  50505. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  50506. * @returns true if a cube texture needs to be use
  50507. */
  50508. ShadowLight.prototype.needCube = function () {
  50509. return false;
  50510. };
  50511. /**
  50512. * Detects if the projection matrix requires to be recomputed this frame.
  50513. * @returns true if it requires to be recomputed otherwise, false.
  50514. */
  50515. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  50516. return this._needProjectionMatrixCompute;
  50517. };
  50518. /**
  50519. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  50520. */
  50521. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  50522. this._needProjectionMatrixCompute = true;
  50523. };
  50524. /** @hidden */
  50525. ShadowLight.prototype._initCache = function () {
  50526. _super.prototype._initCache.call(this);
  50527. this._cache.position = BABYLON.Vector3.Zero();
  50528. };
  50529. /** @hidden */
  50530. ShadowLight.prototype._isSynchronized = function () {
  50531. if (!this._cache.position.equals(this.position))
  50532. return false;
  50533. return true;
  50534. };
  50535. /**
  50536. * Computes the world matrix of the node
  50537. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  50538. * @returns the world matrix
  50539. */
  50540. ShadowLight.prototype.computeWorldMatrix = function (force) {
  50541. if (!force && this.isSynchronized()) {
  50542. this._currentRenderId = this.getScene().getRenderId();
  50543. return this._worldMatrix;
  50544. }
  50545. this._updateCache();
  50546. this._cache.position.copyFrom(this.position);
  50547. if (!this._worldMatrix) {
  50548. this._worldMatrix = BABYLON.Matrix.Identity();
  50549. }
  50550. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  50551. if (this.parent && this.parent.getWorldMatrix) {
  50552. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  50553. this._markSyncedWithParent();
  50554. }
  50555. // Cache the determinant
  50556. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  50557. return this._worldMatrix;
  50558. };
  50559. /**
  50560. * Gets the minZ used for shadow according to both the scene and the light.
  50561. * @param activeCamera The camera we are returning the min for
  50562. * @returns the depth min z
  50563. */
  50564. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  50565. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  50566. };
  50567. /**
  50568. * Gets the maxZ used for shadow according to both the scene and the light.
  50569. * @param activeCamera The camera we are returning the max for
  50570. * @returns the depth max z
  50571. */
  50572. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  50573. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  50574. };
  50575. /**
  50576. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  50577. * @param matrix The materix to updated with the projection information
  50578. * @param viewMatrix The transform matrix of the light
  50579. * @param renderList The list of mesh to render in the map
  50580. * @returns The current light
  50581. */
  50582. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50583. if (this.customProjectionMatrixBuilder) {
  50584. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  50585. }
  50586. else {
  50587. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  50588. }
  50589. return this;
  50590. };
  50591. __decorate([
  50592. BABYLON.serializeAsVector3()
  50593. ], ShadowLight.prototype, "position", null);
  50594. __decorate([
  50595. BABYLON.serializeAsVector3()
  50596. ], ShadowLight.prototype, "direction", null);
  50597. __decorate([
  50598. BABYLON.serialize()
  50599. ], ShadowLight.prototype, "shadowMinZ", null);
  50600. __decorate([
  50601. BABYLON.serialize()
  50602. ], ShadowLight.prototype, "shadowMaxZ", null);
  50603. return ShadowLight;
  50604. }(BABYLON.Light));
  50605. BABYLON.ShadowLight = ShadowLight;
  50606. })(BABYLON || (BABYLON = {}));
  50607. //# sourceMappingURL=babylon.shadowLight.js.map
  50608. var BABYLON;
  50609. (function (BABYLON) {
  50610. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  50611. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  50612. });
  50613. /**
  50614. * A point light is a light defined by an unique point in world space.
  50615. * The light is emitted in every direction from this point.
  50616. * A good example of a point light is a standard light bulb.
  50617. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50618. */
  50619. var PointLight = /** @class */ (function (_super) {
  50620. __extends(PointLight, _super);
  50621. /**
  50622. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  50623. * A PointLight emits the light in every direction.
  50624. * It can cast shadows.
  50625. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  50626. * ```javascript
  50627. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  50628. * ```
  50629. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50630. * @param name The light friendly name
  50631. * @param position The position of the point light in the scene
  50632. * @param scene The scene the lights belongs to
  50633. */
  50634. function PointLight(name, position, scene) {
  50635. var _this = _super.call(this, name, scene) || this;
  50636. _this._shadowAngle = Math.PI / 2;
  50637. _this.position = position;
  50638. return _this;
  50639. }
  50640. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  50641. /**
  50642. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  50643. * This specifies what angle the shadow will use to be created.
  50644. *
  50645. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  50646. */
  50647. get: function () {
  50648. return this._shadowAngle;
  50649. },
  50650. /**
  50651. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  50652. * This specifies what angle the shadow will use to be created.
  50653. *
  50654. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  50655. */
  50656. set: function (value) {
  50657. this._shadowAngle = value;
  50658. this.forceProjectionMatrixCompute();
  50659. },
  50660. enumerable: true,
  50661. configurable: true
  50662. });
  50663. Object.defineProperty(PointLight.prototype, "direction", {
  50664. /**
  50665. * Gets the direction if it has been set.
  50666. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  50667. */
  50668. get: function () {
  50669. return this._direction;
  50670. },
  50671. /**
  50672. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  50673. */
  50674. set: function (value) {
  50675. var previousNeedCube = this.needCube();
  50676. this._direction = value;
  50677. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  50678. this._shadowGenerator.recreateShadowMap();
  50679. }
  50680. },
  50681. enumerable: true,
  50682. configurable: true
  50683. });
  50684. /**
  50685. * Returns the string "PointLight"
  50686. * @returns the class name
  50687. */
  50688. PointLight.prototype.getClassName = function () {
  50689. return "PointLight";
  50690. };
  50691. /**
  50692. * Returns the integer 0.
  50693. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50694. */
  50695. PointLight.prototype.getTypeID = function () {
  50696. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  50697. };
  50698. /**
  50699. * Specifies wether or not the shadowmap should be a cube texture.
  50700. * @returns true if the shadowmap needs to be a cube texture.
  50701. */
  50702. PointLight.prototype.needCube = function () {
  50703. return !this.direction;
  50704. };
  50705. /**
  50706. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  50707. * @param faceIndex The index of the face we are computed the direction to generate shadow
  50708. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  50709. */
  50710. PointLight.prototype.getShadowDirection = function (faceIndex) {
  50711. if (this.direction) {
  50712. return _super.prototype.getShadowDirection.call(this, faceIndex);
  50713. }
  50714. else {
  50715. switch (faceIndex) {
  50716. case 0:
  50717. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  50718. case 1:
  50719. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  50720. case 2:
  50721. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  50722. case 3:
  50723. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  50724. case 4:
  50725. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  50726. case 5:
  50727. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  50728. }
  50729. }
  50730. return BABYLON.Vector3.Zero();
  50731. };
  50732. /**
  50733. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  50734. * - fov = PI / 2
  50735. * - aspect ratio : 1.0
  50736. * - z-near and far equal to the active camera minZ and maxZ.
  50737. * Returns the PointLight.
  50738. */
  50739. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50740. var activeCamera = this.getScene().activeCamera;
  50741. if (!activeCamera) {
  50742. return;
  50743. }
  50744. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50745. };
  50746. PointLight.prototype._buildUniformLayout = function () {
  50747. this._uniformBuffer.addUniform("vLightData", 4);
  50748. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50749. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50750. this._uniformBuffer.addUniform("vLightFalloff", 4);
  50751. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50752. this._uniformBuffer.addUniform("depthValues", 2);
  50753. this._uniformBuffer.create();
  50754. };
  50755. /**
  50756. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  50757. * @param effect The effect to update
  50758. * @param lightIndex The index of the light in the effect to update
  50759. * @returns The point light
  50760. */
  50761. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  50762. if (this.computeTransformedInformation()) {
  50763. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  50764. }
  50765. else {
  50766. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  50767. }
  50768. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  50769. return this;
  50770. };
  50771. /**
  50772. * Prepares the list of defines specific to the light type.
  50773. * @param defines the list of defines
  50774. * @param lightIndex defines the index of the light for the effect
  50775. */
  50776. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50777. defines["POINTLIGHT" + lightIndex] = true;
  50778. };
  50779. __decorate([
  50780. BABYLON.serialize()
  50781. ], PointLight.prototype, "shadowAngle", null);
  50782. return PointLight;
  50783. }(BABYLON.ShadowLight));
  50784. BABYLON.PointLight = PointLight;
  50785. })(BABYLON || (BABYLON = {}));
  50786. //# sourceMappingURL=babylon.pointLight.js.map
  50787. var BABYLON;
  50788. (function (BABYLON) {
  50789. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  50790. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  50791. });
  50792. /**
  50793. * A directional light is defined by a direction (what a surprise!).
  50794. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  50795. * 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.
  50796. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50797. */
  50798. var DirectionalLight = /** @class */ (function (_super) {
  50799. __extends(DirectionalLight, _super);
  50800. /**
  50801. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  50802. * The directional light is emitted from everywhere in the given direction.
  50803. * It can cast shadows.
  50804. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50805. * @param name The friendly name of the light
  50806. * @param direction The direction of the light
  50807. * @param scene The scene the light belongs to
  50808. */
  50809. function DirectionalLight(name, direction, scene) {
  50810. var _this = _super.call(this, name, scene) || this;
  50811. _this._shadowFrustumSize = 0;
  50812. _this._shadowOrthoScale = 0.1;
  50813. /**
  50814. * Automatically compute the projection matrix to best fit (including all the casters)
  50815. * on each frame.
  50816. */
  50817. _this.autoUpdateExtends = true;
  50818. // Cache
  50819. _this._orthoLeft = Number.MAX_VALUE;
  50820. _this._orthoRight = Number.MIN_VALUE;
  50821. _this._orthoTop = Number.MIN_VALUE;
  50822. _this._orthoBottom = Number.MAX_VALUE;
  50823. _this.position = direction.scale(-1.0);
  50824. _this.direction = direction;
  50825. return _this;
  50826. }
  50827. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  50828. /**
  50829. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  50830. */
  50831. get: function () {
  50832. return this._shadowFrustumSize;
  50833. },
  50834. /**
  50835. * Specifies a fix frustum size for the shadow generation.
  50836. */
  50837. set: function (value) {
  50838. this._shadowFrustumSize = value;
  50839. this.forceProjectionMatrixCompute();
  50840. },
  50841. enumerable: true,
  50842. configurable: true
  50843. });
  50844. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  50845. /**
  50846. * Gets the shadow projection scale against the optimal computed one.
  50847. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  50848. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  50849. */
  50850. get: function () {
  50851. return this._shadowOrthoScale;
  50852. },
  50853. /**
  50854. * Sets the shadow projection scale against the optimal computed one.
  50855. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  50856. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  50857. */
  50858. set: function (value) {
  50859. this._shadowOrthoScale = value;
  50860. this.forceProjectionMatrixCompute();
  50861. },
  50862. enumerable: true,
  50863. configurable: true
  50864. });
  50865. /**
  50866. * Returns the string "DirectionalLight".
  50867. * @return The class name
  50868. */
  50869. DirectionalLight.prototype.getClassName = function () {
  50870. return "DirectionalLight";
  50871. };
  50872. /**
  50873. * Returns the integer 1.
  50874. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50875. */
  50876. DirectionalLight.prototype.getTypeID = function () {
  50877. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  50878. };
  50879. /**
  50880. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  50881. * Returns the DirectionalLight Shadow projection matrix.
  50882. */
  50883. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50884. if (this.shadowFrustumSize > 0) {
  50885. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  50886. }
  50887. else {
  50888. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  50889. }
  50890. };
  50891. /**
  50892. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  50893. * Returns the DirectionalLight Shadow projection matrix.
  50894. */
  50895. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  50896. var activeCamera = this.getScene().activeCamera;
  50897. if (!activeCamera) {
  50898. return;
  50899. }
  50900. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  50901. };
  50902. /**
  50903. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  50904. * Returns the DirectionalLight Shadow projection matrix.
  50905. */
  50906. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50907. var activeCamera = this.getScene().activeCamera;
  50908. if (!activeCamera) {
  50909. return;
  50910. }
  50911. // Check extends
  50912. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  50913. var tempVector3 = BABYLON.Vector3.Zero();
  50914. this._orthoLeft = Number.MAX_VALUE;
  50915. this._orthoRight = Number.MIN_VALUE;
  50916. this._orthoTop = Number.MIN_VALUE;
  50917. this._orthoBottom = Number.MAX_VALUE;
  50918. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  50919. var mesh = renderList[meshIndex];
  50920. if (!mesh) {
  50921. continue;
  50922. }
  50923. var boundingInfo = mesh.getBoundingInfo();
  50924. var boundingBox = boundingInfo.boundingBox;
  50925. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  50926. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  50927. if (tempVector3.x < this._orthoLeft)
  50928. this._orthoLeft = tempVector3.x;
  50929. if (tempVector3.y < this._orthoBottom)
  50930. this._orthoBottom = tempVector3.y;
  50931. if (tempVector3.x > this._orthoRight)
  50932. this._orthoRight = tempVector3.x;
  50933. if (tempVector3.y > this._orthoTop)
  50934. this._orthoTop = tempVector3.y;
  50935. }
  50936. }
  50937. }
  50938. var xOffset = this._orthoRight - this._orthoLeft;
  50939. var yOffset = this._orthoTop - this._orthoBottom;
  50940. 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);
  50941. };
  50942. DirectionalLight.prototype._buildUniformLayout = function () {
  50943. this._uniformBuffer.addUniform("vLightData", 4);
  50944. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50945. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50946. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50947. this._uniformBuffer.addUniform("depthValues", 2);
  50948. this._uniformBuffer.create();
  50949. };
  50950. /**
  50951. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  50952. * @param effect The effect to update
  50953. * @param lightIndex The index of the light in the effect to update
  50954. * @returns The directional light
  50955. */
  50956. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  50957. if (this.computeTransformedInformation()) {
  50958. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  50959. return this;
  50960. }
  50961. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  50962. return this;
  50963. };
  50964. /**
  50965. * Gets the minZ used for shadow according to both the scene and the light.
  50966. *
  50967. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50968. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50969. * @param activeCamera The camera we are returning the min for
  50970. * @returns the depth min z
  50971. */
  50972. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  50973. return 1;
  50974. };
  50975. /**
  50976. * Gets the maxZ used for shadow according to both the scene and the light.
  50977. *
  50978. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50979. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50980. * @param activeCamera The camera we are returning the max for
  50981. * @returns the depth max z
  50982. */
  50983. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  50984. return 1;
  50985. };
  50986. /**
  50987. * Prepares the list of defines specific to the light type.
  50988. * @param defines the list of defines
  50989. * @param lightIndex defines the index of the light for the effect
  50990. */
  50991. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50992. defines["DIRLIGHT" + lightIndex] = true;
  50993. };
  50994. __decorate([
  50995. BABYLON.serialize()
  50996. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  50997. __decorate([
  50998. BABYLON.serialize()
  50999. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  51000. __decorate([
  51001. BABYLON.serialize()
  51002. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  51003. return DirectionalLight;
  51004. }(BABYLON.ShadowLight));
  51005. BABYLON.DirectionalLight = DirectionalLight;
  51006. })(BABYLON || (BABYLON = {}));
  51007. //# sourceMappingURL=babylon.directionalLight.js.map
  51008. var BABYLON;
  51009. (function (BABYLON) {
  51010. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  51011. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  51012. });
  51013. /**
  51014. * A spot light is defined by a position, a direction, an angle, and an exponent.
  51015. * These values define a cone of light starting from the position, emitting toward the direction.
  51016. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  51017. * and the exponent defines the speed of the decay of the light with distance (reach).
  51018. * Documentation: https://doc.babylonjs.com/babylon101/lights
  51019. */
  51020. var SpotLight = /** @class */ (function (_super) {
  51021. __extends(SpotLight, _super);
  51022. /**
  51023. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  51024. * It can cast shadows.
  51025. * Documentation : http://doc.babylonjs.com/tutorials/lights
  51026. * @param name The light friendly name
  51027. * @param position The position of the spot light in the scene
  51028. * @param direction The direction of the light in the scene
  51029. * @param angle The cone angle of the light in Radians
  51030. * @param exponent The light decay speed with the distance from the emission spot
  51031. * @param scene The scene the lights belongs to
  51032. */
  51033. function SpotLight(name, position, direction, angle, exponent, scene) {
  51034. var _this = _super.call(this, name, scene) || this;
  51035. _this._innerAngle = 0;
  51036. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  51037. _this._projectionTextureLightNear = 1e-6;
  51038. _this._projectionTextureLightFar = 1000.0;
  51039. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  51040. _this._projectionTextureViewLightDirty = true;
  51041. _this._projectionTextureProjectionLightDirty = true;
  51042. _this._projectionTextureDirty = true;
  51043. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  51044. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  51045. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  51046. _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);
  51047. _this.position = position;
  51048. _this.direction = direction;
  51049. _this.angle = angle;
  51050. _this.exponent = exponent;
  51051. return _this;
  51052. }
  51053. Object.defineProperty(SpotLight.prototype, "angle", {
  51054. /**
  51055. * Gets the cone angle of the spot light in Radians.
  51056. */
  51057. get: function () {
  51058. return this._angle;
  51059. },
  51060. /**
  51061. * Sets the cone angle of the spot light in Radians.
  51062. */
  51063. set: function (value) {
  51064. this._angle = value;
  51065. this._cosHalfAngle = Math.cos(value * 0.5);
  51066. this._projectionTextureProjectionLightDirty = true;
  51067. this.forceProjectionMatrixCompute();
  51068. this._computeAngleValues();
  51069. },
  51070. enumerable: true,
  51071. configurable: true
  51072. });
  51073. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  51074. /**
  51075. * Only used in gltf falloff mode, this defines the angle where
  51076. * the directional falloff will start before cutting at angle which could be seen
  51077. * as outer angle.
  51078. */
  51079. get: function () {
  51080. return this._innerAngle;
  51081. },
  51082. /**
  51083. * Only used in gltf falloff mode, this defines the angle where
  51084. * the directional falloff will start before cutting at angle which could be seen
  51085. * as outer angle.
  51086. */
  51087. set: function (value) {
  51088. this._innerAngle = value;
  51089. this._computeAngleValues();
  51090. },
  51091. enumerable: true,
  51092. configurable: true
  51093. });
  51094. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  51095. /**
  51096. * Allows scaling the angle of the light for shadow generation only.
  51097. */
  51098. get: function () {
  51099. return this._shadowAngleScale;
  51100. },
  51101. /**
  51102. * Allows scaling the angle of the light for shadow generation only.
  51103. */
  51104. set: function (value) {
  51105. this._shadowAngleScale = value;
  51106. this.forceProjectionMatrixCompute();
  51107. },
  51108. enumerable: true,
  51109. configurable: true
  51110. });
  51111. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  51112. /**
  51113. * Allows reading the projecton texture
  51114. */
  51115. get: function () {
  51116. return this._projectionTextureMatrix;
  51117. },
  51118. enumerable: true,
  51119. configurable: true
  51120. });
  51121. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  51122. /**
  51123. * Gets the near clip of the Spotlight for texture projection.
  51124. */
  51125. get: function () {
  51126. return this._projectionTextureLightNear;
  51127. },
  51128. /**
  51129. * Sets the near clip of the Spotlight for texture projection.
  51130. */
  51131. set: function (value) {
  51132. this._projectionTextureLightNear = value;
  51133. this._projectionTextureProjectionLightDirty = true;
  51134. },
  51135. enumerable: true,
  51136. configurable: true
  51137. });
  51138. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  51139. /**
  51140. * Gets the far clip of the Spotlight for texture projection.
  51141. */
  51142. get: function () {
  51143. return this._projectionTextureLightFar;
  51144. },
  51145. /**
  51146. * Sets the far clip of the Spotlight for texture projection.
  51147. */
  51148. set: function (value) {
  51149. this._projectionTextureLightFar = value;
  51150. this._projectionTextureProjectionLightDirty = true;
  51151. },
  51152. enumerable: true,
  51153. configurable: true
  51154. });
  51155. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  51156. /**
  51157. * Gets the Up vector of the Spotlight for texture projection.
  51158. */
  51159. get: function () {
  51160. return this._projectionTextureUpDirection;
  51161. },
  51162. /**
  51163. * Sets the Up vector of the Spotlight for texture projection.
  51164. */
  51165. set: function (value) {
  51166. this._projectionTextureUpDirection = value;
  51167. this._projectionTextureProjectionLightDirty = true;
  51168. },
  51169. enumerable: true,
  51170. configurable: true
  51171. });
  51172. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  51173. /**
  51174. * Gets the projection texture of the light.
  51175. */
  51176. get: function () {
  51177. return this._projectionTexture;
  51178. },
  51179. /**
  51180. * Sets the projection texture of the light.
  51181. */
  51182. set: function (value) {
  51183. this._projectionTexture = value;
  51184. this._projectionTextureDirty = true;
  51185. },
  51186. enumerable: true,
  51187. configurable: true
  51188. });
  51189. /**
  51190. * Returns the string "SpotLight".
  51191. * @returns the class name
  51192. */
  51193. SpotLight.prototype.getClassName = function () {
  51194. return "SpotLight";
  51195. };
  51196. /**
  51197. * Returns the integer 2.
  51198. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  51199. */
  51200. SpotLight.prototype.getTypeID = function () {
  51201. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  51202. };
  51203. /**
  51204. * Overrides the direction setter to recompute the projection texture view light Matrix.
  51205. */
  51206. SpotLight.prototype._setDirection = function (value) {
  51207. _super.prototype._setDirection.call(this, value);
  51208. this._projectionTextureViewLightDirty = true;
  51209. };
  51210. /**
  51211. * Overrides the position setter to recompute the projection texture view light Matrix.
  51212. */
  51213. SpotLight.prototype._setPosition = function (value) {
  51214. _super.prototype._setPosition.call(this, value);
  51215. this._projectionTextureViewLightDirty = true;
  51216. };
  51217. /**
  51218. * 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.
  51219. * Returns the SpotLight.
  51220. */
  51221. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51222. var activeCamera = this.getScene().activeCamera;
  51223. if (!activeCamera) {
  51224. return;
  51225. }
  51226. this._shadowAngleScale = this._shadowAngleScale || 1;
  51227. var angle = this._shadowAngleScale * this._angle;
  51228. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  51229. };
  51230. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  51231. this._projectionTextureViewLightDirty = false;
  51232. this._projectionTextureDirty = true;
  51233. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  51234. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  51235. };
  51236. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  51237. this._projectionTextureProjectionLightDirty = false;
  51238. this._projectionTextureDirty = true;
  51239. var light_far = this.projectionTextureLightFar;
  51240. var light_near = this.projectionTextureLightNear;
  51241. var P = light_far / (light_far - light_near);
  51242. var Q = -P * light_near;
  51243. var S = 1.0 / Math.tan(this._angle / 2.0);
  51244. var A = 1.0;
  51245. 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);
  51246. };
  51247. /**
  51248. * Main function for light texture projection matrix computing.
  51249. */
  51250. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  51251. this._projectionTextureDirty = false;
  51252. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  51253. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  51254. };
  51255. SpotLight.prototype._buildUniformLayout = function () {
  51256. this._uniformBuffer.addUniform("vLightData", 4);
  51257. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  51258. this._uniformBuffer.addUniform("vLightSpecular", 3);
  51259. this._uniformBuffer.addUniform("vLightDirection", 3);
  51260. this._uniformBuffer.addUniform("vLightFalloff", 4);
  51261. this._uniformBuffer.addUniform("shadowsInfo", 3);
  51262. this._uniformBuffer.addUniform("depthValues", 2);
  51263. this._uniformBuffer.create();
  51264. };
  51265. SpotLight.prototype._computeAngleValues = function () {
  51266. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  51267. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  51268. };
  51269. /**
  51270. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  51271. * @param effect The effect to update
  51272. * @param lightIndex The index of the light in the effect to update
  51273. * @returns The spot light
  51274. */
  51275. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  51276. var normalizeDirection;
  51277. if (this.computeTransformedInformation()) {
  51278. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  51279. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  51280. }
  51281. else {
  51282. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  51283. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  51284. }
  51285. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  51286. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  51287. if (this.projectionTexture && this.projectionTexture.isReady()) {
  51288. if (this._projectionTextureViewLightDirty) {
  51289. this._computeProjectionTextureViewLightMatrix();
  51290. }
  51291. if (this._projectionTextureProjectionLightDirty) {
  51292. this._computeProjectionTextureProjectionLightMatrix();
  51293. }
  51294. if (this._projectionTextureDirty) {
  51295. this._computeProjectionTextureMatrix();
  51296. }
  51297. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  51298. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  51299. }
  51300. return this;
  51301. };
  51302. /**
  51303. * Disposes the light and the associated resources.
  51304. */
  51305. SpotLight.prototype.dispose = function () {
  51306. _super.prototype.dispose.call(this);
  51307. if (this._projectionTexture) {
  51308. this._projectionTexture.dispose();
  51309. }
  51310. };
  51311. /**
  51312. * Prepares the list of defines specific to the light type.
  51313. * @param defines the list of defines
  51314. * @param lightIndex defines the index of the light for the effect
  51315. */
  51316. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  51317. defines["SPOTLIGHT" + lightIndex] = true;
  51318. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  51319. };
  51320. __decorate([
  51321. BABYLON.serialize()
  51322. ], SpotLight.prototype, "angle", null);
  51323. __decorate([
  51324. BABYLON.serialize()
  51325. ], SpotLight.prototype, "innerAngle", null);
  51326. __decorate([
  51327. BABYLON.serialize()
  51328. ], SpotLight.prototype, "shadowAngleScale", null);
  51329. __decorate([
  51330. BABYLON.serialize()
  51331. ], SpotLight.prototype, "exponent", void 0);
  51332. __decorate([
  51333. BABYLON.serialize()
  51334. ], SpotLight.prototype, "projectionTextureLightNear", null);
  51335. __decorate([
  51336. BABYLON.serialize()
  51337. ], SpotLight.prototype, "projectionTextureLightFar", null);
  51338. __decorate([
  51339. BABYLON.serialize()
  51340. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  51341. __decorate([
  51342. BABYLON.serializeAsTexture("projectedLightTexture")
  51343. ], SpotLight.prototype, "_projectionTexture", void 0);
  51344. return SpotLight;
  51345. }(BABYLON.ShadowLight));
  51346. BABYLON.SpotLight = SpotLight;
  51347. })(BABYLON || (BABYLON = {}));
  51348. //# sourceMappingURL=babylon.spotLight.js.map
  51349. var BABYLON;
  51350. (function (BABYLON) {
  51351. /**
  51352. * Class used to override all child animations of a given target
  51353. */
  51354. var AnimationPropertiesOverride = /** @class */ (function () {
  51355. function AnimationPropertiesOverride() {
  51356. /**
  51357. * Gets or sets a value indicating if animation blending must be used
  51358. */
  51359. this.enableBlending = false;
  51360. /**
  51361. * Gets or sets the blending speed to use when enableBlending is true
  51362. */
  51363. this.blendingSpeed = 0.01;
  51364. /**
  51365. * Gets or sets the default loop mode to use
  51366. */
  51367. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  51368. }
  51369. return AnimationPropertiesOverride;
  51370. }());
  51371. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  51372. })(BABYLON || (BABYLON = {}));
  51373. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  51374. var BABYLON;
  51375. (function (BABYLON) {
  51376. /**
  51377. * Represents the range of an animation
  51378. */
  51379. var AnimationRange = /** @class */ (function () {
  51380. /**
  51381. * Initializes the range of an animation
  51382. * @param name The name of the animation range
  51383. * @param from The starting frame of the animation
  51384. * @param to The ending frame of the animation
  51385. */
  51386. function AnimationRange(
  51387. /**The name of the animation range**/
  51388. name,
  51389. /**The starting frame of the animation */
  51390. from,
  51391. /**The ending frame of the animation*/
  51392. to) {
  51393. this.name = name;
  51394. this.from = from;
  51395. this.to = to;
  51396. }
  51397. /**
  51398. * Makes a copy of the animation range
  51399. * @returns A copy of the animation range
  51400. */
  51401. AnimationRange.prototype.clone = function () {
  51402. return new AnimationRange(this.name, this.from, this.to);
  51403. };
  51404. return AnimationRange;
  51405. }());
  51406. BABYLON.AnimationRange = AnimationRange;
  51407. /**
  51408. * Composed of a frame, and an action function
  51409. */
  51410. var AnimationEvent = /** @class */ (function () {
  51411. /**
  51412. * Initializes the animation event
  51413. * @param frame The frame for which the event is triggered
  51414. * @param action The event to perform when triggered
  51415. * @param onlyOnce Specifies if the event should be triggered only once
  51416. */
  51417. function AnimationEvent(
  51418. /** The frame for which the event is triggered **/
  51419. frame,
  51420. /** The event to perform when triggered **/
  51421. action,
  51422. /** Specifies if the event should be triggered only once**/
  51423. onlyOnce) {
  51424. this.frame = frame;
  51425. this.action = action;
  51426. this.onlyOnce = onlyOnce;
  51427. /**
  51428. * Specifies if the animation event is done
  51429. */
  51430. this.isDone = false;
  51431. }
  51432. /** @hidden */
  51433. AnimationEvent.prototype._clone = function () {
  51434. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  51435. };
  51436. return AnimationEvent;
  51437. }());
  51438. BABYLON.AnimationEvent = AnimationEvent;
  51439. /**
  51440. * A cursor which tracks a point on a path
  51441. */
  51442. var PathCursor = /** @class */ (function () {
  51443. /**
  51444. * Initializes the path cursor
  51445. * @param path The path to track
  51446. */
  51447. function PathCursor(path) {
  51448. this.path = path;
  51449. /**
  51450. * Stores path cursor callbacks for when an onchange event is triggered
  51451. */
  51452. this._onchange = new Array();
  51453. /**
  51454. * The value of the path cursor
  51455. */
  51456. this.value = 0;
  51457. /**
  51458. * The animation array of the path cursor
  51459. */
  51460. this.animations = new Array();
  51461. }
  51462. /**
  51463. * Gets the cursor point on the path
  51464. * @returns A point on the path cursor at the cursor location
  51465. */
  51466. PathCursor.prototype.getPoint = function () {
  51467. var point = this.path.getPointAtLengthPosition(this.value);
  51468. return new BABYLON.Vector3(point.x, 0, point.y);
  51469. };
  51470. /**
  51471. * Moves the cursor ahead by the step amount
  51472. * @param step The amount to move the cursor forward
  51473. * @returns This path cursor
  51474. */
  51475. PathCursor.prototype.moveAhead = function (step) {
  51476. if (step === void 0) { step = 0.002; }
  51477. this.move(step);
  51478. return this;
  51479. };
  51480. /**
  51481. * Moves the cursor behind by the step amount
  51482. * @param step The amount to move the cursor back
  51483. * @returns This path cursor
  51484. */
  51485. PathCursor.prototype.moveBack = function (step) {
  51486. if (step === void 0) { step = 0.002; }
  51487. this.move(-step);
  51488. return this;
  51489. };
  51490. /**
  51491. * Moves the cursor by the step amount
  51492. * If the step amount is greater than one, an exception is thrown
  51493. * @param step The amount to move the cursor
  51494. * @returns This path cursor
  51495. */
  51496. PathCursor.prototype.move = function (step) {
  51497. if (Math.abs(step) > 1) {
  51498. throw "step size should be less than 1.";
  51499. }
  51500. this.value += step;
  51501. this.ensureLimits();
  51502. this.raiseOnChange();
  51503. return this;
  51504. };
  51505. /**
  51506. * Ensures that the value is limited between zero and one
  51507. * @returns This path cursor
  51508. */
  51509. PathCursor.prototype.ensureLimits = function () {
  51510. while (this.value > 1) {
  51511. this.value -= 1;
  51512. }
  51513. while (this.value < 0) {
  51514. this.value += 1;
  51515. }
  51516. return this;
  51517. };
  51518. /**
  51519. * Runs onchange callbacks on change (used by the animation engine)
  51520. * @returns This path cursor
  51521. */
  51522. PathCursor.prototype.raiseOnChange = function () {
  51523. var _this = this;
  51524. this._onchange.forEach(function (f) { return f(_this); });
  51525. return this;
  51526. };
  51527. /**
  51528. * Executes a function on change
  51529. * @param f A path cursor onchange callback
  51530. * @returns This path cursor
  51531. */
  51532. PathCursor.prototype.onchange = function (f) {
  51533. this._onchange.push(f);
  51534. return this;
  51535. };
  51536. return PathCursor;
  51537. }());
  51538. BABYLON.PathCursor = PathCursor;
  51539. /**
  51540. * Enum for the animation key frame interpolation type
  51541. */
  51542. var AnimationKeyInterpolation;
  51543. (function (AnimationKeyInterpolation) {
  51544. /**
  51545. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  51546. */
  51547. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  51548. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  51549. /**
  51550. * Class used to store any kind of animation
  51551. */
  51552. var Animation = /** @class */ (function () {
  51553. /**
  51554. * Initializes the animation
  51555. * @param name Name of the animation
  51556. * @param targetProperty Property to animate
  51557. * @param framePerSecond The frames per second of the animation
  51558. * @param dataType The data type of the animation
  51559. * @param loopMode The loop mode of the animation
  51560. * @param enableBlendings Specifies if blending should be enabled
  51561. */
  51562. function Animation(
  51563. /**Name of the animation */
  51564. name,
  51565. /**Property to animate */
  51566. targetProperty,
  51567. /**The frames per second of the animation */
  51568. framePerSecond,
  51569. /**The data type of the animation */
  51570. dataType,
  51571. /**The loop mode of the animation */
  51572. loopMode,
  51573. /**Specifies if blending should be enabled */
  51574. enableBlending) {
  51575. this.name = name;
  51576. this.targetProperty = targetProperty;
  51577. this.framePerSecond = framePerSecond;
  51578. this.dataType = dataType;
  51579. this.loopMode = loopMode;
  51580. this.enableBlending = enableBlending;
  51581. /**
  51582. * @hidden Internal use only
  51583. */
  51584. this._runtimeAnimations = new Array();
  51585. /**
  51586. * The set of event that will be linked to this animation
  51587. */
  51588. this._events = new Array();
  51589. /**
  51590. * Stores the blending speed of the animation
  51591. */
  51592. this.blendingSpeed = 0.01;
  51593. /**
  51594. * Stores the animation ranges for the animation
  51595. */
  51596. this._ranges = {};
  51597. this.targetPropertyPath = targetProperty.split(".");
  51598. this.dataType = dataType;
  51599. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  51600. }
  51601. /**
  51602. * @hidden Internal use
  51603. */
  51604. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  51605. var dataType = undefined;
  51606. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  51607. dataType = Animation.ANIMATIONTYPE_FLOAT;
  51608. }
  51609. else if (from instanceof BABYLON.Quaternion) {
  51610. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  51611. }
  51612. else if (from instanceof BABYLON.Vector3) {
  51613. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  51614. }
  51615. else if (from instanceof BABYLON.Vector2) {
  51616. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  51617. }
  51618. else if (from instanceof BABYLON.Color3) {
  51619. dataType = Animation.ANIMATIONTYPE_COLOR3;
  51620. }
  51621. else if (from instanceof BABYLON.Size) {
  51622. dataType = Animation.ANIMATIONTYPE_SIZE;
  51623. }
  51624. if (dataType == undefined) {
  51625. return null;
  51626. }
  51627. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  51628. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  51629. animation.setKeys(keys);
  51630. if (easingFunction !== undefined) {
  51631. animation.setEasingFunction(easingFunction);
  51632. }
  51633. return animation;
  51634. };
  51635. /**
  51636. * Sets up an animation
  51637. * @param property The property to animate
  51638. * @param animationType The animation type to apply
  51639. * @param framePerSecond The frames per second of the animation
  51640. * @param easingFunction The easing function used in the animation
  51641. * @returns The created animation
  51642. */
  51643. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  51644. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  51645. animation.setEasingFunction(easingFunction);
  51646. return animation;
  51647. };
  51648. /**
  51649. * Create and start an animation on a node
  51650. * @param name defines the name of the global animation that will be run on all nodes
  51651. * @param node defines the root node where the animation will take place
  51652. * @param targetProperty defines property to animate
  51653. * @param framePerSecond defines the number of frame per second yo use
  51654. * @param totalFrame defines the number of frames in total
  51655. * @param from defines the initial value
  51656. * @param to defines the final value
  51657. * @param loopMode defines which loop mode you want to use (off by default)
  51658. * @param easingFunction defines the easing function to use (linear by default)
  51659. * @param onAnimationEnd defines the callback to call when animation end
  51660. * @returns the animatable created for this animation
  51661. */
  51662. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  51663. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  51664. if (!animation) {
  51665. return null;
  51666. }
  51667. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  51668. };
  51669. /**
  51670. * Create and start an animation on a node and its descendants
  51671. * @param name defines the name of the global animation that will be run on all nodes
  51672. * @param node defines the root node where the animation will take place
  51673. * @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
  51674. * @param targetProperty defines property to animate
  51675. * @param framePerSecond defines the number of frame per second to use
  51676. * @param totalFrame defines the number of frames in total
  51677. * @param from defines the initial value
  51678. * @param to defines the final value
  51679. * @param loopMode defines which loop mode you want to use (off by default)
  51680. * @param easingFunction defines the easing function to use (linear by default)
  51681. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  51682. * @returns the list of animatables created for all nodes
  51683. * @example https://www.babylonjs-playground.com/#MH0VLI
  51684. */
  51685. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  51686. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  51687. if (!animation) {
  51688. return null;
  51689. }
  51690. var scene = node.getScene();
  51691. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  51692. };
  51693. /**
  51694. * Creates a new animation, merges it with the existing animations and starts it
  51695. * @param name Name of the animation
  51696. * @param node Node which contains the scene that begins the animations
  51697. * @param targetProperty Specifies which property to animate
  51698. * @param framePerSecond The frames per second of the animation
  51699. * @param totalFrame The total number of frames
  51700. * @param from The frame at the beginning of the animation
  51701. * @param to The frame at the end of the animation
  51702. * @param loopMode Specifies the loop mode of the animation
  51703. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  51704. * @param onAnimationEnd Callback to run once the animation is complete
  51705. * @returns Nullable animation
  51706. */
  51707. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  51708. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  51709. if (!animation) {
  51710. return null;
  51711. }
  51712. node.animations.push(animation);
  51713. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  51714. };
  51715. /**
  51716. * Transition property of an host to the target Value
  51717. * @param property The property to transition
  51718. * @param targetValue The target Value of the property
  51719. * @param host The object where the property to animate belongs
  51720. * @param scene Scene used to run the animation
  51721. * @param frameRate Framerate (in frame/s) to use
  51722. * @param transition The transition type we want to use
  51723. * @param duration The duration of the animation, in milliseconds
  51724. * @param onAnimationEnd Callback trigger at the end of the animation
  51725. * @returns Nullable animation
  51726. */
  51727. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  51728. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  51729. if (duration <= 0) {
  51730. host[property] = targetValue;
  51731. if (onAnimationEnd) {
  51732. onAnimationEnd();
  51733. }
  51734. return null;
  51735. }
  51736. var endFrame = frameRate * (duration / 1000);
  51737. transition.setKeys([{
  51738. frame: 0,
  51739. value: host[property].clone ? host[property].clone() : host[property]
  51740. },
  51741. {
  51742. frame: endFrame,
  51743. value: targetValue
  51744. }]);
  51745. if (!host.animations) {
  51746. host.animations = [];
  51747. }
  51748. host.animations.push(transition);
  51749. var animation = scene.beginAnimation(host, 0, endFrame, false);
  51750. animation.onAnimationEnd = onAnimationEnd;
  51751. return animation;
  51752. };
  51753. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  51754. /**
  51755. * Return the array of runtime animations currently using this animation
  51756. */
  51757. get: function () {
  51758. return this._runtimeAnimations;
  51759. },
  51760. enumerable: true,
  51761. configurable: true
  51762. });
  51763. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  51764. /**
  51765. * Specifies if any of the runtime animations are currently running
  51766. */
  51767. get: function () {
  51768. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  51769. var runtimeAnimation = _a[_i];
  51770. if (!runtimeAnimation.isStopped) {
  51771. return true;
  51772. }
  51773. }
  51774. return false;
  51775. },
  51776. enumerable: true,
  51777. configurable: true
  51778. });
  51779. // Methods
  51780. /**
  51781. * Converts the animation to a string
  51782. * @param fullDetails support for multiple levels of logging within scene loading
  51783. * @returns String form of the animation
  51784. */
  51785. Animation.prototype.toString = function (fullDetails) {
  51786. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  51787. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  51788. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  51789. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  51790. if (fullDetails) {
  51791. ret += ", Ranges: {";
  51792. var first = true;
  51793. for (var name in this._ranges) {
  51794. if (first) {
  51795. ret += ", ";
  51796. first = false;
  51797. }
  51798. ret += name;
  51799. }
  51800. ret += "}";
  51801. }
  51802. return ret;
  51803. };
  51804. /**
  51805. * Add an event to this animation
  51806. * @param event Event to add
  51807. */
  51808. Animation.prototype.addEvent = function (event) {
  51809. this._events.push(event);
  51810. };
  51811. /**
  51812. * Remove all events found at the given frame
  51813. * @param frame The frame to remove events from
  51814. */
  51815. Animation.prototype.removeEvents = function (frame) {
  51816. for (var index = 0; index < this._events.length; index++) {
  51817. if (this._events[index].frame === frame) {
  51818. this._events.splice(index, 1);
  51819. index--;
  51820. }
  51821. }
  51822. };
  51823. /**
  51824. * Retrieves all the events from the animation
  51825. * @returns Events from the animation
  51826. */
  51827. Animation.prototype.getEvents = function () {
  51828. return this._events;
  51829. };
  51830. /**
  51831. * Creates an animation range
  51832. * @param name Name of the animation range
  51833. * @param from Starting frame of the animation range
  51834. * @param to Ending frame of the animation
  51835. */
  51836. Animation.prototype.createRange = function (name, from, to) {
  51837. // check name not already in use; could happen for bones after serialized
  51838. if (!this._ranges[name]) {
  51839. this._ranges[name] = new AnimationRange(name, from, to);
  51840. }
  51841. };
  51842. /**
  51843. * Deletes an animation range by name
  51844. * @param name Name of the animation range to delete
  51845. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  51846. */
  51847. Animation.prototype.deleteRange = function (name, deleteFrames) {
  51848. if (deleteFrames === void 0) { deleteFrames = true; }
  51849. var range = this._ranges[name];
  51850. if (!range) {
  51851. return;
  51852. }
  51853. if (deleteFrames) {
  51854. var from = range.from;
  51855. var to = range.to;
  51856. // this loop MUST go high to low for multiple splices to work
  51857. for (var key = this._keys.length - 1; key >= 0; key--) {
  51858. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  51859. this._keys.splice(key, 1);
  51860. }
  51861. }
  51862. }
  51863. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  51864. };
  51865. /**
  51866. * Gets the animation range by name, or null if not defined
  51867. * @param name Name of the animation range
  51868. * @returns Nullable animation range
  51869. */
  51870. Animation.prototype.getRange = function (name) {
  51871. return this._ranges[name];
  51872. };
  51873. /**
  51874. * Gets the key frames from the animation
  51875. * @returns The key frames of the animation
  51876. */
  51877. Animation.prototype.getKeys = function () {
  51878. return this._keys;
  51879. };
  51880. /**
  51881. * Gets the highest frame rate of the animation
  51882. * @returns Highest frame rate of the animation
  51883. */
  51884. Animation.prototype.getHighestFrame = function () {
  51885. var ret = 0;
  51886. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  51887. if (ret < this._keys[key].frame) {
  51888. ret = this._keys[key].frame;
  51889. }
  51890. }
  51891. return ret;
  51892. };
  51893. /**
  51894. * Gets the easing function of the animation
  51895. * @returns Easing function of the animation
  51896. */
  51897. Animation.prototype.getEasingFunction = function () {
  51898. return this._easingFunction;
  51899. };
  51900. /**
  51901. * Sets the easing function of the animation
  51902. * @param easingFunction A custom mathematical formula for animation
  51903. */
  51904. Animation.prototype.setEasingFunction = function (easingFunction) {
  51905. this._easingFunction = easingFunction;
  51906. };
  51907. /**
  51908. * Interpolates a scalar linearly
  51909. * @param startValue Start value of the animation curve
  51910. * @param endValue End value of the animation curve
  51911. * @param gradient Scalar amount to interpolate
  51912. * @returns Interpolated scalar value
  51913. */
  51914. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  51915. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  51916. };
  51917. /**
  51918. * Interpolates a scalar cubically
  51919. * @param startValue Start value of the animation curve
  51920. * @param outTangent End tangent of the animation
  51921. * @param endValue End value of the animation curve
  51922. * @param inTangent Start tangent of the animation curve
  51923. * @param gradient Scalar amount to interpolate
  51924. * @returns Interpolated scalar value
  51925. */
  51926. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51927. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51928. };
  51929. /**
  51930. * Interpolates a quaternion using a spherical linear interpolation
  51931. * @param startValue Start value of the animation curve
  51932. * @param endValue End value of the animation curve
  51933. * @param gradient Scalar amount to interpolate
  51934. * @returns Interpolated quaternion value
  51935. */
  51936. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  51937. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  51938. };
  51939. /**
  51940. * Interpolates a quaternion cubically
  51941. * @param startValue Start value of the animation curve
  51942. * @param outTangent End tangent of the animation curve
  51943. * @param endValue End value of the animation curve
  51944. * @param inTangent Start tangent of the animation curve
  51945. * @param gradient Scalar amount to interpolate
  51946. * @returns Interpolated quaternion value
  51947. */
  51948. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51949. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  51950. };
  51951. /**
  51952. * Interpolates a Vector3 linearl
  51953. * @param startValue Start value of the animation curve
  51954. * @param endValue End value of the animation curve
  51955. * @param gradient Scalar amount to interpolate
  51956. * @returns Interpolated scalar value
  51957. */
  51958. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  51959. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  51960. };
  51961. /**
  51962. * Interpolates a Vector3 cubically
  51963. * @param startValue Start value of the animation curve
  51964. * @param outTangent End tangent of the animation
  51965. * @param endValue End value of the animation curve
  51966. * @param inTangent Start tangent of the animation curve
  51967. * @param gradient Scalar amount to interpolate
  51968. * @returns InterpolatedVector3 value
  51969. */
  51970. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51971. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51972. };
  51973. /**
  51974. * Interpolates a Vector2 linearly
  51975. * @param startValue Start value of the animation curve
  51976. * @param endValue End value of the animation curve
  51977. * @param gradient Scalar amount to interpolate
  51978. * @returns Interpolated Vector2 value
  51979. */
  51980. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  51981. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  51982. };
  51983. /**
  51984. * Interpolates a Vector2 cubically
  51985. * @param startValue Start value of the animation curve
  51986. * @param outTangent End tangent of the animation
  51987. * @param endValue End value of the animation curve
  51988. * @param inTangent Start tangent of the animation curve
  51989. * @param gradient Scalar amount to interpolate
  51990. * @returns Interpolated Vector2 value
  51991. */
  51992. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51993. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51994. };
  51995. /**
  51996. * Interpolates a size linearly
  51997. * @param startValue Start value of the animation curve
  51998. * @param endValue End value of the animation curve
  51999. * @param gradient Scalar amount to interpolate
  52000. * @returns Interpolated Size value
  52001. */
  52002. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  52003. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  52004. };
  52005. /**
  52006. * Interpolates a Color3 linearly
  52007. * @param startValue Start value of the animation curve
  52008. * @param endValue End value of the animation curve
  52009. * @param gradient Scalar amount to interpolate
  52010. * @returns Interpolated Color3 value
  52011. */
  52012. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  52013. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  52014. };
  52015. /**
  52016. * @hidden Internal use only
  52017. */
  52018. Animation.prototype._getKeyValue = function (value) {
  52019. if (typeof value === "function") {
  52020. return value();
  52021. }
  52022. return value;
  52023. };
  52024. /**
  52025. * @hidden Internal use only
  52026. */
  52027. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  52028. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  52029. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  52030. }
  52031. var keys = this.getKeys();
  52032. // Try to get a hash to find the right key
  52033. 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));
  52034. if (keys[startKeyIndex].frame >= currentFrame) {
  52035. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  52036. startKeyIndex--;
  52037. }
  52038. }
  52039. for (var key = startKeyIndex; key < keys.length; key++) {
  52040. var endKey = keys[key + 1];
  52041. if (endKey.frame >= currentFrame) {
  52042. var startKey = keys[key];
  52043. var startValue = this._getKeyValue(startKey.value);
  52044. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  52045. return startValue;
  52046. }
  52047. var endValue = this._getKeyValue(endKey.value);
  52048. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  52049. var frameDelta = endKey.frame - startKey.frame;
  52050. // gradient : percent of currentFrame between the frame inf and the frame sup
  52051. var gradient = (currentFrame - startKey.frame) / frameDelta;
  52052. // check for easingFunction and correction of gradient
  52053. var easingFunction = this.getEasingFunction();
  52054. if (easingFunction != null) {
  52055. gradient = easingFunction.ease(gradient);
  52056. }
  52057. switch (this.dataType) {
  52058. // Float
  52059. case Animation.ANIMATIONTYPE_FLOAT:
  52060. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  52061. switch (loopMode) {
  52062. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52063. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52064. return floatValue;
  52065. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52066. return offsetValue * repeatCount + floatValue;
  52067. }
  52068. break;
  52069. // Quaternion
  52070. case Animation.ANIMATIONTYPE_QUATERNION:
  52071. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  52072. switch (loopMode) {
  52073. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52074. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52075. return quatValue;
  52076. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52077. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  52078. }
  52079. return quatValue;
  52080. // Vector3
  52081. case Animation.ANIMATIONTYPE_VECTOR3:
  52082. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  52083. switch (loopMode) {
  52084. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52085. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52086. return vec3Value;
  52087. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52088. return vec3Value.add(offsetValue.scale(repeatCount));
  52089. }
  52090. // Vector2
  52091. case Animation.ANIMATIONTYPE_VECTOR2:
  52092. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  52093. switch (loopMode) {
  52094. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52095. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52096. return vec2Value;
  52097. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52098. return vec2Value.add(offsetValue.scale(repeatCount));
  52099. }
  52100. // Size
  52101. case Animation.ANIMATIONTYPE_SIZE:
  52102. switch (loopMode) {
  52103. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52104. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52105. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  52106. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52107. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  52108. }
  52109. // Color3
  52110. case Animation.ANIMATIONTYPE_COLOR3:
  52111. switch (loopMode) {
  52112. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52113. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52114. return this.color3InterpolateFunction(startValue, endValue, gradient);
  52115. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52116. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  52117. }
  52118. // Matrix
  52119. case Animation.ANIMATIONTYPE_MATRIX:
  52120. switch (loopMode) {
  52121. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52122. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52123. if (Animation.AllowMatricesInterpolation) {
  52124. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  52125. }
  52126. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52127. return startValue;
  52128. }
  52129. default:
  52130. break;
  52131. }
  52132. break;
  52133. }
  52134. }
  52135. return this._getKeyValue(keys[keys.length - 1].value);
  52136. };
  52137. /**
  52138. * Defines the function to use to interpolate matrices
  52139. * @param startValue defines the start matrix
  52140. * @param endValue defines the end matrix
  52141. * @param gradient defines the gradient between both matrices
  52142. * @param result defines an optional target matrix where to store the interpolation
  52143. * @returns the interpolated matrix
  52144. */
  52145. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  52146. if (Animation.AllowMatrixDecomposeForInterpolation) {
  52147. if (result) {
  52148. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  52149. return result;
  52150. }
  52151. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  52152. }
  52153. if (result) {
  52154. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  52155. return result;
  52156. }
  52157. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  52158. };
  52159. /**
  52160. * Makes a copy of the animation
  52161. * @returns Cloned animation
  52162. */
  52163. Animation.prototype.clone = function () {
  52164. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  52165. clone.enableBlending = this.enableBlending;
  52166. clone.blendingSpeed = this.blendingSpeed;
  52167. if (this._keys) {
  52168. clone.setKeys(this._keys);
  52169. }
  52170. if (this._ranges) {
  52171. clone._ranges = {};
  52172. for (var name in this._ranges) {
  52173. var range = this._ranges[name];
  52174. if (!range) {
  52175. continue;
  52176. }
  52177. clone._ranges[name] = range.clone();
  52178. }
  52179. }
  52180. return clone;
  52181. };
  52182. /**
  52183. * Sets the key frames of the animation
  52184. * @param values The animation key frames to set
  52185. */
  52186. Animation.prototype.setKeys = function (values) {
  52187. this._keys = values.slice(0);
  52188. };
  52189. /**
  52190. * Serializes the animation to an object
  52191. * @returns Serialized object
  52192. */
  52193. Animation.prototype.serialize = function () {
  52194. var serializationObject = {};
  52195. serializationObject.name = this.name;
  52196. serializationObject.property = this.targetProperty;
  52197. serializationObject.framePerSecond = this.framePerSecond;
  52198. serializationObject.dataType = this.dataType;
  52199. serializationObject.loopBehavior = this.loopMode;
  52200. serializationObject.enableBlending = this.enableBlending;
  52201. serializationObject.blendingSpeed = this.blendingSpeed;
  52202. var dataType = this.dataType;
  52203. serializationObject.keys = [];
  52204. var keys = this.getKeys();
  52205. for (var index = 0; index < keys.length; index++) {
  52206. var animationKey = keys[index];
  52207. var key = {};
  52208. key.frame = animationKey.frame;
  52209. switch (dataType) {
  52210. case Animation.ANIMATIONTYPE_FLOAT:
  52211. key.values = [animationKey.value];
  52212. break;
  52213. case Animation.ANIMATIONTYPE_QUATERNION:
  52214. case Animation.ANIMATIONTYPE_MATRIX:
  52215. case Animation.ANIMATIONTYPE_VECTOR3:
  52216. case Animation.ANIMATIONTYPE_COLOR3:
  52217. key.values = animationKey.value.asArray();
  52218. break;
  52219. }
  52220. serializationObject.keys.push(key);
  52221. }
  52222. serializationObject.ranges = [];
  52223. for (var name in this._ranges) {
  52224. var source = this._ranges[name];
  52225. if (!source) {
  52226. continue;
  52227. }
  52228. var range = {};
  52229. range.name = name;
  52230. range.from = source.from;
  52231. range.to = source.to;
  52232. serializationObject.ranges.push(range);
  52233. }
  52234. return serializationObject;
  52235. };
  52236. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  52237. /**
  52238. * Get the float animation type
  52239. */
  52240. get: function () {
  52241. return Animation._ANIMATIONTYPE_FLOAT;
  52242. },
  52243. enumerable: true,
  52244. configurable: true
  52245. });
  52246. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  52247. /**
  52248. * Get the Vector3 animation type
  52249. */
  52250. get: function () {
  52251. return Animation._ANIMATIONTYPE_VECTOR3;
  52252. },
  52253. enumerable: true,
  52254. configurable: true
  52255. });
  52256. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  52257. /**
  52258. * Get the Vector2 animation type
  52259. */
  52260. get: function () {
  52261. return Animation._ANIMATIONTYPE_VECTOR2;
  52262. },
  52263. enumerable: true,
  52264. configurable: true
  52265. });
  52266. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  52267. /**
  52268. * Get the Size animation type
  52269. */
  52270. get: function () {
  52271. return Animation._ANIMATIONTYPE_SIZE;
  52272. },
  52273. enumerable: true,
  52274. configurable: true
  52275. });
  52276. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  52277. /**
  52278. * Get the Quaternion animation type
  52279. */
  52280. get: function () {
  52281. return Animation._ANIMATIONTYPE_QUATERNION;
  52282. },
  52283. enumerable: true,
  52284. configurable: true
  52285. });
  52286. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  52287. /**
  52288. * Get the Matrix animation type
  52289. */
  52290. get: function () {
  52291. return Animation._ANIMATIONTYPE_MATRIX;
  52292. },
  52293. enumerable: true,
  52294. configurable: true
  52295. });
  52296. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  52297. /**
  52298. * Get the Color3 animation type
  52299. */
  52300. get: function () {
  52301. return Animation._ANIMATIONTYPE_COLOR3;
  52302. },
  52303. enumerable: true,
  52304. configurable: true
  52305. });
  52306. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  52307. /**
  52308. * Get the Relative Loop Mode
  52309. */
  52310. get: function () {
  52311. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  52312. },
  52313. enumerable: true,
  52314. configurable: true
  52315. });
  52316. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  52317. /**
  52318. * Get the Cycle Loop Mode
  52319. */
  52320. get: function () {
  52321. return Animation._ANIMATIONLOOPMODE_CYCLE;
  52322. },
  52323. enumerable: true,
  52324. configurable: true
  52325. });
  52326. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  52327. /**
  52328. * Get the Constant Loop Mode
  52329. */
  52330. get: function () {
  52331. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  52332. },
  52333. enumerable: true,
  52334. configurable: true
  52335. });
  52336. /** @hidden */
  52337. Animation._UniversalLerp = function (left, right, amount) {
  52338. var constructor = left.constructor;
  52339. if (constructor.Lerp) { // Lerp supported
  52340. return constructor.Lerp(left, right, amount);
  52341. }
  52342. else if (constructor.Slerp) { // Slerp supported
  52343. return constructor.Slerp(left, right, amount);
  52344. }
  52345. else if (left.toFixed) { // Number
  52346. return left * (1.0 - amount) + amount * right;
  52347. }
  52348. else { // Blending not supported
  52349. return right;
  52350. }
  52351. };
  52352. /**
  52353. * Parses an animation object and creates an animation
  52354. * @param parsedAnimation Parsed animation object
  52355. * @returns Animation object
  52356. */
  52357. Animation.Parse = function (parsedAnimation) {
  52358. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  52359. var dataType = parsedAnimation.dataType;
  52360. var keys = [];
  52361. var data;
  52362. var index;
  52363. if (parsedAnimation.enableBlending) {
  52364. animation.enableBlending = parsedAnimation.enableBlending;
  52365. }
  52366. if (parsedAnimation.blendingSpeed) {
  52367. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  52368. }
  52369. for (index = 0; index < parsedAnimation.keys.length; index++) {
  52370. var key = parsedAnimation.keys[index];
  52371. var inTangent;
  52372. var outTangent;
  52373. switch (dataType) {
  52374. case Animation.ANIMATIONTYPE_FLOAT:
  52375. data = key.values[0];
  52376. if (key.values.length >= 1) {
  52377. inTangent = key.values[1];
  52378. }
  52379. if (key.values.length >= 2) {
  52380. outTangent = key.values[2];
  52381. }
  52382. break;
  52383. case Animation.ANIMATIONTYPE_QUATERNION:
  52384. data = BABYLON.Quaternion.FromArray(key.values);
  52385. if (key.values.length >= 8) {
  52386. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  52387. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  52388. inTangent = _inTangent;
  52389. }
  52390. }
  52391. if (key.values.length >= 12) {
  52392. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  52393. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  52394. outTangent = _outTangent;
  52395. }
  52396. }
  52397. break;
  52398. case Animation.ANIMATIONTYPE_MATRIX:
  52399. data = BABYLON.Matrix.FromArray(key.values);
  52400. break;
  52401. case Animation.ANIMATIONTYPE_COLOR3:
  52402. data = BABYLON.Color3.FromArray(key.values);
  52403. break;
  52404. case Animation.ANIMATIONTYPE_VECTOR3:
  52405. default:
  52406. data = BABYLON.Vector3.FromArray(key.values);
  52407. break;
  52408. }
  52409. var keyData = {};
  52410. keyData.frame = key.frame;
  52411. keyData.value = data;
  52412. if (inTangent != undefined) {
  52413. keyData.inTangent = inTangent;
  52414. }
  52415. if (outTangent != undefined) {
  52416. keyData.outTangent = outTangent;
  52417. }
  52418. keys.push(keyData);
  52419. }
  52420. animation.setKeys(keys);
  52421. if (parsedAnimation.ranges) {
  52422. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  52423. data = parsedAnimation.ranges[index];
  52424. animation.createRange(data.name, data.from, data.to);
  52425. }
  52426. }
  52427. return animation;
  52428. };
  52429. /**
  52430. * Appends the serialized animations from the source animations
  52431. * @param source Source containing the animations
  52432. * @param destination Target to store the animations
  52433. */
  52434. Animation.AppendSerializedAnimations = function (source, destination) {
  52435. if (source.animations) {
  52436. destination.animations = [];
  52437. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  52438. var animation = source.animations[animationIndex];
  52439. destination.animations.push(animation.serialize());
  52440. }
  52441. }
  52442. };
  52443. /**
  52444. * Use matrix interpolation instead of using direct key value when animating matrices
  52445. */
  52446. Animation.AllowMatricesInterpolation = false;
  52447. /**
  52448. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  52449. */
  52450. Animation.AllowMatrixDecomposeForInterpolation = true;
  52451. // Statics
  52452. /**
  52453. * Float animation type
  52454. */
  52455. Animation._ANIMATIONTYPE_FLOAT = 0;
  52456. /**
  52457. * Vector3 animation type
  52458. */
  52459. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  52460. /**
  52461. * Quaternion animation type
  52462. */
  52463. Animation._ANIMATIONTYPE_QUATERNION = 2;
  52464. /**
  52465. * Matrix animation type
  52466. */
  52467. Animation._ANIMATIONTYPE_MATRIX = 3;
  52468. /**
  52469. * Color3 animation type
  52470. */
  52471. Animation._ANIMATIONTYPE_COLOR3 = 4;
  52472. /**
  52473. * Vector2 animation type
  52474. */
  52475. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  52476. /**
  52477. * Size animation type
  52478. */
  52479. Animation._ANIMATIONTYPE_SIZE = 6;
  52480. /**
  52481. * Relative Loop Mode
  52482. */
  52483. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  52484. /**
  52485. * Cycle Loop Mode
  52486. */
  52487. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  52488. /**
  52489. * Constant Loop Mode
  52490. */
  52491. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  52492. return Animation;
  52493. }());
  52494. BABYLON.Animation = Animation;
  52495. })(BABYLON || (BABYLON = {}));
  52496. //# sourceMappingURL=babylon.animation.js.map
  52497. var BABYLON;
  52498. (function (BABYLON) {
  52499. /**
  52500. * This class defines the direct association between an animation and a target
  52501. */
  52502. var TargetedAnimation = /** @class */ (function () {
  52503. function TargetedAnimation() {
  52504. }
  52505. return TargetedAnimation;
  52506. }());
  52507. BABYLON.TargetedAnimation = TargetedAnimation;
  52508. /**
  52509. * Use this class to create coordinated animations on multiple targets
  52510. */
  52511. var AnimationGroup = /** @class */ (function () {
  52512. /**
  52513. * Instantiates a new Animation Group.
  52514. * This helps managing several animations at once.
  52515. * @see http://doc.babylonjs.com/how_to/group
  52516. * @param name Defines the name of the group
  52517. * @param scene Defines the scene the group belongs to
  52518. */
  52519. function AnimationGroup(
  52520. /** The name of the animation group */
  52521. name, scene) {
  52522. if (scene === void 0) { scene = null; }
  52523. this.name = name;
  52524. this._targetedAnimations = new Array();
  52525. this._animatables = new Array();
  52526. this._from = Number.MAX_VALUE;
  52527. this._to = -Number.MAX_VALUE;
  52528. this._speedRatio = 1;
  52529. /**
  52530. * This observable will notify when one animation have ended.
  52531. */
  52532. this.onAnimationEndObservable = new BABYLON.Observable();
  52533. /**
  52534. * This observable will notify when all animations have ended.
  52535. */
  52536. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  52537. /**
  52538. * This observable will notify when all animations have paused.
  52539. */
  52540. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  52541. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52542. this._scene.animationGroups.push(this);
  52543. }
  52544. Object.defineProperty(AnimationGroup.prototype, "from", {
  52545. /**
  52546. * Gets the first frame
  52547. */
  52548. get: function () {
  52549. return this._from;
  52550. },
  52551. enumerable: true,
  52552. configurable: true
  52553. });
  52554. Object.defineProperty(AnimationGroup.prototype, "to", {
  52555. /**
  52556. * Gets the last frame
  52557. */
  52558. get: function () {
  52559. return this._to;
  52560. },
  52561. enumerable: true,
  52562. configurable: true
  52563. });
  52564. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  52565. /**
  52566. * Define if the animations are started
  52567. */
  52568. get: function () {
  52569. return this._isStarted;
  52570. },
  52571. enumerable: true,
  52572. configurable: true
  52573. });
  52574. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  52575. /**
  52576. * Gets or sets the speed ratio to use for all animations
  52577. */
  52578. get: function () {
  52579. return this._speedRatio;
  52580. },
  52581. /**
  52582. * Gets or sets the speed ratio to use for all animations
  52583. */
  52584. set: function (value) {
  52585. if (this._speedRatio === value) {
  52586. return;
  52587. }
  52588. this._speedRatio = value;
  52589. for (var index = 0; index < this._animatables.length; index++) {
  52590. var animatable = this._animatables[index];
  52591. animatable.speedRatio = this._speedRatio;
  52592. }
  52593. },
  52594. enumerable: true,
  52595. configurable: true
  52596. });
  52597. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  52598. /**
  52599. * Gets the targeted animations for this animation group
  52600. */
  52601. get: function () {
  52602. return this._targetedAnimations;
  52603. },
  52604. enumerable: true,
  52605. configurable: true
  52606. });
  52607. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  52608. /**
  52609. * returning the list of animatables controlled by this animation group.
  52610. */
  52611. get: function () {
  52612. return this._animatables;
  52613. },
  52614. enumerable: true,
  52615. configurable: true
  52616. });
  52617. /**
  52618. * Add an animation (with its target) in the group
  52619. * @param animation defines the animation we want to add
  52620. * @param target defines the target of the animation
  52621. * @returns the {BABYLON.TargetedAnimation} object
  52622. */
  52623. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  52624. var targetedAnimation = {
  52625. animation: animation,
  52626. target: target
  52627. };
  52628. var keys = animation.getKeys();
  52629. if (this._from > keys[0].frame) {
  52630. this._from = keys[0].frame;
  52631. }
  52632. if (this._to < keys[keys.length - 1].frame) {
  52633. this._to = keys[keys.length - 1].frame;
  52634. }
  52635. this._targetedAnimations.push(targetedAnimation);
  52636. return targetedAnimation;
  52637. };
  52638. /**
  52639. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  52640. * It can add constant keys at begin or end
  52641. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  52642. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  52643. * @returns the animation group
  52644. */
  52645. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  52646. if (beginFrame === void 0) { beginFrame = null; }
  52647. if (endFrame === void 0) { endFrame = null; }
  52648. if (beginFrame == null)
  52649. beginFrame = this._from;
  52650. if (endFrame == null)
  52651. endFrame = this._to;
  52652. for (var index = 0; index < this._targetedAnimations.length; index++) {
  52653. var targetedAnimation = this._targetedAnimations[index];
  52654. var keys = targetedAnimation.animation.getKeys();
  52655. var startKey = keys[0];
  52656. var endKey = keys[keys.length - 1];
  52657. if (startKey.frame > beginFrame) {
  52658. var newKey = {
  52659. frame: beginFrame,
  52660. value: startKey.value,
  52661. inTangent: startKey.inTangent,
  52662. outTangent: startKey.outTangent,
  52663. interpolation: startKey.interpolation
  52664. };
  52665. keys.splice(0, 0, newKey);
  52666. }
  52667. if (endKey.frame < endFrame) {
  52668. var newKey = {
  52669. frame: endFrame,
  52670. value: endKey.value,
  52671. inTangent: endKey.outTangent,
  52672. outTangent: endKey.outTangent,
  52673. interpolation: endKey.interpolation
  52674. };
  52675. keys.push(newKey);
  52676. }
  52677. }
  52678. this._from = beginFrame;
  52679. this._to = endFrame;
  52680. return this;
  52681. };
  52682. /**
  52683. * Start all animations on given targets
  52684. * @param loop defines if animations must loop
  52685. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  52686. * @param from defines the from key (optional)
  52687. * @param to defines the to key (optional)
  52688. * @returns the current animation group
  52689. */
  52690. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  52691. var _this = this;
  52692. if (loop === void 0) { loop = false; }
  52693. if (speedRatio === void 0) { speedRatio = 1; }
  52694. if (this._isStarted || this._targetedAnimations.length === 0) {
  52695. return this;
  52696. }
  52697. var _loop_1 = function (targetedAnimation) {
  52698. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  52699. animatable.onAnimationEnd = function () {
  52700. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  52701. _this._checkAnimationGroupEnded(animatable);
  52702. };
  52703. this_1._animatables.push(animatable);
  52704. };
  52705. var this_1 = this;
  52706. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  52707. var targetedAnimation = _a[_i];
  52708. _loop_1(targetedAnimation);
  52709. }
  52710. this._speedRatio = speedRatio;
  52711. this._isStarted = true;
  52712. return this;
  52713. };
  52714. /**
  52715. * Pause all animations
  52716. * @returns the animation group
  52717. */
  52718. AnimationGroup.prototype.pause = function () {
  52719. if (!this._isStarted) {
  52720. return this;
  52721. }
  52722. for (var index = 0; index < this._animatables.length; index++) {
  52723. var animatable = this._animatables[index];
  52724. animatable.pause();
  52725. }
  52726. this.onAnimationGroupPauseObservable.notifyObservers(this);
  52727. return this;
  52728. };
  52729. /**
  52730. * Play all animations to initial state
  52731. * This function will start() the animations if they were not started or will restart() them if they were paused
  52732. * @param loop defines if animations must loop
  52733. * @returns the animation group
  52734. */
  52735. AnimationGroup.prototype.play = function (loop) {
  52736. // only if all animatables are ready and exist
  52737. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  52738. if (loop !== undefined) {
  52739. for (var index = 0; index < this._animatables.length; index++) {
  52740. var animatable = this._animatables[index];
  52741. animatable.loopAnimation = loop;
  52742. }
  52743. }
  52744. this.restart();
  52745. }
  52746. else {
  52747. this.stop();
  52748. this.start(loop, this._speedRatio);
  52749. }
  52750. return this;
  52751. };
  52752. /**
  52753. * Reset all animations to initial state
  52754. * @returns the animation group
  52755. */
  52756. AnimationGroup.prototype.reset = function () {
  52757. if (!this._isStarted) {
  52758. return this;
  52759. }
  52760. for (var index = 0; index < this._animatables.length; index++) {
  52761. var animatable = this._animatables[index];
  52762. animatable.reset();
  52763. }
  52764. return this;
  52765. };
  52766. /**
  52767. * Restart animations from key 0
  52768. * @returns the animation group
  52769. */
  52770. AnimationGroup.prototype.restart = function () {
  52771. if (!this._isStarted) {
  52772. return this;
  52773. }
  52774. for (var index = 0; index < this._animatables.length; index++) {
  52775. var animatable = this._animatables[index];
  52776. animatable.restart();
  52777. }
  52778. return this;
  52779. };
  52780. /**
  52781. * Stop all animations
  52782. * @returns the animation group
  52783. */
  52784. AnimationGroup.prototype.stop = function () {
  52785. if (!this._isStarted) {
  52786. return this;
  52787. }
  52788. var list = this._animatables.slice();
  52789. for (var index = 0; index < list.length; index++) {
  52790. list[index].stop();
  52791. }
  52792. this._isStarted = false;
  52793. return this;
  52794. };
  52795. /**
  52796. * Set animation weight for all animatables
  52797. * @param weight defines the weight to use
  52798. * @return the animationGroup
  52799. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  52800. */
  52801. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  52802. for (var index = 0; index < this._animatables.length; index++) {
  52803. var animatable = this._animatables[index];
  52804. animatable.weight = weight;
  52805. }
  52806. return this;
  52807. };
  52808. /**
  52809. * Synchronize and normalize all animatables with a source animatable
  52810. * @param root defines the root animatable to synchronize with
  52811. * @return the animationGroup
  52812. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  52813. */
  52814. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  52815. for (var index = 0; index < this._animatables.length; index++) {
  52816. var animatable = this._animatables[index];
  52817. animatable.syncWith(root);
  52818. }
  52819. return this;
  52820. };
  52821. /**
  52822. * Goes to a specific frame in this animation group
  52823. * @param frame the frame number to go to
  52824. * @return the animationGroup
  52825. */
  52826. AnimationGroup.prototype.goToFrame = function (frame) {
  52827. if (!this._isStarted) {
  52828. return this;
  52829. }
  52830. for (var index = 0; index < this._animatables.length; index++) {
  52831. var animatable = this._animatables[index];
  52832. animatable.goToFrame(frame);
  52833. }
  52834. return this;
  52835. };
  52836. /**
  52837. * Dispose all associated resources
  52838. */
  52839. AnimationGroup.prototype.dispose = function () {
  52840. this._targetedAnimations = [];
  52841. this._animatables = [];
  52842. var index = this._scene.animationGroups.indexOf(this);
  52843. if (index > -1) {
  52844. this._scene.animationGroups.splice(index, 1);
  52845. }
  52846. };
  52847. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  52848. // animatable should be taken out of the array
  52849. var idx = this._animatables.indexOf(animatable);
  52850. if (idx > -1) {
  52851. this._animatables.splice(idx, 1);
  52852. }
  52853. // all animatables were removed? animation group ended!
  52854. if (this._animatables.length === 0) {
  52855. this._isStarted = false;
  52856. this.onAnimationGroupEndObservable.notifyObservers(this);
  52857. }
  52858. };
  52859. // Statics
  52860. /**
  52861. * Returns a new AnimationGroup object parsed from the source provided.
  52862. * @param parsedAnimationGroup defines the source
  52863. * @param scene defines the scene that will receive the animationGroup
  52864. * @returns a new AnimationGroup
  52865. */
  52866. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  52867. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  52868. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  52869. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  52870. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  52871. var id = targetedAnimation.targetId;
  52872. var targetNode = scene.getNodeByID(id);
  52873. if (targetNode != null)
  52874. animationGroup.addTargetedAnimation(animation, targetNode);
  52875. }
  52876. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null)
  52877. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  52878. return animationGroup;
  52879. };
  52880. /**
  52881. * Returns the string "AnimationGroup"
  52882. * @returns "AnimationGroup"
  52883. */
  52884. AnimationGroup.prototype.getClassName = function () {
  52885. return "AnimationGroup";
  52886. };
  52887. /**
  52888. * Creates a detailled string about the object
  52889. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  52890. * @returns a string representing the object
  52891. */
  52892. AnimationGroup.prototype.toString = function (fullDetails) {
  52893. var ret = "Name: " + this.name;
  52894. ret += ", type: " + this.getClassName();
  52895. if (fullDetails) {
  52896. ret += ", from: " + this._from;
  52897. ret += ", to: " + this._to;
  52898. ret += ", isStarted: " + this._isStarted;
  52899. ret += ", speedRatio: " + this._speedRatio;
  52900. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  52901. ret += ", animatables length: " + this._animatables;
  52902. }
  52903. return ret;
  52904. };
  52905. return AnimationGroup;
  52906. }());
  52907. BABYLON.AnimationGroup = AnimationGroup;
  52908. })(BABYLON || (BABYLON = {}));
  52909. //# sourceMappingURL=babylon.animationGroup.js.map
  52910. var BABYLON;
  52911. (function (BABYLON) {
  52912. // Static values to help the garbage collector
  52913. // Quaternion
  52914. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  52915. // Vector3
  52916. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  52917. // Vector2
  52918. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  52919. // Size
  52920. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  52921. // Color3
  52922. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  52923. /**
  52924. * Defines a runtime animation
  52925. */
  52926. var RuntimeAnimation = /** @class */ (function () {
  52927. /**
  52928. * Create a new RuntimeAnimation object
  52929. * @param target defines the target of the animation
  52930. * @param animation defines the source animation object
  52931. * @param scene defines the hosting scene
  52932. * @param host defines the initiating Animatable
  52933. */
  52934. function RuntimeAnimation(target, animation, scene, host) {
  52935. var _this = this;
  52936. this._events = new Array();
  52937. /**
  52938. * The current frame of the runtime animation
  52939. */
  52940. this._currentFrame = 0;
  52941. /**
  52942. * The original value of the runtime animation
  52943. */
  52944. this._originalValue = new Array();
  52945. /**
  52946. * The offsets cache of the runtime animation
  52947. */
  52948. this._offsetsCache = {};
  52949. /**
  52950. * The high limits cache of the runtime animation
  52951. */
  52952. this._highLimitsCache = {};
  52953. /**
  52954. * Specifies if the runtime animation has been stopped
  52955. */
  52956. this._stopped = false;
  52957. /**
  52958. * The blending factor of the runtime animation
  52959. */
  52960. this._blendingFactor = 0;
  52961. /**
  52962. * The target path of the runtime animation
  52963. */
  52964. this._targetPath = "";
  52965. /**
  52966. * The weight of the runtime animation
  52967. */
  52968. this._weight = 1.0;
  52969. /**
  52970. * The ratio offset of the runtime animation
  52971. */
  52972. this._ratioOffset = 0;
  52973. /**
  52974. * The previous delay of the runtime animation
  52975. */
  52976. this._previousDelay = 0;
  52977. /**
  52978. * The previous ratio of the runtime animation
  52979. */
  52980. this._previousRatio = 0;
  52981. this._animation = animation;
  52982. this._target = target;
  52983. this._scene = scene;
  52984. this._host = host;
  52985. animation._runtimeAnimations.push(this);
  52986. // Cloning events locally
  52987. var events = animation.getEvents();
  52988. if (events && events.length > 0) {
  52989. events.forEach(function (e) {
  52990. _this._events.push(e._clone());
  52991. });
  52992. }
  52993. }
  52994. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  52995. /**
  52996. * Gets the current frame of the runtime animation
  52997. */
  52998. get: function () {
  52999. return this._currentFrame;
  53000. },
  53001. enumerable: true,
  53002. configurable: true
  53003. });
  53004. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  53005. /**
  53006. * Gets the weight of the runtime animation
  53007. */
  53008. get: function () {
  53009. return this._weight;
  53010. },
  53011. enumerable: true,
  53012. configurable: true
  53013. });
  53014. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  53015. /**
  53016. * Gets the current value of the runtime animation
  53017. */
  53018. get: function () {
  53019. return this._currentValue;
  53020. },
  53021. enumerable: true,
  53022. configurable: true
  53023. });
  53024. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  53025. /**
  53026. * Gets the target path of the runtime animation
  53027. */
  53028. get: function () {
  53029. return this._targetPath;
  53030. },
  53031. enumerable: true,
  53032. configurable: true
  53033. });
  53034. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  53035. /**
  53036. * Gets the actual target of the runtime animation
  53037. */
  53038. get: function () {
  53039. return this._activeTarget;
  53040. },
  53041. enumerable: true,
  53042. configurable: true
  53043. });
  53044. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  53045. /**
  53046. * Gets the animation from the runtime animation
  53047. */
  53048. get: function () {
  53049. return this._animation;
  53050. },
  53051. enumerable: true,
  53052. configurable: true
  53053. });
  53054. /**
  53055. * Resets the runtime animation to the beginning
  53056. * @param restoreOriginal defines whether to restore the target property to the original value
  53057. */
  53058. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  53059. if (restoreOriginal === void 0) { restoreOriginal = false; }
  53060. if (restoreOriginal) {
  53061. if (this._target instanceof Array) {
  53062. var index = 0;
  53063. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  53064. var target = _a[_i];
  53065. if (this._originalValue[index] !== undefined) {
  53066. this._setValue(target, this._originalValue[index], -1);
  53067. }
  53068. index++;
  53069. }
  53070. }
  53071. else {
  53072. if (this._originalValue[0] !== undefined) {
  53073. this._setValue(this._target, this._originalValue[0], -1);
  53074. }
  53075. }
  53076. }
  53077. this._offsetsCache = {};
  53078. this._highLimitsCache = {};
  53079. this._currentFrame = 0;
  53080. this._blendingFactor = 0;
  53081. this._originalValue = new Array();
  53082. // Events
  53083. for (var index = 0; index < this._events.length; index++) {
  53084. this._events[index].isDone = false;
  53085. }
  53086. };
  53087. /**
  53088. * Specifies if the runtime animation is stopped
  53089. * @returns Boolean specifying if the runtime animation is stopped
  53090. */
  53091. RuntimeAnimation.prototype.isStopped = function () {
  53092. return this._stopped;
  53093. };
  53094. /**
  53095. * Disposes of the runtime animation
  53096. */
  53097. RuntimeAnimation.prototype.dispose = function () {
  53098. var index = this._animation.runtimeAnimations.indexOf(this);
  53099. if (index > -1) {
  53100. this._animation.runtimeAnimations.splice(index, 1);
  53101. }
  53102. };
  53103. /**
  53104. * Interpolates the animation from the current frame
  53105. * @param currentFrame The frame to interpolate the animation to
  53106. * @param repeatCount The number of times that the animation should loop
  53107. * @param loopMode The type of looping mode to use
  53108. * @param offsetValue Animation offset value
  53109. * @param highLimitValue The high limit value
  53110. * @returns The interpolated value
  53111. */
  53112. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  53113. this._currentFrame = currentFrame;
  53114. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  53115. this._workValue = BABYLON.Matrix.Zero();
  53116. }
  53117. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  53118. };
  53119. /**
  53120. * Apply the interpolated value to the target
  53121. * @param currentValue defines the value computed by the animation
  53122. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  53123. */
  53124. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  53125. if (weight === void 0) { weight = 1.0; }
  53126. if (this._target instanceof Array) {
  53127. var index = 0;
  53128. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  53129. var target = _a[_i];
  53130. this._setValue(target, currentValue, weight, index);
  53131. index++;
  53132. }
  53133. }
  53134. else {
  53135. this._setValue(this._target, currentValue, weight);
  53136. }
  53137. };
  53138. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  53139. if (targetIndex === void 0) { targetIndex = 0; }
  53140. // Set value
  53141. var path;
  53142. var destination;
  53143. var targetPropertyPath = this._animation.targetPropertyPath;
  53144. if (targetPropertyPath.length > 1) {
  53145. var property = target[targetPropertyPath[0]];
  53146. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  53147. property = property[targetPropertyPath[index]];
  53148. }
  53149. path = targetPropertyPath[targetPropertyPath.length - 1];
  53150. destination = property;
  53151. }
  53152. else {
  53153. path = targetPropertyPath[0];
  53154. destination = target;
  53155. }
  53156. this._targetPath = path;
  53157. this._activeTarget = destination;
  53158. this._weight = weight;
  53159. if (this._originalValue[targetIndex] === undefined) {
  53160. var originalValue = void 0;
  53161. if (destination.getRestPose && path === "_matrix") { // For bones
  53162. originalValue = destination.getRestPose();
  53163. }
  53164. else {
  53165. originalValue = destination[path];
  53166. }
  53167. if (originalValue && originalValue.clone) {
  53168. this._originalValue[targetIndex] = originalValue.clone();
  53169. }
  53170. else {
  53171. this._originalValue[targetIndex] = originalValue;
  53172. }
  53173. }
  53174. // Blending
  53175. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  53176. if (enableBlending && this._blendingFactor <= 1.0) {
  53177. if (!this._originalBlendValue) {
  53178. var originalValue = destination[path];
  53179. if (originalValue.clone) {
  53180. this._originalBlendValue = originalValue.clone();
  53181. }
  53182. else {
  53183. this._originalBlendValue = originalValue;
  53184. }
  53185. }
  53186. if (this._originalBlendValue.m) { // Matrix
  53187. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  53188. if (this._currentValue) {
  53189. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  53190. }
  53191. else {
  53192. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  53193. }
  53194. }
  53195. else {
  53196. if (this._currentValue) {
  53197. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  53198. }
  53199. else {
  53200. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  53201. }
  53202. }
  53203. }
  53204. else {
  53205. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  53206. }
  53207. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  53208. this._blendingFactor += blendingSpeed;
  53209. }
  53210. else {
  53211. this._currentValue = currentValue;
  53212. }
  53213. if (weight !== -1.0) {
  53214. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  53215. }
  53216. else {
  53217. destination[path] = this._currentValue;
  53218. }
  53219. if (target.markAsDirty) {
  53220. target.markAsDirty(this._animation.targetProperty);
  53221. }
  53222. };
  53223. /**
  53224. * Gets the loop pmode of the runtime animation
  53225. * @returns Loop Mode
  53226. */
  53227. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  53228. if (this._target && this._target.animationPropertiesOverride) {
  53229. return this._target.animationPropertiesOverride.loopMode;
  53230. }
  53231. return this._animation.loopMode;
  53232. };
  53233. /**
  53234. * Move the current animation to a given frame
  53235. * @param frame defines the frame to move to
  53236. */
  53237. RuntimeAnimation.prototype.goToFrame = function (frame) {
  53238. var keys = this._animation.getKeys();
  53239. if (frame < keys[0].frame) {
  53240. frame = keys[0].frame;
  53241. }
  53242. else if (frame > keys[keys.length - 1].frame) {
  53243. frame = keys[keys.length - 1].frame;
  53244. }
  53245. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  53246. this.setValue(currentValue, -1);
  53247. };
  53248. /**
  53249. * @hidden Internal use only
  53250. */
  53251. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  53252. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  53253. this._ratioOffset = this._previousRatio - newRatio;
  53254. };
  53255. /**
  53256. * Execute the current animation
  53257. * @param delay defines the delay to add to the current frame
  53258. * @param from defines the lower bound of the animation range
  53259. * @param to defines the upper bound of the animation range
  53260. * @param loop defines if the current animation must loop
  53261. * @param speedRatio defines the current speed ratio
  53262. * @param weight defines the weight of the animation (default is -1 so no weight)
  53263. * @returns a boolean indicating if the animation is running
  53264. */
  53265. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  53266. if (weight === void 0) { weight = -1.0; }
  53267. var targetPropertyPath = this._animation.targetPropertyPath;
  53268. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  53269. this._stopped = true;
  53270. return false;
  53271. }
  53272. var returnValue = true;
  53273. var keys = this._animation.getKeys();
  53274. // Adding a start key at frame 0 if missing
  53275. if (keys[0].frame !== 0) {
  53276. var newKey = { frame: 0, value: keys[0].value };
  53277. keys.splice(0, 0, newKey);
  53278. }
  53279. // Adding a duplicate key when there is only one key at frame zero
  53280. else if (keys.length === 1) {
  53281. var newKey = { frame: 0.001, value: keys[0].value };
  53282. keys.push(newKey);
  53283. }
  53284. // Check limits
  53285. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  53286. from = keys[0].frame;
  53287. }
  53288. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  53289. to = keys[keys.length - 1].frame;
  53290. }
  53291. //to and from cannot be the same key
  53292. if (from === to) {
  53293. if (from > keys[0].frame) {
  53294. from--;
  53295. }
  53296. else if (to < keys[keys.length - 1].frame) {
  53297. to++;
  53298. }
  53299. }
  53300. // Compute ratio
  53301. var range = to - from;
  53302. var offsetValue;
  53303. // ratio represents the frame delta between from and to
  53304. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  53305. var highLimitValue = 0;
  53306. this._previousDelay = delay;
  53307. this._previousRatio = ratio;
  53308. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  53309. returnValue = false;
  53310. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  53311. }
  53312. else {
  53313. // Get max value if required
  53314. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  53315. var keyOffset = to.toString() + from.toString();
  53316. if (!this._offsetsCache[keyOffset]) {
  53317. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  53318. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  53319. switch (this._animation.dataType) {
  53320. // Float
  53321. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  53322. this._offsetsCache[keyOffset] = toValue - fromValue;
  53323. break;
  53324. // Quaternion
  53325. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  53326. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53327. break;
  53328. // Vector3
  53329. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  53330. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53331. // Vector2
  53332. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  53333. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53334. // Size
  53335. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  53336. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53337. // Color3
  53338. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  53339. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53340. default:
  53341. break;
  53342. }
  53343. this._highLimitsCache[keyOffset] = toValue;
  53344. }
  53345. highLimitValue = this._highLimitsCache[keyOffset];
  53346. offsetValue = this._offsetsCache[keyOffset];
  53347. }
  53348. }
  53349. if (offsetValue === undefined) {
  53350. switch (this._animation.dataType) {
  53351. // Float
  53352. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  53353. offsetValue = 0;
  53354. break;
  53355. // Quaternion
  53356. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  53357. offsetValue = _staticOffsetValueQuaternion;
  53358. break;
  53359. // Vector3
  53360. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  53361. offsetValue = _staticOffsetValueVector3;
  53362. break;
  53363. // Vector2
  53364. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  53365. offsetValue = _staticOffsetValueVector2;
  53366. break;
  53367. // Size
  53368. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  53369. offsetValue = _staticOffsetValueSize;
  53370. break;
  53371. // Color3
  53372. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  53373. offsetValue = _staticOffsetValueColor3;
  53374. }
  53375. }
  53376. // Compute value
  53377. var repeatCount = (ratio / range) >> 0;
  53378. var currentFrame = returnValue ? from + ratio % range : to;
  53379. // Need to normalize?
  53380. if (this._host && this._host.syncRoot) {
  53381. var syncRoot = this._host.syncRoot;
  53382. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  53383. currentFrame = from + (to - from) * hostNormalizedFrame;
  53384. }
  53385. // Reset events if looping
  53386. var events = this._events;
  53387. if (range > 0 && this.currentFrame > currentFrame ||
  53388. range < 0 && this.currentFrame < currentFrame) {
  53389. // Need to reset animation events
  53390. for (var index = 0; index < events.length; index++) {
  53391. if (!events[index].onlyOnce) {
  53392. // reset event, the animation is looping
  53393. events[index].isDone = false;
  53394. }
  53395. }
  53396. }
  53397. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  53398. // Set value
  53399. this.setValue(currentValue, weight);
  53400. // Check events
  53401. for (var index = 0; index < events.length; index++) {
  53402. // Make sure current frame has passed event frame and that event frame is within the current range
  53403. // Also, handle both forward and reverse animations
  53404. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  53405. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  53406. var event = events[index];
  53407. if (!event.isDone) {
  53408. // If event should be done only once, remove it.
  53409. if (event.onlyOnce) {
  53410. events.splice(index, 1);
  53411. index--;
  53412. }
  53413. event.isDone = true;
  53414. event.action(currentFrame);
  53415. } // Don't do anything if the event has already be done.
  53416. }
  53417. }
  53418. if (!returnValue) {
  53419. this._stopped = true;
  53420. }
  53421. return returnValue;
  53422. };
  53423. return RuntimeAnimation;
  53424. }());
  53425. BABYLON.RuntimeAnimation = RuntimeAnimation;
  53426. })(BABYLON || (BABYLON = {}));
  53427. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  53428. var BABYLON;
  53429. (function (BABYLON) {
  53430. /**
  53431. * Class used to store an actual running animation
  53432. */
  53433. var Animatable = /** @class */ (function () {
  53434. /**
  53435. * Creates a new Animatable
  53436. * @param scene defines the hosting scene
  53437. * @param target defines the target object
  53438. * @param fromFrame defines the starting frame number (default is 0)
  53439. * @param toFrame defines the ending frame number (default is 100)
  53440. * @param loopAnimation defines if the animation must loop (default is false)
  53441. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  53442. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  53443. * @param animations defines a group of animation to add to the new Animatable
  53444. */
  53445. function Animatable(scene,
  53446. /** defines the target object */
  53447. target,
  53448. /** defines the starting frame number (default is 0) */
  53449. fromFrame,
  53450. /** defines the ending frame number (default is 100) */
  53451. toFrame,
  53452. /** defines if the animation must loop (default is false) */
  53453. loopAnimation, speedRatio,
  53454. /** defines a callback to call when animation ends if it is not looping */
  53455. onAnimationEnd, animations) {
  53456. if (fromFrame === void 0) { fromFrame = 0; }
  53457. if (toFrame === void 0) { toFrame = 100; }
  53458. if (loopAnimation === void 0) { loopAnimation = false; }
  53459. if (speedRatio === void 0) { speedRatio = 1.0; }
  53460. this.target = target;
  53461. this.fromFrame = fromFrame;
  53462. this.toFrame = toFrame;
  53463. this.loopAnimation = loopAnimation;
  53464. this.onAnimationEnd = onAnimationEnd;
  53465. this._localDelayOffset = null;
  53466. this._pausedDelay = null;
  53467. this._runtimeAnimations = new Array();
  53468. this._paused = false;
  53469. this._speedRatio = 1;
  53470. this._weight = -1.0;
  53471. /**
  53472. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  53473. * This will only apply for non looping animation (default is true)
  53474. */
  53475. this.disposeOnEnd = true;
  53476. /**
  53477. * Gets a boolean indicating if the animation has started
  53478. */
  53479. this.animationStarted = false;
  53480. /**
  53481. * Observer raised when the animation ends
  53482. */
  53483. this.onAnimationEndObservable = new BABYLON.Observable();
  53484. this._scene = scene;
  53485. if (animations) {
  53486. this.appendAnimations(target, animations);
  53487. }
  53488. this._speedRatio = speedRatio;
  53489. scene._activeAnimatables.push(this);
  53490. }
  53491. Object.defineProperty(Animatable.prototype, "syncRoot", {
  53492. /**
  53493. * Gets the root Animatable used to synchronize and normalize animations
  53494. */
  53495. get: function () {
  53496. return this._syncRoot;
  53497. },
  53498. enumerable: true,
  53499. configurable: true
  53500. });
  53501. Object.defineProperty(Animatable.prototype, "masterFrame", {
  53502. /**
  53503. * Gets the current frame of the first RuntimeAnimation
  53504. * Used to synchronize Animatables
  53505. */
  53506. get: function () {
  53507. if (this._runtimeAnimations.length === 0) {
  53508. return 0;
  53509. }
  53510. return this._runtimeAnimations[0].currentFrame;
  53511. },
  53512. enumerable: true,
  53513. configurable: true
  53514. });
  53515. Object.defineProperty(Animatable.prototype, "weight", {
  53516. /**
  53517. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  53518. */
  53519. get: function () {
  53520. return this._weight;
  53521. },
  53522. set: function (value) {
  53523. if (value === -1) { // -1 is ok and means no weight
  53524. this._weight = -1;
  53525. return;
  53526. }
  53527. // Else weight must be in [0, 1] range
  53528. this._weight = Math.min(Math.max(value, 0), 1.0);
  53529. },
  53530. enumerable: true,
  53531. configurable: true
  53532. });
  53533. Object.defineProperty(Animatable.prototype, "speedRatio", {
  53534. /**
  53535. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  53536. */
  53537. get: function () {
  53538. return this._speedRatio;
  53539. },
  53540. set: function (value) {
  53541. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  53542. var animation = this._runtimeAnimations[index];
  53543. animation._prepareForSpeedRatioChange(value);
  53544. }
  53545. this._speedRatio = value;
  53546. },
  53547. enumerable: true,
  53548. configurable: true
  53549. });
  53550. // Methods
  53551. /**
  53552. * Synchronize and normalize current Animatable with a source Animatable
  53553. * This is useful when using animation weights and when animations are not of the same length
  53554. * @param root defines the root Animatable to synchronize with
  53555. * @returns the current Animatable
  53556. */
  53557. Animatable.prototype.syncWith = function (root) {
  53558. this._syncRoot = root;
  53559. if (root) {
  53560. // Make sure this animatable will animate after the root
  53561. var index = this._scene._activeAnimatables.indexOf(this);
  53562. if (index > -1) {
  53563. this._scene._activeAnimatables.splice(index, 1);
  53564. this._scene._activeAnimatables.push(this);
  53565. }
  53566. }
  53567. return this;
  53568. };
  53569. /**
  53570. * Gets the list of runtime animations
  53571. * @returns an array of RuntimeAnimation
  53572. */
  53573. Animatable.prototype.getAnimations = function () {
  53574. return this._runtimeAnimations;
  53575. };
  53576. /**
  53577. * Adds more animations to the current animatable
  53578. * @param target defines the target of the animations
  53579. * @param animations defines the new animations to add
  53580. */
  53581. Animatable.prototype.appendAnimations = function (target, animations) {
  53582. for (var index = 0; index < animations.length; index++) {
  53583. var animation = animations[index];
  53584. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  53585. }
  53586. };
  53587. /**
  53588. * Gets the source animation for a specific property
  53589. * @param property defines the propertyu to look for
  53590. * @returns null or the source animation for the given property
  53591. */
  53592. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  53593. var runtimeAnimations = this._runtimeAnimations;
  53594. for (var index = 0; index < runtimeAnimations.length; index++) {
  53595. if (runtimeAnimations[index].animation.targetProperty === property) {
  53596. return runtimeAnimations[index].animation;
  53597. }
  53598. }
  53599. return null;
  53600. };
  53601. /**
  53602. * Gets the runtime animation for a specific property
  53603. * @param property defines the propertyu to look for
  53604. * @returns null or the runtime animation for the given property
  53605. */
  53606. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  53607. var runtimeAnimations = this._runtimeAnimations;
  53608. for (var index = 0; index < runtimeAnimations.length; index++) {
  53609. if (runtimeAnimations[index].animation.targetProperty === property) {
  53610. return runtimeAnimations[index];
  53611. }
  53612. }
  53613. return null;
  53614. };
  53615. /**
  53616. * Resets the animatable to its original state
  53617. */
  53618. Animatable.prototype.reset = function () {
  53619. var runtimeAnimations = this._runtimeAnimations;
  53620. for (var index = 0; index < runtimeAnimations.length; index++) {
  53621. runtimeAnimations[index].reset(true);
  53622. }
  53623. this._localDelayOffset = null;
  53624. this._pausedDelay = null;
  53625. };
  53626. /**
  53627. * Allows the animatable to blend with current running animations
  53628. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  53629. * @param blendingSpeed defines the blending speed to use
  53630. */
  53631. Animatable.prototype.enableBlending = function (blendingSpeed) {
  53632. var runtimeAnimations = this._runtimeAnimations;
  53633. for (var index = 0; index < runtimeAnimations.length; index++) {
  53634. runtimeAnimations[index].animation.enableBlending = true;
  53635. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  53636. }
  53637. };
  53638. /**
  53639. * Disable animation blending
  53640. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  53641. */
  53642. Animatable.prototype.disableBlending = function () {
  53643. var runtimeAnimations = this._runtimeAnimations;
  53644. for (var index = 0; index < runtimeAnimations.length; index++) {
  53645. runtimeAnimations[index].animation.enableBlending = false;
  53646. }
  53647. };
  53648. /**
  53649. * Jump directly to a given frame
  53650. * @param frame defines the frame to jump to
  53651. */
  53652. Animatable.prototype.goToFrame = function (frame) {
  53653. var runtimeAnimations = this._runtimeAnimations;
  53654. if (runtimeAnimations[0]) {
  53655. var fps = runtimeAnimations[0].animation.framePerSecond;
  53656. var currentFrame = runtimeAnimations[0].currentFrame;
  53657. var adjustTime = frame - currentFrame;
  53658. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  53659. if (this._localDelayOffset === null) {
  53660. this._localDelayOffset = 0;
  53661. }
  53662. this._localDelayOffset -= delay;
  53663. }
  53664. for (var index = 0; index < runtimeAnimations.length; index++) {
  53665. runtimeAnimations[index].goToFrame(frame);
  53666. }
  53667. };
  53668. /**
  53669. * Pause the animation
  53670. */
  53671. Animatable.prototype.pause = function () {
  53672. if (this._paused) {
  53673. return;
  53674. }
  53675. this._paused = true;
  53676. };
  53677. /**
  53678. * Restart the animation
  53679. */
  53680. Animatable.prototype.restart = function () {
  53681. this._paused = false;
  53682. };
  53683. Animatable.prototype._raiseOnAnimationEnd = function () {
  53684. if (this.onAnimationEnd) {
  53685. this.onAnimationEnd();
  53686. }
  53687. this.onAnimationEndObservable.notifyObservers(this);
  53688. };
  53689. /**
  53690. * Stop and delete the current animation
  53691. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  53692. * @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)
  53693. */
  53694. Animatable.prototype.stop = function (animationName, targetMask) {
  53695. if (animationName || targetMask) {
  53696. var idx = this._scene._activeAnimatables.indexOf(this);
  53697. if (idx > -1) {
  53698. var runtimeAnimations = this._runtimeAnimations;
  53699. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  53700. var runtimeAnimation = runtimeAnimations[index];
  53701. if (animationName && runtimeAnimation.animation.name != animationName) {
  53702. continue;
  53703. }
  53704. if (targetMask && !targetMask(runtimeAnimation.target)) {
  53705. continue;
  53706. }
  53707. runtimeAnimation.dispose();
  53708. runtimeAnimations.splice(index, 1);
  53709. }
  53710. if (runtimeAnimations.length == 0) {
  53711. this._scene._activeAnimatables.splice(idx, 1);
  53712. this._raiseOnAnimationEnd();
  53713. }
  53714. }
  53715. }
  53716. else {
  53717. var index = this._scene._activeAnimatables.indexOf(this);
  53718. if (index > -1) {
  53719. this._scene._activeAnimatables.splice(index, 1);
  53720. var runtimeAnimations = this._runtimeAnimations;
  53721. for (var index = 0; index < runtimeAnimations.length; index++) {
  53722. runtimeAnimations[index].dispose();
  53723. }
  53724. this._raiseOnAnimationEnd();
  53725. }
  53726. }
  53727. };
  53728. /**
  53729. * Wait asynchronously for the animation to end
  53730. * @returns a promise which will be fullfilled when the animation ends
  53731. */
  53732. Animatable.prototype.waitAsync = function () {
  53733. var _this = this;
  53734. return new Promise(function (resolve, reject) {
  53735. _this.onAnimationEndObservable.add(function () {
  53736. resolve(_this);
  53737. }, undefined, undefined, _this, true);
  53738. });
  53739. };
  53740. /** @hidden */
  53741. Animatable.prototype._animate = function (delay) {
  53742. if (this._paused) {
  53743. this.animationStarted = false;
  53744. if (this._pausedDelay === null) {
  53745. this._pausedDelay = delay;
  53746. }
  53747. return true;
  53748. }
  53749. if (this._localDelayOffset === null) {
  53750. this._localDelayOffset = delay;
  53751. this._pausedDelay = null;
  53752. }
  53753. else if (this._pausedDelay !== null) {
  53754. this._localDelayOffset += delay - this._pausedDelay;
  53755. this._pausedDelay = null;
  53756. }
  53757. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  53758. return true;
  53759. }
  53760. // Animating
  53761. var running = false;
  53762. var runtimeAnimations = this._runtimeAnimations;
  53763. var index;
  53764. for (index = 0; index < runtimeAnimations.length; index++) {
  53765. var animation = runtimeAnimations[index];
  53766. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  53767. running = running || isRunning;
  53768. }
  53769. this.animationStarted = running;
  53770. if (!running) {
  53771. if (this.disposeOnEnd) {
  53772. // Remove from active animatables
  53773. index = this._scene._activeAnimatables.indexOf(this);
  53774. this._scene._activeAnimatables.splice(index, 1);
  53775. // Dispose all runtime animations
  53776. for (index = 0; index < runtimeAnimations.length; index++) {
  53777. runtimeAnimations[index].dispose();
  53778. }
  53779. }
  53780. this._raiseOnAnimationEnd();
  53781. if (this.disposeOnEnd) {
  53782. this.onAnimationEnd = null;
  53783. this.onAnimationEndObservable.clear();
  53784. }
  53785. }
  53786. return running;
  53787. };
  53788. return Animatable;
  53789. }());
  53790. BABYLON.Animatable = Animatable;
  53791. })(BABYLON || (BABYLON = {}));
  53792. //# sourceMappingURL=babylon.animatable.js.map
  53793. var BABYLON;
  53794. (function (BABYLON) {
  53795. /**
  53796. * Base class used for every default easing function.
  53797. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53798. */
  53799. var EasingFunction = /** @class */ (function () {
  53800. function EasingFunction() {
  53801. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  53802. }
  53803. /**
  53804. * Sets the easing mode of the current function.
  53805. * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT)
  53806. */
  53807. EasingFunction.prototype.setEasingMode = function (easingMode) {
  53808. var n = Math.min(Math.max(easingMode, 0), 2);
  53809. this._easingMode = n;
  53810. };
  53811. /**
  53812. * Gets the current easing mode.
  53813. * @returns the easing mode
  53814. */
  53815. EasingFunction.prototype.getEasingMode = function () {
  53816. return this._easingMode;
  53817. };
  53818. /**
  53819. * @hidden
  53820. */
  53821. EasingFunction.prototype.easeInCore = function (gradient) {
  53822. throw new Error('You must implement this method');
  53823. };
  53824. /**
  53825. * Given an input gradient between 0 and 1, this returns the corrseponding value
  53826. * of the easing function.
  53827. * @param gradient Defines the value between 0 and 1 we want the easing value for
  53828. * @returns the corresponding value on the curve defined by the easing function
  53829. */
  53830. EasingFunction.prototype.ease = function (gradient) {
  53831. switch (this._easingMode) {
  53832. case EasingFunction.EASINGMODE_EASEIN:
  53833. return this.easeInCore(gradient);
  53834. case EasingFunction.EASINGMODE_EASEOUT:
  53835. return (1 - this.easeInCore(1 - gradient));
  53836. }
  53837. if (gradient >= 0.5) {
  53838. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  53839. }
  53840. return (this.easeInCore(gradient * 2) * 0.5);
  53841. };
  53842. /**
  53843. * Interpolation follows the mathematical formula associated with the easing function.
  53844. */
  53845. EasingFunction.EASINGMODE_EASEIN = 0;
  53846. /**
  53847. * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function.
  53848. */
  53849. EasingFunction.EASINGMODE_EASEOUT = 1;
  53850. /**
  53851. * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half.
  53852. */
  53853. EasingFunction.EASINGMODE_EASEINOUT = 2;
  53854. return EasingFunction;
  53855. }());
  53856. BABYLON.EasingFunction = EasingFunction;
  53857. /**
  53858. * Easing function with a circle shape (see link below).
  53859. * @see https://easings.net/#easeInCirc
  53860. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53861. */
  53862. var CircleEase = /** @class */ (function (_super) {
  53863. __extends(CircleEase, _super);
  53864. function CircleEase() {
  53865. return _super !== null && _super.apply(this, arguments) || this;
  53866. }
  53867. /** @hidden */
  53868. CircleEase.prototype.easeInCore = function (gradient) {
  53869. gradient = Math.max(0, Math.min(1, gradient));
  53870. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  53871. };
  53872. return CircleEase;
  53873. }(EasingFunction));
  53874. BABYLON.CircleEase = CircleEase;
  53875. /**
  53876. * Easing function with a ease back shape (see link below).
  53877. * @see https://easings.net/#easeInBack
  53878. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53879. */
  53880. var BackEase = /** @class */ (function (_super) {
  53881. __extends(BackEase, _super);
  53882. /**
  53883. * Instantiates a back ease easing
  53884. * @see https://easings.net/#easeInBack
  53885. * @param amplitude Defines the amplitude of the function
  53886. */
  53887. function BackEase(
  53888. /** Defines the amplitude of the function */
  53889. amplitude) {
  53890. if (amplitude === void 0) { amplitude = 1; }
  53891. var _this = _super.call(this) || this;
  53892. _this.amplitude = amplitude;
  53893. return _this;
  53894. }
  53895. /** @hidden */
  53896. BackEase.prototype.easeInCore = function (gradient) {
  53897. var num = Math.max(0, this.amplitude);
  53898. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  53899. };
  53900. return BackEase;
  53901. }(EasingFunction));
  53902. BABYLON.BackEase = BackEase;
  53903. /**
  53904. * Easing function with a bouncing shape (see link below).
  53905. * @see https://easings.net/#easeInBounce
  53906. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53907. */
  53908. var BounceEase = /** @class */ (function (_super) {
  53909. __extends(BounceEase, _super);
  53910. /**
  53911. * Instantiates a bounce easing
  53912. * @see https://easings.net/#easeInBounce
  53913. * @param bounces Defines the number of bounces
  53914. * @param bounciness Defines the amplitude of the bounce
  53915. */
  53916. function BounceEase(
  53917. /** Defines the number of bounces */
  53918. bounces,
  53919. /** Defines the amplitude of the bounce */
  53920. bounciness) {
  53921. if (bounces === void 0) { bounces = 3; }
  53922. if (bounciness === void 0) { bounciness = 2; }
  53923. var _this = _super.call(this) || this;
  53924. _this.bounces = bounces;
  53925. _this.bounciness = bounciness;
  53926. return _this;
  53927. }
  53928. /** @hidden */
  53929. BounceEase.prototype.easeInCore = function (gradient) {
  53930. var y = Math.max(0.0, this.bounces);
  53931. var bounciness = this.bounciness;
  53932. if (bounciness <= 1.0) {
  53933. bounciness = 1.001;
  53934. }
  53935. var num9 = Math.pow(bounciness, y);
  53936. var num5 = 1.0 - bounciness;
  53937. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  53938. var num15 = gradient * num4;
  53939. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  53940. var num3 = Math.floor(num65);
  53941. var num13 = num3 + 1.0;
  53942. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  53943. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  53944. var num7 = (num8 + num12) * 0.5;
  53945. var num6 = gradient - num7;
  53946. var num2 = num7 - num8;
  53947. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  53948. };
  53949. return BounceEase;
  53950. }(EasingFunction));
  53951. BABYLON.BounceEase = BounceEase;
  53952. /**
  53953. * Easing function with a power of 3 shape (see link below).
  53954. * @see https://easings.net/#easeInCubic
  53955. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53956. */
  53957. var CubicEase = /** @class */ (function (_super) {
  53958. __extends(CubicEase, _super);
  53959. function CubicEase() {
  53960. return _super !== null && _super.apply(this, arguments) || this;
  53961. }
  53962. /** @hidden */
  53963. CubicEase.prototype.easeInCore = function (gradient) {
  53964. return (gradient * gradient * gradient);
  53965. };
  53966. return CubicEase;
  53967. }(EasingFunction));
  53968. BABYLON.CubicEase = CubicEase;
  53969. /**
  53970. * Easing function with an elastic shape (see link below).
  53971. * @see https://easings.net/#easeInElastic
  53972. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53973. */
  53974. var ElasticEase = /** @class */ (function (_super) {
  53975. __extends(ElasticEase, _super);
  53976. /**
  53977. * Instantiates an elastic easing function
  53978. * @see https://easings.net/#easeInElastic
  53979. * @param oscillations Defines the number of oscillations
  53980. * @param springiness Defines the amplitude of the oscillations
  53981. */
  53982. function ElasticEase(
  53983. /** Defines the number of oscillations*/
  53984. oscillations,
  53985. /** Defines the amplitude of the oscillations*/
  53986. springiness) {
  53987. if (oscillations === void 0) { oscillations = 3; }
  53988. if (springiness === void 0) { springiness = 3; }
  53989. var _this = _super.call(this) || this;
  53990. _this.oscillations = oscillations;
  53991. _this.springiness = springiness;
  53992. return _this;
  53993. }
  53994. /** @hidden */
  53995. ElasticEase.prototype.easeInCore = function (gradient) {
  53996. var num2;
  53997. var num3 = Math.max(0.0, this.oscillations);
  53998. var num = Math.max(0.0, this.springiness);
  53999. if (num == 0) {
  54000. num2 = gradient;
  54001. }
  54002. else {
  54003. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  54004. }
  54005. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  54006. };
  54007. return ElasticEase;
  54008. }(EasingFunction));
  54009. BABYLON.ElasticEase = ElasticEase;
  54010. /**
  54011. * Easing function with an exponential shape (see link below).
  54012. * @see https://easings.net/#easeInExpo
  54013. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54014. */
  54015. var ExponentialEase = /** @class */ (function (_super) {
  54016. __extends(ExponentialEase, _super);
  54017. /**
  54018. * Instantiates an exponential easing function
  54019. * @see https://easings.net/#easeInExpo
  54020. * @param exponent Defines the exponent of the function
  54021. */
  54022. function ExponentialEase(
  54023. /** Defines the exponent of the function */
  54024. exponent) {
  54025. if (exponent === void 0) { exponent = 2; }
  54026. var _this = _super.call(this) || this;
  54027. _this.exponent = exponent;
  54028. return _this;
  54029. }
  54030. /** @hidden */
  54031. ExponentialEase.prototype.easeInCore = function (gradient) {
  54032. if (this.exponent <= 0) {
  54033. return gradient;
  54034. }
  54035. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  54036. };
  54037. return ExponentialEase;
  54038. }(EasingFunction));
  54039. BABYLON.ExponentialEase = ExponentialEase;
  54040. /**
  54041. * Easing function with a power shape (see link below).
  54042. * @see https://easings.net/#easeInQuad
  54043. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54044. */
  54045. var PowerEase = /** @class */ (function (_super) {
  54046. __extends(PowerEase, _super);
  54047. /**
  54048. * Instantiates an power base easing function
  54049. * @see https://easings.net/#easeInQuad
  54050. * @param power Defines the power of the function
  54051. */
  54052. function PowerEase(
  54053. /** Defines the power of the function */
  54054. power) {
  54055. if (power === void 0) { power = 2; }
  54056. var _this = _super.call(this) || this;
  54057. _this.power = power;
  54058. return _this;
  54059. }
  54060. /** @hidden */
  54061. PowerEase.prototype.easeInCore = function (gradient) {
  54062. var y = Math.max(0.0, this.power);
  54063. return Math.pow(gradient, y);
  54064. };
  54065. return PowerEase;
  54066. }(EasingFunction));
  54067. BABYLON.PowerEase = PowerEase;
  54068. /**
  54069. * Easing function with a power of 2 shape (see link below).
  54070. * @see https://easings.net/#easeInQuad
  54071. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54072. */
  54073. var QuadraticEase = /** @class */ (function (_super) {
  54074. __extends(QuadraticEase, _super);
  54075. function QuadraticEase() {
  54076. return _super !== null && _super.apply(this, arguments) || this;
  54077. }
  54078. /** @hidden */
  54079. QuadraticEase.prototype.easeInCore = function (gradient) {
  54080. return (gradient * gradient);
  54081. };
  54082. return QuadraticEase;
  54083. }(EasingFunction));
  54084. BABYLON.QuadraticEase = QuadraticEase;
  54085. /**
  54086. * Easing function with a power of 4 shape (see link below).
  54087. * @see https://easings.net/#easeInQuart
  54088. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54089. */
  54090. var QuarticEase = /** @class */ (function (_super) {
  54091. __extends(QuarticEase, _super);
  54092. function QuarticEase() {
  54093. return _super !== null && _super.apply(this, arguments) || this;
  54094. }
  54095. /** @hidden */
  54096. QuarticEase.prototype.easeInCore = function (gradient) {
  54097. return (gradient * gradient * gradient * gradient);
  54098. };
  54099. return QuarticEase;
  54100. }(EasingFunction));
  54101. BABYLON.QuarticEase = QuarticEase;
  54102. /**
  54103. * Easing function with a power of 5 shape (see link below).
  54104. * @see https://easings.net/#easeInQuint
  54105. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54106. */
  54107. var QuinticEase = /** @class */ (function (_super) {
  54108. __extends(QuinticEase, _super);
  54109. function QuinticEase() {
  54110. return _super !== null && _super.apply(this, arguments) || this;
  54111. }
  54112. /** @hidden */
  54113. QuinticEase.prototype.easeInCore = function (gradient) {
  54114. return (gradient * gradient * gradient * gradient * gradient);
  54115. };
  54116. return QuinticEase;
  54117. }(EasingFunction));
  54118. BABYLON.QuinticEase = QuinticEase;
  54119. /**
  54120. * Easing function with a sin shape (see link below).
  54121. * @see https://easings.net/#easeInSine
  54122. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54123. */
  54124. var SineEase = /** @class */ (function (_super) {
  54125. __extends(SineEase, _super);
  54126. function SineEase() {
  54127. return _super !== null && _super.apply(this, arguments) || this;
  54128. }
  54129. /** @hidden */
  54130. SineEase.prototype.easeInCore = function (gradient) {
  54131. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  54132. };
  54133. return SineEase;
  54134. }(EasingFunction));
  54135. BABYLON.SineEase = SineEase;
  54136. /**
  54137. * Easing function with a bezier shape (see link below).
  54138. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  54139. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54140. */
  54141. var BezierCurveEase = /** @class */ (function (_super) {
  54142. __extends(BezierCurveEase, _super);
  54143. /**
  54144. * Instantiates a bezier function
  54145. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  54146. * @param x1 Defines the x component of the start tangent in the bezier curve
  54147. * @param y1 Defines the y component of the start tangent in the bezier curve
  54148. * @param x2 Defines the x component of the end tangent in the bezier curve
  54149. * @param y2 Defines the y component of the end tangent in the bezier curve
  54150. */
  54151. function BezierCurveEase(
  54152. /** Defines the x component of the start tangent in the bezier curve */
  54153. x1,
  54154. /** Defines the y component of the start tangent in the bezier curve */
  54155. y1,
  54156. /** Defines the x component of the end tangent in the bezier curve */
  54157. x2,
  54158. /** Defines the y component of the end tangent in the bezier curve */
  54159. y2) {
  54160. if (x1 === void 0) { x1 = 0; }
  54161. if (y1 === void 0) { y1 = 0; }
  54162. if (x2 === void 0) { x2 = 1; }
  54163. if (y2 === void 0) { y2 = 1; }
  54164. var _this = _super.call(this) || this;
  54165. _this.x1 = x1;
  54166. _this.y1 = y1;
  54167. _this.x2 = x2;
  54168. _this.y2 = y2;
  54169. return _this;
  54170. }
  54171. /** @hidden */
  54172. BezierCurveEase.prototype.easeInCore = function (gradient) {
  54173. return BABYLON.BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  54174. };
  54175. return BezierCurveEase;
  54176. }(EasingFunction));
  54177. BABYLON.BezierCurveEase = BezierCurveEase;
  54178. })(BABYLON || (BABYLON = {}));
  54179. //# sourceMappingURL=babylon.easing.js.map
  54180. var BABYLON;
  54181. (function (BABYLON) {
  54182. /**
  54183. * A Condition applied to an Action
  54184. */
  54185. var Condition = /** @class */ (function () {
  54186. /**
  54187. * Creates a new Condition
  54188. * @param actionManager the manager of the action the condition is applied to
  54189. */
  54190. function Condition(actionManager) {
  54191. this._actionManager = actionManager;
  54192. }
  54193. /**
  54194. * Check if the current condition is valid
  54195. * @returns a boolean
  54196. */
  54197. Condition.prototype.isValid = function () {
  54198. return true;
  54199. };
  54200. /**
  54201. * Internal only
  54202. * @hidden
  54203. */
  54204. Condition.prototype._getProperty = function (propertyPath) {
  54205. return this._actionManager._getProperty(propertyPath);
  54206. };
  54207. /**
  54208. * Internal only
  54209. * @hidden
  54210. */
  54211. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  54212. return this._actionManager._getEffectiveTarget(target, propertyPath);
  54213. };
  54214. /**
  54215. * Serialize placeholder for child classes
  54216. * @returns the serialized object
  54217. */
  54218. Condition.prototype.serialize = function () {
  54219. };
  54220. /**
  54221. * Internal only
  54222. * @hidden
  54223. */
  54224. Condition.prototype._serialize = function (serializedCondition) {
  54225. return {
  54226. type: 2,
  54227. children: [],
  54228. name: serializedCondition.name,
  54229. properties: serializedCondition.properties
  54230. };
  54231. };
  54232. return Condition;
  54233. }());
  54234. BABYLON.Condition = Condition;
  54235. /**
  54236. * Defines specific conditional operators as extensions of Condition
  54237. */
  54238. var ValueCondition = /** @class */ (function (_super) {
  54239. __extends(ValueCondition, _super);
  54240. /**
  54241. * Creates a new ValueCondition
  54242. * @param actionManager manager for the action the condition applies to
  54243. * @param target for the action
  54244. * @param propertyPath path to specify the property of the target the conditional operator uses
  54245. * @param value the value compared by the conditional operator against the current value of the property
  54246. * @param operator the conditional operator, default ValueCondition.IsEqual
  54247. */
  54248. function ValueCondition(actionManager, target,
  54249. /** path to specify the property of the target the conditional operator uses */
  54250. propertyPath,
  54251. /** the value compared by the conditional operator against the current value of the property */
  54252. value,
  54253. /** the conditional operator, default ValueCondition.IsEqual */
  54254. operator) {
  54255. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  54256. var _this = _super.call(this, actionManager) || this;
  54257. _this.propertyPath = propertyPath;
  54258. _this.value = value;
  54259. _this.operator = operator;
  54260. _this._target = target;
  54261. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  54262. _this._property = _this._getProperty(_this.propertyPath);
  54263. return _this;
  54264. }
  54265. Object.defineProperty(ValueCondition, "IsEqual", {
  54266. /**
  54267. * returns the number for IsEqual
  54268. */
  54269. get: function () {
  54270. return ValueCondition._IsEqual;
  54271. },
  54272. enumerable: true,
  54273. configurable: true
  54274. });
  54275. Object.defineProperty(ValueCondition, "IsDifferent", {
  54276. /**
  54277. * Returns the number for IsDifferent
  54278. */
  54279. get: function () {
  54280. return ValueCondition._IsDifferent;
  54281. },
  54282. enumerable: true,
  54283. configurable: true
  54284. });
  54285. Object.defineProperty(ValueCondition, "IsGreater", {
  54286. /**
  54287. * Returns the number for IsGreater
  54288. */
  54289. get: function () {
  54290. return ValueCondition._IsGreater;
  54291. },
  54292. enumerable: true,
  54293. configurable: true
  54294. });
  54295. Object.defineProperty(ValueCondition, "IsLesser", {
  54296. /**
  54297. * Returns the number for IsLesser
  54298. */
  54299. get: function () {
  54300. return ValueCondition._IsLesser;
  54301. },
  54302. enumerable: true,
  54303. configurable: true
  54304. });
  54305. /**
  54306. * Compares the given value with the property value for the specified conditional operator
  54307. * @returns the result of the comparison
  54308. */
  54309. ValueCondition.prototype.isValid = function () {
  54310. switch (this.operator) {
  54311. case ValueCondition.IsGreater:
  54312. return this._effectiveTarget[this._property] > this.value;
  54313. case ValueCondition.IsLesser:
  54314. return this._effectiveTarget[this._property] < this.value;
  54315. case ValueCondition.IsEqual:
  54316. case ValueCondition.IsDifferent:
  54317. var check;
  54318. if (this.value.equals) {
  54319. check = this.value.equals(this._effectiveTarget[this._property]);
  54320. }
  54321. else {
  54322. check = this.value === this._effectiveTarget[this._property];
  54323. }
  54324. return this.operator === ValueCondition.IsEqual ? check : !check;
  54325. }
  54326. return false;
  54327. };
  54328. /**
  54329. * Serialize the ValueCondition into a JSON compatible object
  54330. * @returns serialization object
  54331. */
  54332. ValueCondition.prototype.serialize = function () {
  54333. return this._serialize({
  54334. name: "ValueCondition",
  54335. properties: [
  54336. BABYLON.Action._GetTargetProperty(this._target),
  54337. { name: "propertyPath", value: this.propertyPath },
  54338. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54339. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  54340. ]
  54341. });
  54342. };
  54343. /**
  54344. * Gets the name of the conditional operator for the ValueCondition
  54345. * @param operator the conditional operator
  54346. * @returns the name
  54347. */
  54348. ValueCondition.GetOperatorName = function (operator) {
  54349. switch (operator) {
  54350. case ValueCondition._IsEqual: return "IsEqual";
  54351. case ValueCondition._IsDifferent: return "IsDifferent";
  54352. case ValueCondition._IsGreater: return "IsGreater";
  54353. case ValueCondition._IsLesser: return "IsLesser";
  54354. default: return "";
  54355. }
  54356. };
  54357. /**
  54358. * Internal only
  54359. * @hidden
  54360. */
  54361. ValueCondition._IsEqual = 0;
  54362. /**
  54363. * Internal only
  54364. * @hidden
  54365. */
  54366. ValueCondition._IsDifferent = 1;
  54367. /**
  54368. * Internal only
  54369. * @hidden
  54370. */
  54371. ValueCondition._IsGreater = 2;
  54372. /**
  54373. * Internal only
  54374. * @hidden
  54375. */
  54376. ValueCondition._IsLesser = 3;
  54377. return ValueCondition;
  54378. }(Condition));
  54379. BABYLON.ValueCondition = ValueCondition;
  54380. /**
  54381. * Defines a predicate condition as an extension of Condition
  54382. */
  54383. var PredicateCondition = /** @class */ (function (_super) {
  54384. __extends(PredicateCondition, _super);
  54385. /**
  54386. * Creates a new PredicateCondition
  54387. * @param actionManager manager for the action the condition applies to
  54388. * @param predicate defines the predicate function used to validate the condition
  54389. */
  54390. function PredicateCondition(actionManager,
  54391. /** defines the predicate function used to validate the condition */
  54392. predicate) {
  54393. var _this = _super.call(this, actionManager) || this;
  54394. _this.predicate = predicate;
  54395. return _this;
  54396. }
  54397. /**
  54398. * @returns the validity of the predicate condition
  54399. */
  54400. PredicateCondition.prototype.isValid = function () {
  54401. return this.predicate();
  54402. };
  54403. return PredicateCondition;
  54404. }(Condition));
  54405. BABYLON.PredicateCondition = PredicateCondition;
  54406. /**
  54407. * Defines a state condition as an extension of Condition
  54408. */
  54409. var StateCondition = /** @class */ (function (_super) {
  54410. __extends(StateCondition, _super);
  54411. /**
  54412. * Creates a new StateCondition
  54413. * @param actionManager manager for the action the condition applies to
  54414. * @param target of the condition
  54415. * @param value to compare with target state
  54416. */
  54417. function StateCondition(actionManager, target, value) {
  54418. var _this = _super.call(this, actionManager) || this;
  54419. _this.value = value;
  54420. _this._target = target;
  54421. return _this;
  54422. }
  54423. /**
  54424. * @returns the validity of the state
  54425. */
  54426. StateCondition.prototype.isValid = function () {
  54427. return this._target.state === this.value;
  54428. };
  54429. /**
  54430. * Serialize the StateCondition into a JSON compatible object
  54431. * @returns serialization object
  54432. */
  54433. StateCondition.prototype.serialize = function () {
  54434. return this._serialize({
  54435. name: "StateCondition",
  54436. properties: [
  54437. BABYLON.Action._GetTargetProperty(this._target),
  54438. { name: "value", value: this.value }
  54439. ]
  54440. });
  54441. };
  54442. return StateCondition;
  54443. }(Condition));
  54444. BABYLON.StateCondition = StateCondition;
  54445. })(BABYLON || (BABYLON = {}));
  54446. //# sourceMappingURL=babylon.condition.js.map
  54447. var BABYLON;
  54448. (function (BABYLON) {
  54449. /**
  54450. * The action to be carried out following a trigger
  54451. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  54452. */
  54453. var Action = /** @class */ (function () {
  54454. /**
  54455. * Creates a new Action
  54456. * @param triggerOptions the trigger, with or without parameters, for the action
  54457. * @param condition an optional determinant of action
  54458. */
  54459. function Action(
  54460. /** the trigger, with or without parameters, for the action */
  54461. triggerOptions, condition) {
  54462. this.triggerOptions = triggerOptions;
  54463. /**
  54464. * An event triggered prior to action being executed.
  54465. */
  54466. this.onBeforeExecuteObservable = new BABYLON.Observable();
  54467. if (triggerOptions.parameter) {
  54468. this.trigger = triggerOptions.trigger;
  54469. this._triggerParameter = triggerOptions.parameter;
  54470. }
  54471. else if (triggerOptions.trigger) {
  54472. this.trigger = triggerOptions.trigger;
  54473. }
  54474. else {
  54475. this.trigger = triggerOptions;
  54476. }
  54477. this._nextActiveAction = this;
  54478. this._condition = condition;
  54479. }
  54480. /**
  54481. * Internal only
  54482. * @hidden
  54483. */
  54484. Action.prototype._prepare = function () {
  54485. };
  54486. /**
  54487. * Gets the trigger parameters
  54488. * @returns the trigger parameters
  54489. */
  54490. Action.prototype.getTriggerParameter = function () {
  54491. return this._triggerParameter;
  54492. };
  54493. /**
  54494. * Internal only - executes current action event
  54495. * @hidden
  54496. */
  54497. Action.prototype._executeCurrent = function (evt) {
  54498. if (this._nextActiveAction._condition) {
  54499. var condition = this._nextActiveAction._condition;
  54500. var currentRenderId = this._actionManager.getScene().getRenderId();
  54501. // We cache the current evaluation for the current frame
  54502. if (condition._evaluationId === currentRenderId) {
  54503. if (!condition._currentResult) {
  54504. return;
  54505. }
  54506. }
  54507. else {
  54508. condition._evaluationId = currentRenderId;
  54509. if (!condition.isValid()) {
  54510. condition._currentResult = false;
  54511. return;
  54512. }
  54513. condition._currentResult = true;
  54514. }
  54515. }
  54516. this.onBeforeExecuteObservable.notifyObservers(this);
  54517. this._nextActiveAction.execute(evt);
  54518. this.skipToNextActiveAction();
  54519. };
  54520. /**
  54521. * Execute placeholder for child classes
  54522. * @param evt optional action event
  54523. */
  54524. Action.prototype.execute = function (evt) {
  54525. };
  54526. /**
  54527. * Skips to next active action
  54528. */
  54529. Action.prototype.skipToNextActiveAction = function () {
  54530. if (this._nextActiveAction._child) {
  54531. if (!this._nextActiveAction._child._actionManager) {
  54532. this._nextActiveAction._child._actionManager = this._actionManager;
  54533. }
  54534. this._nextActiveAction = this._nextActiveAction._child;
  54535. }
  54536. else {
  54537. this._nextActiveAction = this;
  54538. }
  54539. };
  54540. /**
  54541. * Adds action to chain of actions, may be a DoNothingAction
  54542. * @param action defines the next action to execute
  54543. * @returns The action passed in
  54544. * @see https://www.babylonjs-playground.com/#1T30HR#0
  54545. */
  54546. Action.prototype.then = function (action) {
  54547. this._child = action;
  54548. action._actionManager = this._actionManager;
  54549. action._prepare();
  54550. return action;
  54551. };
  54552. /**
  54553. * Internal only
  54554. * @hidden
  54555. */
  54556. Action.prototype._getProperty = function (propertyPath) {
  54557. return this._actionManager._getProperty(propertyPath);
  54558. };
  54559. /**
  54560. * Internal only
  54561. * @hidden
  54562. */
  54563. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  54564. return this._actionManager._getEffectiveTarget(target, propertyPath);
  54565. };
  54566. /**
  54567. * Serialize placeholder for child classes
  54568. * @param parent of child
  54569. * @returns the serialized object
  54570. */
  54571. Action.prototype.serialize = function (parent) {
  54572. };
  54573. /**
  54574. * Internal only called by serialize
  54575. * @hidden
  54576. */
  54577. Action.prototype._serialize = function (serializedAction, parent) {
  54578. var serializationObject = {
  54579. type: 1,
  54580. children: [],
  54581. name: serializedAction.name,
  54582. properties: serializedAction.properties || []
  54583. };
  54584. // Serialize child
  54585. if (this._child) {
  54586. this._child.serialize(serializationObject);
  54587. }
  54588. // Check if "this" has a condition
  54589. if (this._condition) {
  54590. var serializedCondition = this._condition.serialize();
  54591. serializedCondition.children.push(serializationObject);
  54592. if (parent) {
  54593. parent.children.push(serializedCondition);
  54594. }
  54595. return serializedCondition;
  54596. }
  54597. if (parent) {
  54598. parent.children.push(serializationObject);
  54599. }
  54600. return serializationObject;
  54601. };
  54602. /**
  54603. * Internal only
  54604. * @hidden
  54605. */
  54606. Action._SerializeValueAsString = function (value) {
  54607. if (typeof value === "number") {
  54608. return value.toString();
  54609. }
  54610. if (typeof value === "boolean") {
  54611. return value ? "true" : "false";
  54612. }
  54613. if (value instanceof BABYLON.Vector2) {
  54614. return value.x + ", " + value.y;
  54615. }
  54616. if (value instanceof BABYLON.Vector3) {
  54617. return value.x + ", " + value.y + ", " + value.z;
  54618. }
  54619. if (value instanceof BABYLON.Color3) {
  54620. return value.r + ", " + value.g + ", " + value.b;
  54621. }
  54622. if (value instanceof BABYLON.Color4) {
  54623. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  54624. }
  54625. return value; // string
  54626. };
  54627. /**
  54628. * Internal only
  54629. * @hidden
  54630. */
  54631. Action._GetTargetProperty = function (target) {
  54632. return {
  54633. name: "target",
  54634. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  54635. : target instanceof BABYLON.Light ? "LightProperties"
  54636. : target instanceof BABYLON.Camera ? "CameraProperties"
  54637. : "SceneProperties",
  54638. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  54639. };
  54640. };
  54641. return Action;
  54642. }());
  54643. BABYLON.Action = Action;
  54644. })(BABYLON || (BABYLON = {}));
  54645. //# sourceMappingURL=babylon.action.js.map
  54646. var BABYLON;
  54647. (function (BABYLON) {
  54648. /**
  54649. * ActionEvent is the event being sent when an action is triggered.
  54650. */
  54651. var ActionEvent = /** @class */ (function () {
  54652. /**
  54653. * Creates a new ActionEvent
  54654. * @param source The mesh or sprite that triggered the action
  54655. * @param pointerX The X mouse cursor position at the time of the event
  54656. * @param pointerY The Y mouse cursor position at the time of the event
  54657. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  54658. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  54659. * @param additionalData additional data for the event
  54660. */
  54661. function ActionEvent(
  54662. /** The mesh or sprite that triggered the action */
  54663. source,
  54664. /** The X mouse cursor position at the time of the event */
  54665. pointerX,
  54666. /** The Y mouse cursor position at the time of the event */
  54667. pointerY,
  54668. /** The mesh that is currently pointed at (can be null) */
  54669. meshUnderPointer,
  54670. /** the original (browser) event that triggered the ActionEvent */
  54671. sourceEvent,
  54672. /** additional data for the event */
  54673. additionalData) {
  54674. this.source = source;
  54675. this.pointerX = pointerX;
  54676. this.pointerY = pointerY;
  54677. this.meshUnderPointer = meshUnderPointer;
  54678. this.sourceEvent = sourceEvent;
  54679. this.additionalData = additionalData;
  54680. }
  54681. /**
  54682. * Helper function to auto-create an ActionEvent from a source mesh.
  54683. * @param source The source mesh that triggered the event
  54684. * @param evt The original (browser) event
  54685. * @param additionalData additional data for the event
  54686. * @returns the new ActionEvent
  54687. */
  54688. ActionEvent.CreateNew = function (source, evt, additionalData) {
  54689. var scene = source.getScene();
  54690. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  54691. };
  54692. /**
  54693. * Helper function to auto-create an ActionEvent from a source sprite
  54694. * @param source The source sprite that triggered the event
  54695. * @param scene Scene associated with the sprite
  54696. * @param evt The original (browser) event
  54697. * @param additionalData additional data for the event
  54698. * @returns the new ActionEvent
  54699. */
  54700. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  54701. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  54702. };
  54703. /**
  54704. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  54705. * @param scene the scene where the event occurred
  54706. * @param evt The original (browser) event
  54707. * @returns the new ActionEvent
  54708. */
  54709. ActionEvent.CreateNewFromScene = function (scene, evt) {
  54710. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  54711. };
  54712. /**
  54713. * Helper function to auto-create an ActionEvent from a primitive
  54714. * @param prim defines the target primitive
  54715. * @param pointerPos defines the pointer position
  54716. * @param evt The original (browser) event
  54717. * @param additionalData additional data for the event
  54718. * @returns the new ActionEvent
  54719. */
  54720. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  54721. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  54722. };
  54723. return ActionEvent;
  54724. }());
  54725. BABYLON.ActionEvent = ActionEvent;
  54726. /**
  54727. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  54728. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  54729. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54730. */
  54731. var ActionManager = /** @class */ (function () {
  54732. /**
  54733. * Creates a new action manager
  54734. * @param scene defines the hosting scene
  54735. */
  54736. function ActionManager(scene) {
  54737. // Members
  54738. /** Gets the list of actions */
  54739. this.actions = new Array();
  54740. /** Gets the cursor to use when hovering items */
  54741. this.hoverCursor = '';
  54742. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54743. scene.actionManagers.push(this);
  54744. }
  54745. // Methods
  54746. /**
  54747. * Releases all associated resources
  54748. */
  54749. ActionManager.prototype.dispose = function () {
  54750. var index = this._scene.actionManagers.indexOf(this);
  54751. for (var i = 0; i < this.actions.length; i++) {
  54752. var action = this.actions[i];
  54753. ActionManager.Triggers[action.trigger]--;
  54754. if (ActionManager.Triggers[action.trigger] === 0) {
  54755. delete ActionManager.Triggers[action.trigger];
  54756. }
  54757. }
  54758. if (index > -1) {
  54759. this._scene.actionManagers.splice(index, 1);
  54760. }
  54761. };
  54762. /**
  54763. * Gets hosting scene
  54764. * @returns the hosting scene
  54765. */
  54766. ActionManager.prototype.getScene = function () {
  54767. return this._scene;
  54768. };
  54769. /**
  54770. * Does this action manager handles actions of any of the given triggers
  54771. * @param triggers defines the triggers to be tested
  54772. * @return a boolean indicating whether one (or more) of the triggers is handled
  54773. */
  54774. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  54775. for (var index = 0; index < this.actions.length; index++) {
  54776. var action = this.actions[index];
  54777. if (triggers.indexOf(action.trigger) > -1) {
  54778. return true;
  54779. }
  54780. }
  54781. return false;
  54782. };
  54783. /**
  54784. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  54785. * speed.
  54786. * @param triggerA defines the trigger to be tested
  54787. * @param triggerB defines the trigger to be tested
  54788. * @return a boolean indicating whether one (or more) of the triggers is handled
  54789. */
  54790. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  54791. for (var index = 0; index < this.actions.length; index++) {
  54792. var action = this.actions[index];
  54793. if (triggerA == action.trigger || triggerB == action.trigger) {
  54794. return true;
  54795. }
  54796. }
  54797. return false;
  54798. };
  54799. /**
  54800. * Does this action manager handles actions of a given trigger
  54801. * @param trigger defines the trigger to be tested
  54802. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  54803. * @return whether the trigger is handled
  54804. */
  54805. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  54806. for (var index = 0; index < this.actions.length; index++) {
  54807. var action = this.actions[index];
  54808. if (action.trigger === trigger) {
  54809. if (parameterPredicate) {
  54810. if (parameterPredicate(action.getTriggerParameter())) {
  54811. return true;
  54812. }
  54813. }
  54814. else {
  54815. return true;
  54816. }
  54817. }
  54818. }
  54819. return false;
  54820. };
  54821. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  54822. /**
  54823. * Does this action manager has pointer triggers
  54824. */
  54825. get: function () {
  54826. for (var index = 0; index < this.actions.length; index++) {
  54827. var action = this.actions[index];
  54828. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) {
  54829. return true;
  54830. }
  54831. }
  54832. return false;
  54833. },
  54834. enumerable: true,
  54835. configurable: true
  54836. });
  54837. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  54838. /**
  54839. * Does this action manager has pick triggers
  54840. */
  54841. get: function () {
  54842. for (var index = 0; index < this.actions.length; index++) {
  54843. var action = this.actions[index];
  54844. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) {
  54845. return true;
  54846. }
  54847. }
  54848. return false;
  54849. },
  54850. enumerable: true,
  54851. configurable: true
  54852. });
  54853. Object.defineProperty(ActionManager, "HasTriggers", {
  54854. /**
  54855. * Does exist one action manager with at least one trigger
  54856. **/
  54857. get: function () {
  54858. for (var t in ActionManager.Triggers) {
  54859. if (ActionManager.Triggers.hasOwnProperty(t)) {
  54860. return true;
  54861. }
  54862. }
  54863. return false;
  54864. },
  54865. enumerable: true,
  54866. configurable: true
  54867. });
  54868. Object.defineProperty(ActionManager, "HasPickTriggers", {
  54869. /**
  54870. * Does exist one action manager with at least one pick trigger
  54871. **/
  54872. get: function () {
  54873. for (var t in ActionManager.Triggers) {
  54874. if (ActionManager.Triggers.hasOwnProperty(t)) {
  54875. var t_int = parseInt(t);
  54876. if (t_int >= ActionManager.OnPickTrigger && t_int <= ActionManager.OnPickUpTrigger) {
  54877. return true;
  54878. }
  54879. }
  54880. }
  54881. return false;
  54882. },
  54883. enumerable: true,
  54884. configurable: true
  54885. });
  54886. /**
  54887. * Does exist one action manager that handles actions of a given trigger
  54888. * @param trigger defines the trigger to be tested
  54889. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  54890. **/
  54891. ActionManager.HasSpecificTrigger = function (trigger) {
  54892. for (var t in ActionManager.Triggers) {
  54893. if (ActionManager.Triggers.hasOwnProperty(t)) {
  54894. var t_int = parseInt(t);
  54895. if (t_int === trigger) {
  54896. return true;
  54897. }
  54898. }
  54899. }
  54900. return false;
  54901. };
  54902. /**
  54903. * Registers an action to this action manager
  54904. * @param action defines the action to be registered
  54905. * @return the action amended (prepared) after registration
  54906. */
  54907. ActionManager.prototype.registerAction = function (action) {
  54908. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  54909. if (this.getScene().actionManager !== this) {
  54910. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  54911. return null;
  54912. }
  54913. }
  54914. this.actions.push(action);
  54915. if (ActionManager.Triggers[action.trigger]) {
  54916. ActionManager.Triggers[action.trigger]++;
  54917. }
  54918. else {
  54919. ActionManager.Triggers[action.trigger] = 1;
  54920. }
  54921. action._actionManager = this;
  54922. action._prepare();
  54923. return action;
  54924. };
  54925. /**
  54926. * Unregisters an action to this action manager
  54927. * @param action defines the action to be unregistered
  54928. * @return a boolean indicating whether the action has been unregistered
  54929. */
  54930. ActionManager.prototype.unregisterAction = function (action) {
  54931. var index = this.actions.indexOf(action);
  54932. if (index !== -1) {
  54933. this.actions.splice(index, 1);
  54934. ActionManager.Triggers[action.trigger] -= 1;
  54935. if (ActionManager.Triggers[action.trigger] === 0) {
  54936. delete ActionManager.Triggers[action.trigger];
  54937. }
  54938. delete action._actionManager;
  54939. return true;
  54940. }
  54941. return false;
  54942. };
  54943. /**
  54944. * Process a specific trigger
  54945. * @param trigger defines the trigger to process
  54946. * @param evt defines the event details to be processed
  54947. */
  54948. ActionManager.prototype.processTrigger = function (trigger, evt) {
  54949. for (var index = 0; index < this.actions.length; index++) {
  54950. var action = this.actions[index];
  54951. if (action.trigger === trigger) {
  54952. if (evt) {
  54953. if (trigger === ActionManager.OnKeyUpTrigger
  54954. || trigger === ActionManager.OnKeyDownTrigger) {
  54955. var parameter = action.getTriggerParameter();
  54956. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  54957. if (!parameter.toLowerCase) {
  54958. continue;
  54959. }
  54960. var lowerCase = parameter.toLowerCase();
  54961. if (lowerCase !== evt.sourceEvent.key) {
  54962. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  54963. var actualkey = String.fromCharCode(unicode).toLowerCase();
  54964. if (actualkey !== lowerCase) {
  54965. continue;
  54966. }
  54967. }
  54968. }
  54969. }
  54970. }
  54971. action._executeCurrent(evt);
  54972. }
  54973. }
  54974. };
  54975. /** @hidden */
  54976. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  54977. var properties = propertyPath.split(".");
  54978. for (var index = 0; index < properties.length - 1; index++) {
  54979. target = target[properties[index]];
  54980. }
  54981. return target;
  54982. };
  54983. /** @hidden */
  54984. ActionManager.prototype._getProperty = function (propertyPath) {
  54985. var properties = propertyPath.split(".");
  54986. return properties[properties.length - 1];
  54987. };
  54988. /**
  54989. * Serialize this manager to a JSON object
  54990. * @param name defines the property name to store this manager
  54991. * @returns a JSON representation of this manager
  54992. */
  54993. ActionManager.prototype.serialize = function (name) {
  54994. var root = {
  54995. children: new Array(),
  54996. name: name,
  54997. type: 3,
  54998. properties: new Array() // Empty for root but required
  54999. };
  55000. for (var i = 0; i < this.actions.length; i++) {
  55001. var triggerObject = {
  55002. type: 0,
  55003. children: new Array(),
  55004. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  55005. properties: new Array()
  55006. };
  55007. var triggerOptions = this.actions[i].triggerOptions;
  55008. if (triggerOptions && typeof triggerOptions !== "number") {
  55009. if (triggerOptions.parameter instanceof BABYLON.Node) {
  55010. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  55011. }
  55012. else {
  55013. var parameter = {};
  55014. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  55015. if (triggerOptions.parameter.mesh) {
  55016. parameter._meshId = triggerOptions.parameter.mesh.id;
  55017. }
  55018. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  55019. }
  55020. }
  55021. // Serialize child action, recursively
  55022. this.actions[i].serialize(triggerObject);
  55023. // Add serialized trigger
  55024. root.children.push(triggerObject);
  55025. }
  55026. return root;
  55027. };
  55028. /**
  55029. * Creates a new ActionManager from a JSON data
  55030. * @param parsedActions defines the JSON data to read from
  55031. * @param object defines the hosting mesh
  55032. * @param scene defines the hosting scene
  55033. */
  55034. ActionManager.Parse = function (parsedActions, object, scene) {
  55035. var actionManager = new ActionManager(scene);
  55036. if (object === null)
  55037. scene.actionManager = actionManager;
  55038. else
  55039. object.actionManager = actionManager;
  55040. // instanciate a new object
  55041. var instanciate = function (name, params) {
  55042. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  55043. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  55044. newInstance.constructor.apply(newInstance, params);
  55045. return newInstance;
  55046. };
  55047. var parseParameter = function (name, value, target, propertyPath) {
  55048. if (propertyPath === null) {
  55049. // String, boolean or float
  55050. var floatValue = parseFloat(value);
  55051. if (value === "true" || value === "false")
  55052. return value === "true";
  55053. else
  55054. return isNaN(floatValue) ? value : floatValue;
  55055. }
  55056. var effectiveTarget = propertyPath.split(".");
  55057. var values = value.split(",");
  55058. // Get effective Target
  55059. for (var i = 0; i < effectiveTarget.length; i++) {
  55060. target = target[effectiveTarget[i]];
  55061. }
  55062. // Return appropriate value with its type
  55063. if (typeof (target) === "boolean")
  55064. return values[0] === "true";
  55065. if (typeof (target) === "string")
  55066. return values[0];
  55067. // Parameters with multiple values such as Vector3 etc.
  55068. var split = new Array();
  55069. for (var i = 0; i < values.length; i++)
  55070. split.push(parseFloat(values[i]));
  55071. if (target instanceof BABYLON.Vector3)
  55072. return BABYLON.Vector3.FromArray(split);
  55073. if (target instanceof BABYLON.Vector4)
  55074. return BABYLON.Vector4.FromArray(split);
  55075. if (target instanceof BABYLON.Color3)
  55076. return BABYLON.Color3.FromArray(split);
  55077. if (target instanceof BABYLON.Color4)
  55078. return BABYLON.Color4.FromArray(split);
  55079. return parseFloat(values[0]);
  55080. };
  55081. // traverse graph per trigger
  55082. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  55083. if (combineArray === void 0) { combineArray = null; }
  55084. if (parsedAction.detached)
  55085. return;
  55086. var parameters = new Array();
  55087. var target = null;
  55088. var propertyPath = null;
  55089. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  55090. // Parameters
  55091. if (parsedAction.type === 2)
  55092. parameters.push(actionManager);
  55093. else
  55094. parameters.push(trigger);
  55095. if (combine) {
  55096. var actions = new Array();
  55097. for (var j = 0; j < parsedAction.combine.length; j++) {
  55098. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  55099. }
  55100. parameters.push(actions);
  55101. }
  55102. else {
  55103. for (var i = 0; i < parsedAction.properties.length; i++) {
  55104. var value = parsedAction.properties[i].value;
  55105. var name = parsedAction.properties[i].name;
  55106. var targetType = parsedAction.properties[i].targetType;
  55107. if (name === "target")
  55108. if (targetType !== null && targetType === "SceneProperties")
  55109. value = target = scene;
  55110. else
  55111. value = target = scene.getNodeByName(value);
  55112. else if (name === "parent")
  55113. value = scene.getNodeByName(value);
  55114. else if (name === "sound") {
  55115. // Can not externalize to component, so only checks for the presence off the API.
  55116. if (scene.getSoundByName) {
  55117. value = scene.getSoundByName(value);
  55118. }
  55119. }
  55120. else if (name !== "propertyPath") {
  55121. if (parsedAction.type === 2 && name === "operator")
  55122. value = BABYLON.ValueCondition[value];
  55123. else
  55124. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  55125. }
  55126. else {
  55127. propertyPath = value;
  55128. }
  55129. parameters.push(value);
  55130. }
  55131. }
  55132. if (combineArray === null) {
  55133. parameters.push(condition);
  55134. }
  55135. else {
  55136. parameters.push(null);
  55137. }
  55138. // If interpolate value action
  55139. if (parsedAction.name === "InterpolateValueAction") {
  55140. var param = parameters[parameters.length - 2];
  55141. parameters[parameters.length - 1] = param;
  55142. parameters[parameters.length - 2] = condition;
  55143. }
  55144. // Action or condition(s) and not CombineAction
  55145. var newAction = instanciate(parsedAction.name, parameters);
  55146. if (newAction instanceof BABYLON.Condition && condition !== null) {
  55147. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  55148. if (action)
  55149. action.then(nothing);
  55150. else
  55151. actionManager.registerAction(nothing);
  55152. action = nothing;
  55153. }
  55154. if (combineArray === null) {
  55155. if (newAction instanceof BABYLON.Condition) {
  55156. condition = newAction;
  55157. newAction = action;
  55158. }
  55159. else {
  55160. condition = null;
  55161. if (action)
  55162. action.then(newAction);
  55163. else
  55164. actionManager.registerAction(newAction);
  55165. }
  55166. }
  55167. else {
  55168. combineArray.push(newAction);
  55169. }
  55170. for (var i = 0; i < parsedAction.children.length; i++)
  55171. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  55172. };
  55173. // triggers
  55174. for (var i = 0; i < parsedActions.children.length; i++) {
  55175. var triggerParams;
  55176. var trigger = parsedActions.children[i];
  55177. if (trigger.properties.length > 0) {
  55178. var param = trigger.properties[0].value;
  55179. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  55180. if (value._meshId) {
  55181. value.mesh = scene.getMeshByID(value._meshId);
  55182. }
  55183. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  55184. }
  55185. else
  55186. triggerParams = ActionManager[trigger.name];
  55187. for (var j = 0; j < trigger.children.length; j++) {
  55188. if (!trigger.detached)
  55189. traverse(trigger.children[j], triggerParams, null, null);
  55190. }
  55191. }
  55192. };
  55193. /**
  55194. * Get a trigger name by index
  55195. * @param trigger defines the trigger index
  55196. * @returns a trigger name
  55197. */
  55198. ActionManager.GetTriggerName = function (trigger) {
  55199. switch (trigger) {
  55200. case 0: return "NothingTrigger";
  55201. case 1: return "OnPickTrigger";
  55202. case 2: return "OnLeftPickTrigger";
  55203. case 3: return "OnRightPickTrigger";
  55204. case 4: return "OnCenterPickTrigger";
  55205. case 5: return "OnPickDownTrigger";
  55206. case 6: return "OnPickUpTrigger";
  55207. case 7: return "OnLongPressTrigger";
  55208. case 8: return "OnPointerOverTrigger";
  55209. case 9: return "OnPointerOutTrigger";
  55210. case 10: return "OnEveryFrameTrigger";
  55211. case 11: return "OnIntersectionEnterTrigger";
  55212. case 12: return "OnIntersectionExitTrigger";
  55213. case 13: return "OnKeyDownTrigger";
  55214. case 14: return "OnKeyUpTrigger";
  55215. case 15: return "OnPickOutTrigger";
  55216. default: return "";
  55217. }
  55218. };
  55219. /**
  55220. * Nothing
  55221. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55222. */
  55223. ActionManager.NothingTrigger = 0;
  55224. /**
  55225. * On pick
  55226. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55227. */
  55228. ActionManager.OnPickTrigger = 1;
  55229. /**
  55230. * On left pick
  55231. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55232. */
  55233. ActionManager.OnLeftPickTrigger = 2;
  55234. /**
  55235. * On right pick
  55236. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55237. */
  55238. ActionManager.OnRightPickTrigger = 3;
  55239. /**
  55240. * On center pick
  55241. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55242. */
  55243. ActionManager.OnCenterPickTrigger = 4;
  55244. /**
  55245. * On pick down
  55246. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55247. */
  55248. ActionManager.OnPickDownTrigger = 5;
  55249. /**
  55250. * On double pick
  55251. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55252. */
  55253. ActionManager.OnDoublePickTrigger = 6;
  55254. /**
  55255. * On pick up
  55256. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55257. */
  55258. ActionManager.OnPickUpTrigger = 7;
  55259. /**
  55260. * On pick out.
  55261. * This trigger will only be raised if you also declared a OnPickDown
  55262. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55263. */
  55264. ActionManager.OnPickOutTrigger = 16;
  55265. /**
  55266. * On long press
  55267. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55268. */
  55269. ActionManager.OnLongPressTrigger = 8;
  55270. /**
  55271. * On pointer over
  55272. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55273. */
  55274. ActionManager.OnPointerOverTrigger = 9;
  55275. /**
  55276. * On pointer out
  55277. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55278. */
  55279. ActionManager.OnPointerOutTrigger = 10;
  55280. /**
  55281. * On every frame
  55282. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55283. */
  55284. ActionManager.OnEveryFrameTrigger = 11;
  55285. /**
  55286. * On intersection enter
  55287. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55288. */
  55289. ActionManager.OnIntersectionEnterTrigger = 12;
  55290. /**
  55291. * On intersection exit
  55292. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55293. */
  55294. ActionManager.OnIntersectionExitTrigger = 13;
  55295. /**
  55296. * On key down
  55297. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55298. */
  55299. ActionManager.OnKeyDownTrigger = 14;
  55300. /**
  55301. * On key up
  55302. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55303. */
  55304. ActionManager.OnKeyUpTrigger = 15;
  55305. /** Gets the list of active triggers */
  55306. ActionManager.Triggers = {};
  55307. return ActionManager;
  55308. }());
  55309. BABYLON.ActionManager = ActionManager;
  55310. })(BABYLON || (BABYLON = {}));
  55311. //# sourceMappingURL=babylon.actionManager.js.map
  55312. var BABYLON;
  55313. (function (BABYLON) {
  55314. /**
  55315. * This defines an action responsible to change the value of a property
  55316. * by interpolating between its current value and the newly set one once triggered.
  55317. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55318. */
  55319. var InterpolateValueAction = /** @class */ (function (_super) {
  55320. __extends(InterpolateValueAction, _super);
  55321. /**
  55322. * Instantiate the action
  55323. * @param triggerOptions defines the trigger options
  55324. * @param target defines the object containing the value to interpolate
  55325. * @param propertyPath defines the path to the property in the target object
  55326. * @param value defines the target value at the end of the interpolation
  55327. * @param duration deines the time it will take for the property to interpolate to the value.
  55328. * @param condition defines the trigger related conditions
  55329. * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered
  55330. * @param onInterpolationDone defines a callback raised once the interpolation animation has been done
  55331. */
  55332. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  55333. if (duration === void 0) { duration = 1000; }
  55334. var _this = _super.call(this, triggerOptions, condition) || this;
  55335. /**
  55336. * Defines the time it will take for the property to interpolate to the value.
  55337. */
  55338. _this.duration = 1000;
  55339. /**
  55340. * Observable triggered once the interpolation animation has been done.
  55341. */
  55342. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  55343. _this.propertyPath = propertyPath;
  55344. _this.value = value;
  55345. _this.duration = duration;
  55346. _this.stopOtherAnimations = stopOtherAnimations;
  55347. _this.onInterpolationDone = onInterpolationDone;
  55348. _this._target = _this._effectiveTarget = target;
  55349. return _this;
  55350. }
  55351. /** @hidden */
  55352. InterpolateValueAction.prototype._prepare = function () {
  55353. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55354. this._property = this._getProperty(this.propertyPath);
  55355. };
  55356. /**
  55357. * Execute the action starts the value interpolation.
  55358. */
  55359. InterpolateValueAction.prototype.execute = function () {
  55360. var _this = this;
  55361. var scene = this._actionManager.getScene();
  55362. var keys = [
  55363. {
  55364. frame: 0,
  55365. value: this._effectiveTarget[this._property]
  55366. }, {
  55367. frame: 100,
  55368. value: this.value
  55369. }
  55370. ];
  55371. var dataType;
  55372. if (typeof this.value === "number") {
  55373. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  55374. }
  55375. else if (this.value instanceof BABYLON.Color3) {
  55376. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  55377. }
  55378. else if (this.value instanceof BABYLON.Vector3) {
  55379. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  55380. }
  55381. else if (this.value instanceof BABYLON.Matrix) {
  55382. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  55383. }
  55384. else if (this.value instanceof BABYLON.Quaternion) {
  55385. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  55386. }
  55387. else {
  55388. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  55389. return;
  55390. }
  55391. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  55392. animation.setKeys(keys);
  55393. if (this.stopOtherAnimations) {
  55394. scene.stopAnimation(this._effectiveTarget);
  55395. }
  55396. var wrapper = function () {
  55397. _this.onInterpolationDoneObservable.notifyObservers(_this);
  55398. if (_this.onInterpolationDone) {
  55399. _this.onInterpolationDone();
  55400. }
  55401. };
  55402. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  55403. };
  55404. /**
  55405. * Serializes the actions and its related information.
  55406. * @param parent defines the object to serialize in
  55407. * @returns the serialized object
  55408. */
  55409. InterpolateValueAction.prototype.serialize = function (parent) {
  55410. return _super.prototype._serialize.call(this, {
  55411. name: "InterpolateValueAction",
  55412. properties: [
  55413. BABYLON.Action._GetTargetProperty(this._target),
  55414. { name: "propertyPath", value: this.propertyPath },
  55415. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  55416. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  55417. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  55418. ]
  55419. }, parent);
  55420. };
  55421. return InterpolateValueAction;
  55422. }(BABYLON.Action));
  55423. BABYLON.InterpolateValueAction = InterpolateValueAction;
  55424. })(BABYLON || (BABYLON = {}));
  55425. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  55426. var BABYLON;
  55427. (function (BABYLON) {
  55428. /**
  55429. * This defines an action responsible to toggle a boolean once triggered.
  55430. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55431. */
  55432. var SwitchBooleanAction = /** @class */ (function (_super) {
  55433. __extends(SwitchBooleanAction, _super);
  55434. /**
  55435. * Instantiate the action
  55436. * @param triggerOptions defines the trigger options
  55437. * @param target defines the object containing the boolean
  55438. * @param propertyPath defines the path to the boolean property in the target object
  55439. * @param condition defines the trigger related conditions
  55440. */
  55441. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  55442. var _this = _super.call(this, triggerOptions, condition) || this;
  55443. _this.propertyPath = propertyPath;
  55444. _this._target = _this._effectiveTarget = target;
  55445. return _this;
  55446. }
  55447. /** @hidden */
  55448. SwitchBooleanAction.prototype._prepare = function () {
  55449. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55450. this._property = this._getProperty(this.propertyPath);
  55451. };
  55452. /**
  55453. * Execute the action toggle the boolean value.
  55454. */
  55455. SwitchBooleanAction.prototype.execute = function () {
  55456. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  55457. };
  55458. /**
  55459. * Serializes the actions and its related information.
  55460. * @param parent defines the object to serialize in
  55461. * @returns the serialized object
  55462. */
  55463. SwitchBooleanAction.prototype.serialize = function (parent) {
  55464. return _super.prototype._serialize.call(this, {
  55465. name: "SwitchBooleanAction",
  55466. properties: [
  55467. BABYLON.Action._GetTargetProperty(this._target),
  55468. { name: "propertyPath", value: this.propertyPath }
  55469. ]
  55470. }, parent);
  55471. };
  55472. return SwitchBooleanAction;
  55473. }(BABYLON.Action));
  55474. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  55475. /**
  55476. * This defines an action responsible to set a the state field of the target
  55477. * to a desired value once triggered.
  55478. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55479. */
  55480. var SetStateAction = /** @class */ (function (_super) {
  55481. __extends(SetStateAction, _super);
  55482. /**
  55483. * Instantiate the action
  55484. * @param triggerOptions defines the trigger options
  55485. * @param target defines the object containing the state property
  55486. * @param value defines the value to store in the state field
  55487. * @param condition defines the trigger related conditions
  55488. */
  55489. function SetStateAction(triggerOptions, target, value, condition) {
  55490. var _this = _super.call(this, triggerOptions, condition) || this;
  55491. _this.value = value;
  55492. _this._target = target;
  55493. return _this;
  55494. }
  55495. /**
  55496. * Execute the action and store the value on the target state property.
  55497. */
  55498. SetStateAction.prototype.execute = function () {
  55499. this._target.state = this.value;
  55500. };
  55501. /**
  55502. * Serializes the actions and its related information.
  55503. * @param parent defines the object to serialize in
  55504. * @returns the serialized object
  55505. */
  55506. SetStateAction.prototype.serialize = function (parent) {
  55507. return _super.prototype._serialize.call(this, {
  55508. name: "SetStateAction",
  55509. properties: [
  55510. BABYLON.Action._GetTargetProperty(this._target),
  55511. { name: "value", value: this.value }
  55512. ]
  55513. }, parent);
  55514. };
  55515. return SetStateAction;
  55516. }(BABYLON.Action));
  55517. BABYLON.SetStateAction = SetStateAction;
  55518. /**
  55519. * This defines an action responsible to set a property of the target
  55520. * to a desired value once triggered.
  55521. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55522. */
  55523. var SetValueAction = /** @class */ (function (_super) {
  55524. __extends(SetValueAction, _super);
  55525. /**
  55526. * Instantiate the action
  55527. * @param triggerOptions defines the trigger options
  55528. * @param target defines the object containing the property
  55529. * @param propertyPath defines the path of the property to set in the target
  55530. * @param value defines the value to set in the property
  55531. * @param condition defines the trigger related conditions
  55532. */
  55533. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  55534. var _this = _super.call(this, triggerOptions, condition) || this;
  55535. _this.propertyPath = propertyPath;
  55536. _this.value = value;
  55537. _this._target = _this._effectiveTarget = target;
  55538. return _this;
  55539. }
  55540. /** @hidden */
  55541. SetValueAction.prototype._prepare = function () {
  55542. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55543. this._property = this._getProperty(this.propertyPath);
  55544. };
  55545. /**
  55546. * Execute the action and set the targetted property to the desired value.
  55547. */
  55548. SetValueAction.prototype.execute = function () {
  55549. this._effectiveTarget[this._property] = this.value;
  55550. if (this._target.markAsDirty) {
  55551. this._target.markAsDirty(this._property);
  55552. }
  55553. };
  55554. /**
  55555. * Serializes the actions and its related information.
  55556. * @param parent defines the object to serialize in
  55557. * @returns the serialized object
  55558. */
  55559. SetValueAction.prototype.serialize = function (parent) {
  55560. return _super.prototype._serialize.call(this, {
  55561. name: "SetValueAction",
  55562. properties: [
  55563. BABYLON.Action._GetTargetProperty(this._target),
  55564. { name: "propertyPath", value: this.propertyPath },
  55565. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  55566. ]
  55567. }, parent);
  55568. };
  55569. return SetValueAction;
  55570. }(BABYLON.Action));
  55571. BABYLON.SetValueAction = SetValueAction;
  55572. /**
  55573. * This defines an action responsible to increment the target value
  55574. * to a desired value once triggered.
  55575. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55576. */
  55577. var IncrementValueAction = /** @class */ (function (_super) {
  55578. __extends(IncrementValueAction, _super);
  55579. /**
  55580. * Instantiate the action
  55581. * @param triggerOptions defines the trigger options
  55582. * @param target defines the object containing the property
  55583. * @param propertyPath defines the path of the property to increment in the target
  55584. * @param value defines the value value we should increment the property by
  55585. * @param condition defines the trigger related conditions
  55586. */
  55587. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  55588. var _this = _super.call(this, triggerOptions, condition) || this;
  55589. _this.propertyPath = propertyPath;
  55590. _this.value = value;
  55591. _this._target = _this._effectiveTarget = target;
  55592. return _this;
  55593. }
  55594. /** @hidden */
  55595. IncrementValueAction.prototype._prepare = function () {
  55596. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55597. this._property = this._getProperty(this.propertyPath);
  55598. if (typeof this._effectiveTarget[this._property] !== "number") {
  55599. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  55600. }
  55601. };
  55602. /**
  55603. * Execute the action and increment the target of the value amount.
  55604. */
  55605. IncrementValueAction.prototype.execute = function () {
  55606. this._effectiveTarget[this._property] += this.value;
  55607. if (this._target.markAsDirty) {
  55608. this._target.markAsDirty(this._property);
  55609. }
  55610. };
  55611. /**
  55612. * Serializes the actions and its related information.
  55613. * @param parent defines the object to serialize in
  55614. * @returns the serialized object
  55615. */
  55616. IncrementValueAction.prototype.serialize = function (parent) {
  55617. return _super.prototype._serialize.call(this, {
  55618. name: "IncrementValueAction",
  55619. properties: [
  55620. BABYLON.Action._GetTargetProperty(this._target),
  55621. { name: "propertyPath", value: this.propertyPath },
  55622. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  55623. ]
  55624. }, parent);
  55625. };
  55626. return IncrementValueAction;
  55627. }(BABYLON.Action));
  55628. BABYLON.IncrementValueAction = IncrementValueAction;
  55629. /**
  55630. * This defines an action responsible to start an animation once triggered.
  55631. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55632. */
  55633. var PlayAnimationAction = /** @class */ (function (_super) {
  55634. __extends(PlayAnimationAction, _super);
  55635. /**
  55636. * Instantiate the action
  55637. * @param triggerOptions defines the trigger options
  55638. * @param target defines the target animation or animation name
  55639. * @param from defines from where the animation should start (animation frame)
  55640. * @param end defines where the animation should stop (animation frame)
  55641. * @param loop defines if the animation should loop or stop after the first play
  55642. * @param condition defines the trigger related conditions
  55643. */
  55644. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  55645. var _this = _super.call(this, triggerOptions, condition) || this;
  55646. _this.from = from;
  55647. _this.to = to;
  55648. _this.loop = loop;
  55649. _this._target = target;
  55650. return _this;
  55651. }
  55652. /** @hidden */
  55653. PlayAnimationAction.prototype._prepare = function () {
  55654. };
  55655. /**
  55656. * Execute the action and play the animation.
  55657. */
  55658. PlayAnimationAction.prototype.execute = function () {
  55659. var scene = this._actionManager.getScene();
  55660. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  55661. };
  55662. /**
  55663. * Serializes the actions and its related information.
  55664. * @param parent defines the object to serialize in
  55665. * @returns the serialized object
  55666. */
  55667. PlayAnimationAction.prototype.serialize = function (parent) {
  55668. return _super.prototype._serialize.call(this, {
  55669. name: "PlayAnimationAction",
  55670. properties: [
  55671. BABYLON.Action._GetTargetProperty(this._target),
  55672. { name: "from", value: String(this.from) },
  55673. { name: "to", value: String(this.to) },
  55674. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  55675. ]
  55676. }, parent);
  55677. };
  55678. return PlayAnimationAction;
  55679. }(BABYLON.Action));
  55680. BABYLON.PlayAnimationAction = PlayAnimationAction;
  55681. /**
  55682. * This defines an action responsible to stop an animation once triggered.
  55683. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55684. */
  55685. var StopAnimationAction = /** @class */ (function (_super) {
  55686. __extends(StopAnimationAction, _super);
  55687. /**
  55688. * Instantiate the action
  55689. * @param triggerOptions defines the trigger options
  55690. * @param target defines the target animation or animation name
  55691. * @param condition defines the trigger related conditions
  55692. */
  55693. function StopAnimationAction(triggerOptions, target, condition) {
  55694. var _this = _super.call(this, triggerOptions, condition) || this;
  55695. _this._target = target;
  55696. return _this;
  55697. }
  55698. /** @hidden */
  55699. StopAnimationAction.prototype._prepare = function () {
  55700. };
  55701. /**
  55702. * Execute the action and stop the animation.
  55703. */
  55704. StopAnimationAction.prototype.execute = function () {
  55705. var scene = this._actionManager.getScene();
  55706. scene.stopAnimation(this._target);
  55707. };
  55708. /**
  55709. * Serializes the actions and its related information.
  55710. * @param parent defines the object to serialize in
  55711. * @returns the serialized object
  55712. */
  55713. StopAnimationAction.prototype.serialize = function (parent) {
  55714. return _super.prototype._serialize.call(this, {
  55715. name: "StopAnimationAction",
  55716. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  55717. }, parent);
  55718. };
  55719. return StopAnimationAction;
  55720. }(BABYLON.Action));
  55721. BABYLON.StopAnimationAction = StopAnimationAction;
  55722. /**
  55723. * This defines an action responsible that does nothing once triggered.
  55724. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55725. */
  55726. var DoNothingAction = /** @class */ (function (_super) {
  55727. __extends(DoNothingAction, _super);
  55728. /**
  55729. * Instantiate the action
  55730. * @param triggerOptions defines the trigger options
  55731. * @param condition defines the trigger related conditions
  55732. */
  55733. function DoNothingAction(triggerOptions, condition) {
  55734. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  55735. return _super.call(this, triggerOptions, condition) || this;
  55736. }
  55737. /**
  55738. * Execute the action and do nothing.
  55739. */
  55740. DoNothingAction.prototype.execute = function () {
  55741. };
  55742. /**
  55743. * Serializes the actions and its related information.
  55744. * @param parent defines the object to serialize in
  55745. * @returns the serialized object
  55746. */
  55747. DoNothingAction.prototype.serialize = function (parent) {
  55748. return _super.prototype._serialize.call(this, {
  55749. name: "DoNothingAction",
  55750. properties: []
  55751. }, parent);
  55752. };
  55753. return DoNothingAction;
  55754. }(BABYLON.Action));
  55755. BABYLON.DoNothingAction = DoNothingAction;
  55756. /**
  55757. * This defines an action responsible to trigger several actions once triggered.
  55758. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55759. */
  55760. var CombineAction = /** @class */ (function (_super) {
  55761. __extends(CombineAction, _super);
  55762. /**
  55763. * Instantiate the action
  55764. * @param triggerOptions defines the trigger options
  55765. * @param children defines the list of aggregated animations to run
  55766. * @param condition defines the trigger related conditions
  55767. */
  55768. function CombineAction(triggerOptions, children, condition) {
  55769. var _this = _super.call(this, triggerOptions, condition) || this;
  55770. _this.children = children;
  55771. return _this;
  55772. }
  55773. /** @hidden */
  55774. CombineAction.prototype._prepare = function () {
  55775. for (var index = 0; index < this.children.length; index++) {
  55776. this.children[index]._actionManager = this._actionManager;
  55777. this.children[index]._prepare();
  55778. }
  55779. };
  55780. /**
  55781. * Execute the action and executes all the aggregated actions.
  55782. */
  55783. CombineAction.prototype.execute = function (evt) {
  55784. for (var index = 0; index < this.children.length; index++) {
  55785. this.children[index].execute(evt);
  55786. }
  55787. };
  55788. /**
  55789. * Serializes the actions and its related information.
  55790. * @param parent defines the object to serialize in
  55791. * @returns the serialized object
  55792. */
  55793. CombineAction.prototype.serialize = function (parent) {
  55794. var serializationObject = _super.prototype._serialize.call(this, {
  55795. name: "CombineAction",
  55796. properties: [],
  55797. combine: []
  55798. }, parent);
  55799. for (var i = 0; i < this.children.length; i++) {
  55800. serializationObject.combine.push(this.children[i].serialize(null));
  55801. }
  55802. return serializationObject;
  55803. };
  55804. return CombineAction;
  55805. }(BABYLON.Action));
  55806. BABYLON.CombineAction = CombineAction;
  55807. /**
  55808. * This defines an action responsible to run code (external event) once triggered.
  55809. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55810. */
  55811. var ExecuteCodeAction = /** @class */ (function (_super) {
  55812. __extends(ExecuteCodeAction, _super);
  55813. /**
  55814. * Instantiate the action
  55815. * @param triggerOptions defines the trigger options
  55816. * @param func defines the callback function to run
  55817. * @param condition defines the trigger related conditions
  55818. */
  55819. function ExecuteCodeAction(triggerOptions, func, condition) {
  55820. var _this = _super.call(this, triggerOptions, condition) || this;
  55821. _this.func = func;
  55822. return _this;
  55823. }
  55824. /**
  55825. * Execute the action and run the attached code.
  55826. */
  55827. ExecuteCodeAction.prototype.execute = function (evt) {
  55828. this.func(evt);
  55829. };
  55830. return ExecuteCodeAction;
  55831. }(BABYLON.Action));
  55832. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  55833. /**
  55834. * This defines an action responsible to set the parent property of the target once triggered.
  55835. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55836. */
  55837. var SetParentAction = /** @class */ (function (_super) {
  55838. __extends(SetParentAction, _super);
  55839. /**
  55840. * Instantiate the action
  55841. * @param triggerOptions defines the trigger options
  55842. * @param target defines the target containing the parent property
  55843. * @param parent defines from where the animation should start (animation frame)
  55844. * @param condition defines the trigger related conditions
  55845. */
  55846. function SetParentAction(triggerOptions, target, parent, condition) {
  55847. var _this = _super.call(this, triggerOptions, condition) || this;
  55848. _this._target = target;
  55849. _this._parent = parent;
  55850. return _this;
  55851. }
  55852. /** @hidden */
  55853. SetParentAction.prototype._prepare = function () {
  55854. };
  55855. /**
  55856. * Execute the action and set the parent property.
  55857. */
  55858. SetParentAction.prototype.execute = function () {
  55859. if (this._target.parent === this._parent) {
  55860. return;
  55861. }
  55862. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  55863. invertParentWorldMatrix.invert();
  55864. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  55865. this._target.parent = this._parent;
  55866. };
  55867. /**
  55868. * Serializes the actions and its related information.
  55869. * @param parent defines the object to serialize in
  55870. * @returns the serialized object
  55871. */
  55872. SetParentAction.prototype.serialize = function (parent) {
  55873. return _super.prototype._serialize.call(this, {
  55874. name: "SetParentAction",
  55875. properties: [
  55876. BABYLON.Action._GetTargetProperty(this._target),
  55877. BABYLON.Action._GetTargetProperty(this._parent),
  55878. ]
  55879. }, parent);
  55880. };
  55881. return SetParentAction;
  55882. }(BABYLON.Action));
  55883. BABYLON.SetParentAction = SetParentAction;
  55884. })(BABYLON || (BABYLON = {}));
  55885. //# sourceMappingURL=babylon.directActions.js.map
  55886. var BABYLON;
  55887. (function (BABYLON) {
  55888. var SpriteManager = /** @class */ (function () {
  55889. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  55890. if (epsilon === void 0) { epsilon = 0.01; }
  55891. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55892. this.name = name;
  55893. this.sprites = new Array();
  55894. this.renderingGroupId = 0;
  55895. this.layerMask = 0x0FFFFFFF;
  55896. this.fogEnabled = true;
  55897. this.isPickable = false;
  55898. /**
  55899. * An event triggered when the manager is disposed.
  55900. */
  55901. this.onDisposeObservable = new BABYLON.Observable();
  55902. this._vertexBuffers = {};
  55903. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  55904. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  55905. }
  55906. this._capacity = capacity;
  55907. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  55908. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55909. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55910. if (cellSize.width && cellSize.height) {
  55911. this.cellWidth = cellSize.width;
  55912. this.cellHeight = cellSize.height;
  55913. }
  55914. else if (cellSize !== undefined) {
  55915. this.cellWidth = cellSize;
  55916. this.cellHeight = cellSize;
  55917. }
  55918. else {
  55919. return;
  55920. }
  55921. this._epsilon = epsilon;
  55922. this._scene = scene;
  55923. this._scene.spriteManagers.push(this);
  55924. var indices = [];
  55925. var index = 0;
  55926. for (var count = 0; count < capacity; count++) {
  55927. indices.push(index);
  55928. indices.push(index + 1);
  55929. indices.push(index + 2);
  55930. indices.push(index);
  55931. indices.push(index + 2);
  55932. indices.push(index + 3);
  55933. index += 4;
  55934. }
  55935. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  55936. // VBO
  55937. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  55938. this._vertexData = new Float32Array(capacity * 16 * 4);
  55939. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  55940. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  55941. var options = this._buffer.createVertexBuffer("options", 4, 4);
  55942. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  55943. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  55944. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55945. this._vertexBuffers["options"] = options;
  55946. this._vertexBuffers["cellInfo"] = cellInfo;
  55947. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55948. // Effects
  55949. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  55950. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  55951. }
  55952. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  55953. set: function (callback) {
  55954. if (this._onDisposeObserver) {
  55955. this.onDisposeObservable.remove(this._onDisposeObserver);
  55956. }
  55957. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55958. },
  55959. enumerable: true,
  55960. configurable: true
  55961. });
  55962. Object.defineProperty(SpriteManager.prototype, "texture", {
  55963. get: function () {
  55964. return this._spriteTexture;
  55965. },
  55966. set: function (value) {
  55967. this._spriteTexture = value;
  55968. },
  55969. enumerable: true,
  55970. configurable: true
  55971. });
  55972. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  55973. var arrayOffset = index * 16;
  55974. if (offsetX === 0)
  55975. offsetX = this._epsilon;
  55976. else if (offsetX === 1)
  55977. offsetX = 1 - this._epsilon;
  55978. if (offsetY === 0)
  55979. offsetY = this._epsilon;
  55980. else if (offsetY === 1)
  55981. offsetY = 1 - this._epsilon;
  55982. this._vertexData[arrayOffset] = sprite.position.x;
  55983. this._vertexData[arrayOffset + 1] = sprite.position.y;
  55984. this._vertexData[arrayOffset + 2] = sprite.position.z;
  55985. this._vertexData[arrayOffset + 3] = sprite.angle;
  55986. this._vertexData[arrayOffset + 4] = sprite.width;
  55987. this._vertexData[arrayOffset + 5] = sprite.height;
  55988. this._vertexData[arrayOffset + 6] = offsetX;
  55989. this._vertexData[arrayOffset + 7] = offsetY;
  55990. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  55991. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  55992. var offset = (sprite.cellIndex / rowSize) >> 0;
  55993. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  55994. this._vertexData[arrayOffset + 11] = offset;
  55995. // Color
  55996. this._vertexData[arrayOffset + 12] = sprite.color.r;
  55997. this._vertexData[arrayOffset + 13] = sprite.color.g;
  55998. this._vertexData[arrayOffset + 14] = sprite.color.b;
  55999. this._vertexData[arrayOffset + 15] = sprite.color.a;
  56000. };
  56001. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  56002. var count = Math.min(this._capacity, this.sprites.length);
  56003. var min = BABYLON.Vector3.Zero();
  56004. var max = BABYLON.Vector3.Zero();
  56005. var distance = Number.MAX_VALUE;
  56006. var currentSprite = null;
  56007. var cameraSpacePosition = BABYLON.Vector3.Zero();
  56008. var cameraView = camera.getViewMatrix();
  56009. for (var index = 0; index < count; index++) {
  56010. var sprite = this.sprites[index];
  56011. if (!sprite) {
  56012. continue;
  56013. }
  56014. if (predicate) {
  56015. if (!predicate(sprite)) {
  56016. continue;
  56017. }
  56018. }
  56019. else if (!sprite.isPickable) {
  56020. continue;
  56021. }
  56022. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  56023. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  56024. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  56025. if (ray.intersectsBoxMinMax(min, max)) {
  56026. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  56027. if (distance > currentDistance) {
  56028. distance = currentDistance;
  56029. currentSprite = sprite;
  56030. if (fastCheck) {
  56031. break;
  56032. }
  56033. }
  56034. }
  56035. }
  56036. if (currentSprite) {
  56037. var result = new BABYLON.PickingInfo();
  56038. result.hit = true;
  56039. result.pickedSprite = currentSprite;
  56040. result.distance = distance;
  56041. return result;
  56042. }
  56043. return null;
  56044. };
  56045. SpriteManager.prototype.render = function () {
  56046. // Check
  56047. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  56048. return;
  56049. var engine = this._scene.getEngine();
  56050. var baseSize = this._spriteTexture.getBaseSize();
  56051. // Sprites
  56052. var deltaTime = engine.getDeltaTime();
  56053. var max = Math.min(this._capacity, this.sprites.length);
  56054. var rowSize = baseSize.width / this.cellWidth;
  56055. var offset = 0;
  56056. for (var index = 0; index < max; index++) {
  56057. var sprite = this.sprites[index];
  56058. if (!sprite || !sprite.isVisible) {
  56059. continue;
  56060. }
  56061. sprite._animate(deltaTime);
  56062. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  56063. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  56064. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  56065. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  56066. }
  56067. this._buffer.update(this._vertexData);
  56068. // Render
  56069. var effect = this._effectBase;
  56070. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  56071. effect = this._effectFog;
  56072. }
  56073. engine.enableEffect(effect);
  56074. var viewMatrix = this._scene.getViewMatrix();
  56075. effect.setTexture("diffuseSampler", this._spriteTexture);
  56076. effect.setMatrix("view", viewMatrix);
  56077. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56078. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  56079. // Fog
  56080. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  56081. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  56082. effect.setColor3("vFogColor", this._scene.fogColor);
  56083. }
  56084. // VBOs
  56085. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56086. // Draw order
  56087. engine.setDepthFunctionToLessOrEqual();
  56088. effect.setBool("alphaTest", true);
  56089. engine.setColorWrite(false);
  56090. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  56091. engine.setColorWrite(true);
  56092. effect.setBool("alphaTest", false);
  56093. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56094. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  56095. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56096. };
  56097. SpriteManager.prototype.dispose = function () {
  56098. if (this._buffer) {
  56099. this._buffer.dispose();
  56100. this._buffer = null;
  56101. }
  56102. if (this._indexBuffer) {
  56103. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56104. this._indexBuffer = null;
  56105. }
  56106. if (this._spriteTexture) {
  56107. this._spriteTexture.dispose();
  56108. this._spriteTexture = null;
  56109. }
  56110. // Remove from scene
  56111. var index = this._scene.spriteManagers.indexOf(this);
  56112. this._scene.spriteManagers.splice(index, 1);
  56113. // Callback
  56114. this.onDisposeObservable.notifyObservers(this);
  56115. this.onDisposeObservable.clear();
  56116. };
  56117. return SpriteManager;
  56118. }());
  56119. BABYLON.SpriteManager = SpriteManager;
  56120. })(BABYLON || (BABYLON = {}));
  56121. //# sourceMappingURL=babylon.spriteManager.js.map
  56122. var BABYLON;
  56123. (function (BABYLON) {
  56124. var Sprite = /** @class */ (function () {
  56125. function Sprite(name, manager) {
  56126. this.name = name;
  56127. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56128. this.width = 1.0;
  56129. this.height = 1.0;
  56130. this.angle = 0;
  56131. this.cellIndex = 0;
  56132. this.invertU = 0;
  56133. this.invertV = 0;
  56134. this.animations = new Array();
  56135. this.isPickable = false;
  56136. this._animationStarted = false;
  56137. this._loopAnimation = false;
  56138. this._fromIndex = 0;
  56139. this._toIndex = 0;
  56140. this._delay = 0;
  56141. this._direction = 1;
  56142. this._time = 0;
  56143. /**
  56144. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  56145. */
  56146. this.isVisible = true;
  56147. this._manager = manager;
  56148. this._manager.sprites.push(this);
  56149. this.position = BABYLON.Vector3.Zero();
  56150. }
  56151. Object.defineProperty(Sprite.prototype, "size", {
  56152. get: function () {
  56153. return this.width;
  56154. },
  56155. set: function (value) {
  56156. this.width = value;
  56157. this.height = value;
  56158. },
  56159. enumerable: true,
  56160. configurable: true
  56161. });
  56162. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  56163. this._fromIndex = from;
  56164. this._toIndex = to;
  56165. this._loopAnimation = loop;
  56166. this._delay = delay;
  56167. this._animationStarted = true;
  56168. this._direction = from < to ? 1 : -1;
  56169. this.cellIndex = from;
  56170. this._time = 0;
  56171. this._onAnimationEnd = onAnimationEnd;
  56172. };
  56173. Sprite.prototype.stopAnimation = function () {
  56174. this._animationStarted = false;
  56175. };
  56176. /** @hidden */
  56177. Sprite.prototype._animate = function (deltaTime) {
  56178. if (!this._animationStarted)
  56179. return;
  56180. this._time += deltaTime;
  56181. if (this._time > this._delay) {
  56182. this._time = this._time % this._delay;
  56183. this.cellIndex += this._direction;
  56184. if (this.cellIndex > this._toIndex) {
  56185. if (this._loopAnimation) {
  56186. this.cellIndex = this._fromIndex;
  56187. }
  56188. else {
  56189. this.cellIndex = this._toIndex;
  56190. this._animationStarted = false;
  56191. if (this._onAnimationEnd) {
  56192. this._onAnimationEnd();
  56193. }
  56194. if (this.disposeWhenFinishedAnimating) {
  56195. this.dispose();
  56196. }
  56197. }
  56198. }
  56199. }
  56200. };
  56201. Sprite.prototype.dispose = function () {
  56202. for (var i = 0; i < this._manager.sprites.length; i++) {
  56203. if (this._manager.sprites[i] == this) {
  56204. this._manager.sprites.splice(i, 1);
  56205. }
  56206. }
  56207. };
  56208. return Sprite;
  56209. }());
  56210. BABYLON.Sprite = Sprite;
  56211. })(BABYLON || (BABYLON = {}));
  56212. //# sourceMappingURL=babylon.sprite.js.map
  56213. var BABYLON;
  56214. (function (BABYLON) {
  56215. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  56216. if (!BABYLON.PickingInfo) {
  56217. return null;
  56218. }
  56219. var pickingInfo = null;
  56220. if (!camera) {
  56221. if (!this.activeCamera) {
  56222. return null;
  56223. }
  56224. camera = this.activeCamera;
  56225. }
  56226. if (this.spriteManagers.length > 0) {
  56227. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  56228. var spriteManager = this.spriteManagers[spriteIndex];
  56229. if (!spriteManager.isPickable) {
  56230. continue;
  56231. }
  56232. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  56233. if (!result || !result.hit)
  56234. continue;
  56235. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  56236. continue;
  56237. pickingInfo = result;
  56238. if (fastCheck) {
  56239. break;
  56240. }
  56241. }
  56242. }
  56243. return pickingInfo || new BABYLON.PickingInfo();
  56244. };
  56245. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  56246. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  56247. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  56248. };
  56249. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  56250. if (!this._tempSpritePickingRay) {
  56251. return null;
  56252. }
  56253. if (!camera) {
  56254. if (!this.activeCamera) {
  56255. return null;
  56256. }
  56257. camera = this.activeCamera;
  56258. }
  56259. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  56260. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  56261. };
  56262. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  56263. if (this._pointerOverSprite === sprite) {
  56264. return;
  56265. }
  56266. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  56267. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  56268. }
  56269. this._pointerOverSprite = sprite;
  56270. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  56271. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  56272. }
  56273. };
  56274. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  56275. return this._pointerOverSprite;
  56276. };
  56277. /**
  56278. * Defines the sprite scene component responsible to manage sprites
  56279. * in a given scene.
  56280. */
  56281. var SpriteSceneComponent = /** @class */ (function () {
  56282. /**
  56283. * Creates a new instance of the component for the given scene
  56284. * @param scene Defines the scene to register the component in
  56285. */
  56286. function SpriteSceneComponent(scene) {
  56287. /**
  56288. * The component name helpfull to identify the component in the list of scene components.
  56289. */
  56290. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  56291. this.scene = scene;
  56292. this.scene.spriteManagers = new Array();
  56293. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  56294. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  56295. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  56296. this._spritePredicate = function (sprite) {
  56297. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  56298. };
  56299. }
  56300. /**
  56301. * Registers the component in a given scene
  56302. */
  56303. SpriteSceneComponent.prototype.register = function () {
  56304. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  56305. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  56306. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  56307. };
  56308. /**
  56309. * Rebuilds the elements related to this component in case of
  56310. * context lost for instance.
  56311. */
  56312. SpriteSceneComponent.prototype.rebuild = function () {
  56313. /** Nothing to do for sprites */
  56314. };
  56315. /**
  56316. * Disposes the component and the associated ressources.
  56317. */
  56318. SpriteSceneComponent.prototype.dispose = function () {
  56319. this.scene.onBeforeSpritesRenderingObservable.clear();
  56320. this.scene.onAfterSpritesRenderingObservable.clear();
  56321. var spriteManagers = this.scene.spriteManagers;
  56322. while (spriteManagers.length) {
  56323. spriteManagers[0].dispose();
  56324. }
  56325. };
  56326. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  56327. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  56328. if (result) {
  56329. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  56330. }
  56331. return result;
  56332. };
  56333. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  56334. var scene = this.scene;
  56335. if (isMeshPicked) {
  56336. scene.setPointerOverSprite(null);
  56337. }
  56338. else {
  56339. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  56340. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  56341. scene.setPointerOverSprite(pickResult.pickedSprite);
  56342. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  56343. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  56344. }
  56345. else {
  56346. canvas.style.cursor = scene.hoverCursor;
  56347. }
  56348. }
  56349. else {
  56350. scene.setPointerOverSprite(null);
  56351. }
  56352. }
  56353. return pickResult;
  56354. };
  56355. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  56356. var scene = this.scene;
  56357. scene._pickedDownSprite = null;
  56358. if (scene.spriteManagers.length > 0) {
  56359. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  56360. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  56361. if (pickResult.pickedSprite.actionManager) {
  56362. scene._pickedDownSprite = pickResult.pickedSprite;
  56363. switch (evt.button) {
  56364. case 0:
  56365. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56366. break;
  56367. case 1:
  56368. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56369. break;
  56370. case 2:
  56371. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56372. break;
  56373. }
  56374. if (pickResult.pickedSprite.actionManager) {
  56375. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56376. }
  56377. }
  56378. }
  56379. }
  56380. return pickResult;
  56381. };
  56382. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  56383. var scene = this.scene;
  56384. if (scene.spriteManagers.length > 0) {
  56385. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  56386. if (spritePickResult) {
  56387. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  56388. if (spritePickResult.pickedSprite.actionManager) {
  56389. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  56390. if (spritePickResult.pickedSprite.actionManager) {
  56391. if (!this.scene._isPointerSwiping()) {
  56392. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  56393. }
  56394. }
  56395. }
  56396. }
  56397. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  56398. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  56399. }
  56400. }
  56401. }
  56402. return pickResult;
  56403. };
  56404. return SpriteSceneComponent;
  56405. }());
  56406. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  56407. })(BABYLON || (BABYLON = {}));
  56408. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  56409. var BABYLON;
  56410. (function (BABYLON) {
  56411. /**
  56412. * @hidden
  56413. */
  56414. var IntersectionInfo = /** @class */ (function () {
  56415. function IntersectionInfo(bu, bv, distance) {
  56416. this.bu = bu;
  56417. this.bv = bv;
  56418. this.distance = distance;
  56419. this.faceId = 0;
  56420. this.subMeshId = 0;
  56421. }
  56422. return IntersectionInfo;
  56423. }());
  56424. BABYLON.IntersectionInfo = IntersectionInfo;
  56425. /**
  56426. * Information about the result of picking within a scene
  56427. * @see https://doc.babylonjs.com/babylon101/picking_collisions
  56428. */
  56429. var PickingInfo = /** @class */ (function () {
  56430. function PickingInfo() {
  56431. /**
  56432. * If the pick collided with an object
  56433. */
  56434. this.hit = false;
  56435. /**
  56436. * Distance away where the pick collided
  56437. */
  56438. this.distance = 0;
  56439. /**
  56440. * The location of pick collision
  56441. */
  56442. this.pickedPoint = null;
  56443. /**
  56444. * The mesh corresponding the the pick collision
  56445. */
  56446. this.pickedMesh = null;
  56447. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  56448. this.bu = 0;
  56449. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  56450. this.bv = 0;
  56451. /** The id of the face on the mesh that was picked */
  56452. this.faceId = -1;
  56453. /** Id of the the submesh that was picked */
  56454. this.subMeshId = 0;
  56455. /** If a sprite was picked, this will be the sprite the pick collided with */
  56456. this.pickedSprite = null;
  56457. /**
  56458. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  56459. */
  56460. this.originMesh = null;
  56461. /**
  56462. * The ray that was used to perform the picking.
  56463. */
  56464. this.ray = null;
  56465. }
  56466. /**
  56467. * Gets the normal correspodning to the face the pick collided with
  56468. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  56469. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  56470. * @returns The normal correspodning to the face the pick collided with
  56471. */
  56472. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  56473. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  56474. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  56475. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  56476. return null;
  56477. }
  56478. var indices = this.pickedMesh.getIndices();
  56479. if (!indices) {
  56480. return null;
  56481. }
  56482. var result;
  56483. if (useVerticesNormals) {
  56484. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56485. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  56486. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  56487. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  56488. normal0 = normal0.scale(this.bu);
  56489. normal1 = normal1.scale(this.bv);
  56490. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  56491. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  56492. }
  56493. else {
  56494. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56495. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  56496. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  56497. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  56498. var p1p2 = vertex1.subtract(vertex2);
  56499. var p3p2 = vertex3.subtract(vertex2);
  56500. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  56501. }
  56502. if (useWorldCoordinates) {
  56503. var wm = this.pickedMesh.getWorldMatrix();
  56504. if (this.pickedMesh.nonUniformScaling) {
  56505. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  56506. wm = BABYLON.Tmp.Matrix[0];
  56507. wm.setTranslationFromFloats(0, 0, 0);
  56508. wm.invert();
  56509. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  56510. wm = BABYLON.Tmp.Matrix[1];
  56511. }
  56512. result = BABYLON.Vector3.TransformNormal(result, wm);
  56513. }
  56514. result.normalize();
  56515. return result;
  56516. };
  56517. /**
  56518. * Gets the texture coordinates of where the pick occured
  56519. * @returns the vector containing the coordnates of the texture
  56520. */
  56521. PickingInfo.prototype.getTextureCoordinates = function () {
  56522. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  56523. return null;
  56524. }
  56525. var indices = this.pickedMesh.getIndices();
  56526. if (!indices) {
  56527. return null;
  56528. }
  56529. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56530. if (!uvs) {
  56531. return null;
  56532. }
  56533. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  56534. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  56535. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  56536. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  56537. uv1 = uv1.scale(this.bu);
  56538. uv2 = uv2.scale(this.bv);
  56539. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  56540. };
  56541. return PickingInfo;
  56542. }());
  56543. BABYLON.PickingInfo = PickingInfo;
  56544. })(BABYLON || (BABYLON = {}));
  56545. //# sourceMappingURL=babylon.pickingInfo.js.map
  56546. var BABYLON;
  56547. (function (BABYLON) {
  56548. var Ray = /** @class */ (function () {
  56549. function Ray(origin, direction, length) {
  56550. if (length === void 0) { length = Number.MAX_VALUE; }
  56551. this.origin = origin;
  56552. this.direction = direction;
  56553. this.length = length;
  56554. }
  56555. // Methods
  56556. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  56557. var d = 0.0;
  56558. var maxValue = Number.MAX_VALUE;
  56559. var inv;
  56560. var min;
  56561. var max;
  56562. var temp;
  56563. if (Math.abs(this.direction.x) < 0.0000001) {
  56564. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  56565. return false;
  56566. }
  56567. }
  56568. else {
  56569. inv = 1.0 / this.direction.x;
  56570. min = (minimum.x - this.origin.x) * inv;
  56571. max = (maximum.x - this.origin.x) * inv;
  56572. if (max === -Infinity) {
  56573. max = Infinity;
  56574. }
  56575. if (min > max) {
  56576. temp = min;
  56577. min = max;
  56578. max = temp;
  56579. }
  56580. d = Math.max(min, d);
  56581. maxValue = Math.min(max, maxValue);
  56582. if (d > maxValue) {
  56583. return false;
  56584. }
  56585. }
  56586. if (Math.abs(this.direction.y) < 0.0000001) {
  56587. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  56588. return false;
  56589. }
  56590. }
  56591. else {
  56592. inv = 1.0 / this.direction.y;
  56593. min = (minimum.y - this.origin.y) * inv;
  56594. max = (maximum.y - this.origin.y) * inv;
  56595. if (max === -Infinity) {
  56596. max = Infinity;
  56597. }
  56598. if (min > max) {
  56599. temp = min;
  56600. min = max;
  56601. max = temp;
  56602. }
  56603. d = Math.max(min, d);
  56604. maxValue = Math.min(max, maxValue);
  56605. if (d > maxValue) {
  56606. return false;
  56607. }
  56608. }
  56609. if (Math.abs(this.direction.z) < 0.0000001) {
  56610. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  56611. return false;
  56612. }
  56613. }
  56614. else {
  56615. inv = 1.0 / this.direction.z;
  56616. min = (minimum.z - this.origin.z) * inv;
  56617. max = (maximum.z - this.origin.z) * inv;
  56618. if (max === -Infinity) {
  56619. max = Infinity;
  56620. }
  56621. if (min > max) {
  56622. temp = min;
  56623. min = max;
  56624. max = temp;
  56625. }
  56626. d = Math.max(min, d);
  56627. maxValue = Math.min(max, maxValue);
  56628. if (d > maxValue) {
  56629. return false;
  56630. }
  56631. }
  56632. return true;
  56633. };
  56634. Ray.prototype.intersectsBox = function (box) {
  56635. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  56636. };
  56637. Ray.prototype.intersectsSphere = function (sphere) {
  56638. var x = sphere.center.x - this.origin.x;
  56639. var y = sphere.center.y - this.origin.y;
  56640. var z = sphere.center.z - this.origin.z;
  56641. var pyth = (x * x) + (y * y) + (z * z);
  56642. var rr = sphere.radius * sphere.radius;
  56643. if (pyth <= rr) {
  56644. return true;
  56645. }
  56646. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  56647. if (dot < 0.0) {
  56648. return false;
  56649. }
  56650. var temp = pyth - (dot * dot);
  56651. return temp <= rr;
  56652. };
  56653. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  56654. if (!this._edge1) {
  56655. this._edge1 = BABYLON.Vector3.Zero();
  56656. this._edge2 = BABYLON.Vector3.Zero();
  56657. this._pvec = BABYLON.Vector3.Zero();
  56658. this._tvec = BABYLON.Vector3.Zero();
  56659. this._qvec = BABYLON.Vector3.Zero();
  56660. }
  56661. vertex1.subtractToRef(vertex0, this._edge1);
  56662. vertex2.subtractToRef(vertex0, this._edge2);
  56663. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  56664. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  56665. if (det === 0) {
  56666. return null;
  56667. }
  56668. var invdet = 1 / det;
  56669. this.origin.subtractToRef(vertex0, this._tvec);
  56670. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  56671. if (bu < 0 || bu > 1.0) {
  56672. return null;
  56673. }
  56674. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  56675. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  56676. if (bv < 0 || bu + bv > 1.0) {
  56677. return null;
  56678. }
  56679. //check if the distance is longer than the predefined length.
  56680. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  56681. if (distance > this.length) {
  56682. return null;
  56683. }
  56684. return new BABYLON.IntersectionInfo(bu, bv, distance);
  56685. };
  56686. Ray.prototype.intersectsPlane = function (plane) {
  56687. var distance;
  56688. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  56689. if (Math.abs(result1) < 9.99999997475243E-07) {
  56690. return null;
  56691. }
  56692. else {
  56693. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  56694. distance = (-plane.d - result2) / result1;
  56695. if (distance < 0.0) {
  56696. if (distance < -9.99999997475243E-07) {
  56697. return null;
  56698. }
  56699. else {
  56700. return 0;
  56701. }
  56702. }
  56703. return distance;
  56704. }
  56705. };
  56706. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  56707. var tm = BABYLON.Tmp.Matrix[0];
  56708. mesh.getWorldMatrix().invertToRef(tm);
  56709. if (this._tmpRay) {
  56710. Ray.TransformToRef(this, tm, this._tmpRay);
  56711. }
  56712. else {
  56713. this._tmpRay = Ray.Transform(this, tm);
  56714. }
  56715. return mesh.intersects(this._tmpRay, fastCheck);
  56716. };
  56717. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  56718. if (results) {
  56719. results.length = 0;
  56720. }
  56721. else {
  56722. results = [];
  56723. }
  56724. for (var i = 0; i < meshes.length; i++) {
  56725. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  56726. if (pickInfo.hit) {
  56727. results.push(pickInfo);
  56728. }
  56729. }
  56730. results.sort(this._comparePickingInfo);
  56731. return results;
  56732. };
  56733. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  56734. if (pickingInfoA.distance < pickingInfoB.distance) {
  56735. return -1;
  56736. }
  56737. else if (pickingInfoA.distance > pickingInfoB.distance) {
  56738. return 1;
  56739. }
  56740. else {
  56741. return 0;
  56742. }
  56743. };
  56744. /**
  56745. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  56746. * @param sega the first point of the segment to test the intersection against
  56747. * @param segb the second point of the segment to test the intersection against
  56748. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  56749. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  56750. */
  56751. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  56752. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  56753. var u = segb.subtract(sega);
  56754. var v = rsegb.subtract(this.origin);
  56755. var w = sega.subtract(this.origin);
  56756. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  56757. var b = BABYLON.Vector3.Dot(u, v);
  56758. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  56759. var d = BABYLON.Vector3.Dot(u, w);
  56760. var e = BABYLON.Vector3.Dot(v, w);
  56761. var D = a * c - b * b; // always >= 0
  56762. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  56763. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  56764. // compute the line parameters of the two closest points
  56765. if (D < Ray.smallnum) { // the lines are almost parallel
  56766. sN = 0.0; // force using point P0 on segment S1
  56767. sD = 1.0; // to prevent possible division by 0.0 later
  56768. tN = e;
  56769. tD = c;
  56770. }
  56771. else { // get the closest points on the infinite lines
  56772. sN = (b * e - c * d);
  56773. tN = (a * e - b * d);
  56774. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  56775. sN = 0.0;
  56776. tN = e;
  56777. tD = c;
  56778. }
  56779. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  56780. sN = sD;
  56781. tN = e + b;
  56782. tD = c;
  56783. }
  56784. }
  56785. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  56786. tN = 0.0;
  56787. // recompute sc for this edge
  56788. if (-d < 0.0) {
  56789. sN = 0.0;
  56790. }
  56791. else if (-d > a)
  56792. sN = sD;
  56793. else {
  56794. sN = -d;
  56795. sD = a;
  56796. }
  56797. }
  56798. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  56799. tN = tD;
  56800. // recompute sc for this edge
  56801. if ((-d + b) < 0.0) {
  56802. sN = 0;
  56803. }
  56804. else if ((-d + b) > a) {
  56805. sN = sD;
  56806. }
  56807. else {
  56808. sN = (-d + b);
  56809. sD = a;
  56810. }
  56811. }
  56812. // finally do the division to get sc and tc
  56813. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  56814. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  56815. // get the difference of the two closest points
  56816. var qtc = v.multiplyByFloats(tc, tc, tc);
  56817. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  56818. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  56819. if (isIntersected) {
  56820. return qtc.length();
  56821. }
  56822. return -1;
  56823. };
  56824. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  56825. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  56826. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  56827. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  56828. this.direction.normalize();
  56829. return this;
  56830. };
  56831. // Statics
  56832. Ray.Zero = function () {
  56833. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  56834. };
  56835. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  56836. var result = Ray.Zero();
  56837. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  56838. };
  56839. /**
  56840. * 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
  56841. * transformed to the given world matrix.
  56842. * @param origin The origin point
  56843. * @param end The end point
  56844. * @param world a matrix to transform the ray to. Default is the identity matrix.
  56845. */
  56846. Ray.CreateNewFromTo = function (origin, end, world) {
  56847. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  56848. var direction = end.subtract(origin);
  56849. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  56850. direction.normalize();
  56851. return Ray.Transform(new Ray(origin, direction, length), world);
  56852. };
  56853. Ray.Transform = function (ray, matrix) {
  56854. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  56855. Ray.TransformToRef(ray, matrix, result);
  56856. return result;
  56857. };
  56858. Ray.TransformToRef = function (ray, matrix, result) {
  56859. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  56860. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  56861. result.length = ray.length;
  56862. var dir = result.direction;
  56863. var len = dir.length();
  56864. if (!(len === 0 || len === 1)) {
  56865. var num = 1.0 / len;
  56866. dir.x *= num;
  56867. dir.y *= num;
  56868. dir.z *= num;
  56869. result.length *= len;
  56870. }
  56871. };
  56872. Ray.smallnum = 0.00000001;
  56873. Ray.rayl = 10e8;
  56874. return Ray;
  56875. }());
  56876. BABYLON.Ray = Ray;
  56877. })(BABYLON || (BABYLON = {}));
  56878. //# sourceMappingURL=babylon.ray.js.map
  56879. var BABYLON;
  56880. (function (BABYLON) {
  56881. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  56882. if (boxMin.x > sphereCenter.x + sphereRadius)
  56883. return false;
  56884. if (sphereCenter.x - sphereRadius > boxMax.x)
  56885. return false;
  56886. if (boxMin.y > sphereCenter.y + sphereRadius)
  56887. return false;
  56888. if (sphereCenter.y - sphereRadius > boxMax.y)
  56889. return false;
  56890. if (boxMin.z > sphereCenter.z + sphereRadius)
  56891. return false;
  56892. if (sphereCenter.z - sphereRadius > boxMax.z)
  56893. return false;
  56894. return true;
  56895. };
  56896. var getLowestRoot = (function () {
  56897. var result = { root: 0, found: false };
  56898. return function (a, b, c, maxR) {
  56899. result.root = 0;
  56900. result.found = false;
  56901. var determinant = b * b - 4.0 * a * c;
  56902. if (determinant < 0)
  56903. return result;
  56904. var sqrtD = Math.sqrt(determinant);
  56905. var r1 = (-b - sqrtD) / (2.0 * a);
  56906. var r2 = (-b + sqrtD) / (2.0 * a);
  56907. if (r1 > r2) {
  56908. var temp = r2;
  56909. r2 = r1;
  56910. r1 = temp;
  56911. }
  56912. if (r1 > 0 && r1 < maxR) {
  56913. result.root = r1;
  56914. result.found = true;
  56915. return result;
  56916. }
  56917. if (r2 > 0 && r2 < maxR) {
  56918. result.root = r2;
  56919. result.found = true;
  56920. return result;
  56921. }
  56922. return result;
  56923. };
  56924. })();
  56925. /** @hidden */
  56926. var Collider = /** @class */ (function () {
  56927. function Collider() {
  56928. this._collisionPoint = BABYLON.Vector3.Zero();
  56929. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  56930. this._tempVector = BABYLON.Vector3.Zero();
  56931. this._tempVector2 = BABYLON.Vector3.Zero();
  56932. this._tempVector3 = BABYLON.Vector3.Zero();
  56933. this._tempVector4 = BABYLON.Vector3.Zero();
  56934. this._edge = BABYLON.Vector3.Zero();
  56935. this._baseToVertex = BABYLON.Vector3.Zero();
  56936. this._destinationPoint = BABYLON.Vector3.Zero();
  56937. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  56938. this._displacementVector = BABYLON.Vector3.Zero();
  56939. /** @hidden */
  56940. this._radius = BABYLON.Vector3.One();
  56941. /** @hidden */
  56942. this._retry = 0;
  56943. /** @hidden */
  56944. this._basePointWorld = BABYLON.Vector3.Zero();
  56945. this._velocityWorld = BABYLON.Vector3.Zero();
  56946. this._normalizedVelocity = BABYLON.Vector3.Zero();
  56947. this._collisionMask = -1;
  56948. }
  56949. Object.defineProperty(Collider.prototype, "collisionMask", {
  56950. get: function () {
  56951. return this._collisionMask;
  56952. },
  56953. set: function (mask) {
  56954. this._collisionMask = !isNaN(mask) ? mask : -1;
  56955. },
  56956. enumerable: true,
  56957. configurable: true
  56958. });
  56959. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  56960. /**
  56961. * Gets the plane normal used to compute the sliding response (in local space)
  56962. */
  56963. get: function () {
  56964. return this._slidePlaneNormal;
  56965. },
  56966. enumerable: true,
  56967. configurable: true
  56968. });
  56969. // Methods
  56970. /** @hidden */
  56971. Collider.prototype._initialize = function (source, dir, e) {
  56972. this._velocity = dir;
  56973. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  56974. this._basePoint = source;
  56975. source.multiplyToRef(this._radius, this._basePointWorld);
  56976. dir.multiplyToRef(this._radius, this._velocityWorld);
  56977. this._velocityWorldLength = this._velocityWorld.length();
  56978. this._epsilon = e;
  56979. this.collisionFound = false;
  56980. };
  56981. /** @hidden */
  56982. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  56983. pa.subtractToRef(point, this._tempVector);
  56984. pb.subtractToRef(point, this._tempVector2);
  56985. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  56986. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  56987. if (d < 0)
  56988. return false;
  56989. pc.subtractToRef(point, this._tempVector3);
  56990. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  56991. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  56992. if (d < 0)
  56993. return false;
  56994. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  56995. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  56996. return d >= 0;
  56997. };
  56998. /** @hidden */
  56999. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  57000. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  57001. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  57002. if (distance > this._velocityWorldLength + max + sphereRadius) {
  57003. return false;
  57004. }
  57005. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  57006. return false;
  57007. return true;
  57008. };
  57009. /** @hidden */
  57010. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  57011. var t0;
  57012. var embeddedInPlane = false;
  57013. //defensive programming, actually not needed.
  57014. if (!trianglePlaneArray) {
  57015. trianglePlaneArray = [];
  57016. }
  57017. if (!trianglePlaneArray[faceIndex]) {
  57018. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  57019. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  57020. }
  57021. var trianglePlane = trianglePlaneArray[faceIndex];
  57022. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  57023. return;
  57024. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  57025. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  57026. if (normalDotVelocity == 0) {
  57027. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  57028. return;
  57029. embeddedInPlane = true;
  57030. t0 = 0;
  57031. }
  57032. else {
  57033. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  57034. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  57035. if (t0 > t1) {
  57036. var temp = t1;
  57037. t1 = t0;
  57038. t0 = temp;
  57039. }
  57040. if (t0 > 1.0 || t1 < 0.0)
  57041. return;
  57042. if (t0 < 0)
  57043. t0 = 0;
  57044. if (t0 > 1.0)
  57045. t0 = 1.0;
  57046. }
  57047. this._collisionPoint.copyFromFloats(0, 0, 0);
  57048. var found = false;
  57049. var t = 1.0;
  57050. if (!embeddedInPlane) {
  57051. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  57052. this._velocity.scaleToRef(t0, this._tempVector);
  57053. this._planeIntersectionPoint.addInPlace(this._tempVector);
  57054. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  57055. found = true;
  57056. t = t0;
  57057. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  57058. }
  57059. }
  57060. if (!found) {
  57061. var velocitySquaredLength = this._velocity.lengthSquared();
  57062. var a = velocitySquaredLength;
  57063. this._basePoint.subtractToRef(p1, this._tempVector);
  57064. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  57065. var c = this._tempVector.lengthSquared() - 1.0;
  57066. var lowestRoot = getLowestRoot(a, b, c, t);
  57067. if (lowestRoot.found) {
  57068. t = lowestRoot.root;
  57069. found = true;
  57070. this._collisionPoint.copyFrom(p1);
  57071. }
  57072. this._basePoint.subtractToRef(p2, this._tempVector);
  57073. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  57074. c = this._tempVector.lengthSquared() - 1.0;
  57075. lowestRoot = getLowestRoot(a, b, c, t);
  57076. if (lowestRoot.found) {
  57077. t = lowestRoot.root;
  57078. found = true;
  57079. this._collisionPoint.copyFrom(p2);
  57080. }
  57081. this._basePoint.subtractToRef(p3, this._tempVector);
  57082. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  57083. c = this._tempVector.lengthSquared() - 1.0;
  57084. lowestRoot = getLowestRoot(a, b, c, t);
  57085. if (lowestRoot.found) {
  57086. t = lowestRoot.root;
  57087. found = true;
  57088. this._collisionPoint.copyFrom(p3);
  57089. }
  57090. p2.subtractToRef(p1, this._edge);
  57091. p1.subtractToRef(this._basePoint, this._baseToVertex);
  57092. var edgeSquaredLength = this._edge.lengthSquared();
  57093. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  57094. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  57095. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  57096. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  57097. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  57098. lowestRoot = getLowestRoot(a, b, c, t);
  57099. if (lowestRoot.found) {
  57100. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  57101. if (f >= 0.0 && f <= 1.0) {
  57102. t = lowestRoot.root;
  57103. found = true;
  57104. this._edge.scaleInPlace(f);
  57105. p1.addToRef(this._edge, this._collisionPoint);
  57106. }
  57107. }
  57108. p3.subtractToRef(p2, this._edge);
  57109. p2.subtractToRef(this._basePoint, this._baseToVertex);
  57110. edgeSquaredLength = this._edge.lengthSquared();
  57111. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  57112. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  57113. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  57114. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  57115. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  57116. lowestRoot = getLowestRoot(a, b, c, t);
  57117. if (lowestRoot.found) {
  57118. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  57119. if (f >= 0.0 && f <= 1.0) {
  57120. t = lowestRoot.root;
  57121. found = true;
  57122. this._edge.scaleInPlace(f);
  57123. p2.addToRef(this._edge, this._collisionPoint);
  57124. }
  57125. }
  57126. p1.subtractToRef(p3, this._edge);
  57127. p3.subtractToRef(this._basePoint, this._baseToVertex);
  57128. edgeSquaredLength = this._edge.lengthSquared();
  57129. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  57130. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  57131. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  57132. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  57133. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  57134. lowestRoot = getLowestRoot(a, b, c, t);
  57135. if (lowestRoot.found) {
  57136. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  57137. if (f >= 0.0 && f <= 1.0) {
  57138. t = lowestRoot.root;
  57139. found = true;
  57140. this._edge.scaleInPlace(f);
  57141. p3.addToRef(this._edge, this._collisionPoint);
  57142. }
  57143. }
  57144. }
  57145. if (found) {
  57146. var distToCollision = t * this._velocity.length();
  57147. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  57148. if (!this.intersectionPoint) {
  57149. this.intersectionPoint = this._collisionPoint.clone();
  57150. }
  57151. else {
  57152. this.intersectionPoint.copyFrom(this._collisionPoint);
  57153. }
  57154. this._nearestDistance = distToCollision;
  57155. this.collisionFound = true;
  57156. }
  57157. }
  57158. };
  57159. /** @hidden */
  57160. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  57161. for (var i = indexStart; i < indexEnd; i += 3) {
  57162. var p1 = pts[indices[i] - decal];
  57163. var p2 = pts[indices[i + 1] - decal];
  57164. var p3 = pts[indices[i + 2] - decal];
  57165. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  57166. }
  57167. };
  57168. /** @hidden */
  57169. Collider.prototype._getResponse = function (pos, vel) {
  57170. pos.addToRef(vel, this._destinationPoint);
  57171. vel.scaleInPlace((this._nearestDistance / vel.length()));
  57172. this._basePoint.addToRef(vel, pos);
  57173. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  57174. this._slidePlaneNormal.normalize();
  57175. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  57176. pos.addInPlace(this._displacementVector);
  57177. this.intersectionPoint.addInPlace(this._displacementVector);
  57178. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  57179. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  57180. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  57181. };
  57182. return Collider;
  57183. }());
  57184. BABYLON.Collider = Collider;
  57185. })(BABYLON || (BABYLON = {}));
  57186. //# sourceMappingURL=babylon.collider.js.map
  57187. var BABYLON;
  57188. (function (BABYLON) {
  57189. //WebWorker code will be inserted to this variable.
  57190. /** @hidden */
  57191. BABYLON.CollisionWorker = "";
  57192. /** Defines supported task for worker process */
  57193. var WorkerTaskType;
  57194. (function (WorkerTaskType) {
  57195. /** Initialization */
  57196. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  57197. /** Update of geometry */
  57198. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  57199. /** Evaluate collision */
  57200. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  57201. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  57202. /** Defines kind of replies returned by worker */
  57203. var WorkerReplyType;
  57204. (function (WorkerReplyType) {
  57205. /** Success */
  57206. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  57207. /** Unkown error */
  57208. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  57209. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  57210. /** @hidden */
  57211. var CollisionCoordinatorWorker = /** @class */ (function () {
  57212. function CollisionCoordinatorWorker() {
  57213. var _this = this;
  57214. this._scaledPosition = BABYLON.Vector3.Zero();
  57215. this._scaledVelocity = BABYLON.Vector3.Zero();
  57216. this.onMeshUpdated = function (transformNode) {
  57217. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  57218. };
  57219. this.onGeometryUpdated = function (geometry) {
  57220. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  57221. };
  57222. this._afterRender = function () {
  57223. if (!_this._init)
  57224. return;
  57225. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  57226. return;
  57227. }
  57228. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  57229. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  57230. if (_this._runningUpdated > 4) {
  57231. return;
  57232. }
  57233. ++_this._runningUpdated;
  57234. var payload = {
  57235. updatedMeshes: _this._addUpdateMeshesList,
  57236. updatedGeometries: _this._addUpdateGeometriesList,
  57237. removedGeometries: _this._toRemoveGeometryArray,
  57238. removedMeshes: _this._toRemoveMeshesArray
  57239. };
  57240. var message = {
  57241. payload: payload,
  57242. taskType: WorkerTaskType.UPDATE
  57243. };
  57244. var serializable = [];
  57245. for (var id in payload.updatedGeometries) {
  57246. if (payload.updatedGeometries.hasOwnProperty(id)) {
  57247. //prepare transferables
  57248. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  57249. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  57250. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  57251. }
  57252. }
  57253. _this._worker.postMessage(message, serializable);
  57254. _this._addUpdateMeshesList = {};
  57255. _this._addUpdateGeometriesList = {};
  57256. _this._toRemoveGeometryArray = [];
  57257. _this._toRemoveMeshesArray = [];
  57258. };
  57259. this._onMessageFromWorker = function (e) {
  57260. var returnData = e.data;
  57261. if (returnData.error != WorkerReplyType.SUCCESS) {
  57262. //TODO what errors can be returned from the worker?
  57263. BABYLON.Tools.Warn("error returned from worker!");
  57264. return;
  57265. }
  57266. switch (returnData.taskType) {
  57267. case WorkerTaskType.INIT:
  57268. _this._init = true;
  57269. //Update the worked with ALL of the scene's current state
  57270. _this._scene.meshes.forEach(function (mesh) {
  57271. _this.onMeshAdded(mesh);
  57272. });
  57273. _this._scene.getGeometries().forEach(function (geometry) {
  57274. _this.onGeometryAdded(geometry);
  57275. });
  57276. break;
  57277. case WorkerTaskType.UPDATE:
  57278. _this._runningUpdated--;
  57279. break;
  57280. case WorkerTaskType.COLLIDE:
  57281. var returnPayload = returnData.payload;
  57282. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  57283. return;
  57284. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  57285. if (callback) {
  57286. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  57287. if (mesh) {
  57288. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  57289. }
  57290. }
  57291. //cleanup
  57292. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  57293. break;
  57294. }
  57295. };
  57296. this._collisionsCallbackArray = [];
  57297. this._init = false;
  57298. this._runningUpdated = 0;
  57299. this._addUpdateMeshesList = {};
  57300. this._addUpdateGeometriesList = {};
  57301. this._toRemoveGeometryArray = [];
  57302. this._toRemoveMeshesArray = [];
  57303. }
  57304. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  57305. if (!this._init)
  57306. return;
  57307. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  57308. return;
  57309. position.divideToRef(collider._radius, this._scaledPosition);
  57310. displacement.divideToRef(collider._radius, this._scaledVelocity);
  57311. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  57312. var payload = {
  57313. collider: {
  57314. position: this._scaledPosition.asArray(),
  57315. velocity: this._scaledVelocity.asArray(),
  57316. radius: collider._radius.asArray()
  57317. },
  57318. collisionId: collisionIndex,
  57319. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  57320. maximumRetry: maximumRetry
  57321. };
  57322. var message = {
  57323. payload: payload,
  57324. taskType: WorkerTaskType.COLLIDE
  57325. };
  57326. this._worker.postMessage(message);
  57327. };
  57328. CollisionCoordinatorWorker.prototype.init = function (scene) {
  57329. this._scene = scene;
  57330. this._scene.registerAfterRender(this._afterRender);
  57331. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  57332. this._worker = new Worker(workerUrl);
  57333. this._worker.onmessage = this._onMessageFromWorker;
  57334. var message = {
  57335. payload: {},
  57336. taskType: WorkerTaskType.INIT
  57337. };
  57338. this._worker.postMessage(message);
  57339. };
  57340. CollisionCoordinatorWorker.prototype.destroy = function () {
  57341. this._scene.unregisterAfterRender(this._afterRender);
  57342. this._worker.terminate();
  57343. };
  57344. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  57345. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  57346. this.onMeshUpdated(mesh);
  57347. };
  57348. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  57349. this._toRemoveMeshesArray.push(mesh.uniqueId);
  57350. };
  57351. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  57352. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  57353. geometry.onGeometryUpdated = this.onGeometryUpdated;
  57354. this.onGeometryUpdated(geometry);
  57355. };
  57356. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  57357. this._toRemoveGeometryArray.push(geometry.id);
  57358. };
  57359. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  57360. var submeshes = [];
  57361. if (mesh.subMeshes) {
  57362. submeshes = mesh.subMeshes.map(function (sm, idx) {
  57363. var boundingInfo = sm.getBoundingInfo();
  57364. return {
  57365. position: idx,
  57366. verticesStart: sm.verticesStart,
  57367. verticesCount: sm.verticesCount,
  57368. indexStart: sm.indexStart,
  57369. indexCount: sm.indexCount,
  57370. hasMaterial: !!sm.getMaterial(),
  57371. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  57372. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  57373. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  57374. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  57375. };
  57376. });
  57377. }
  57378. var geometryId = null;
  57379. if (mesh instanceof BABYLON.Mesh) {
  57380. var geometry = mesh.geometry;
  57381. geometryId = geometry ? geometry.id : null;
  57382. }
  57383. else if (mesh instanceof BABYLON.InstancedMesh) {
  57384. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  57385. geometryId = geometry ? geometry.id : null;
  57386. }
  57387. var boundingInfo = mesh.getBoundingInfo();
  57388. return {
  57389. uniqueId: mesh.uniqueId,
  57390. id: mesh.id,
  57391. name: mesh.name,
  57392. geometryId: geometryId,
  57393. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  57394. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  57395. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  57396. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  57397. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  57398. subMeshes: submeshes,
  57399. checkCollisions: mesh.checkCollisions
  57400. };
  57401. };
  57402. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  57403. return {
  57404. id: geometry.id,
  57405. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  57406. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  57407. indices: new Uint32Array(geometry.getIndices() || []),
  57408. };
  57409. };
  57410. return CollisionCoordinatorWorker;
  57411. }());
  57412. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  57413. /** @hidden */
  57414. var CollisionCoordinatorLegacy = /** @class */ (function () {
  57415. function CollisionCoordinatorLegacy() {
  57416. this._scaledPosition = BABYLON.Vector3.Zero();
  57417. this._scaledVelocity = BABYLON.Vector3.Zero();
  57418. this._finalPosition = BABYLON.Vector3.Zero();
  57419. }
  57420. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  57421. position.divideToRef(collider._radius, this._scaledPosition);
  57422. displacement.divideToRef(collider._radius, this._scaledVelocity);
  57423. collider.collidedMesh = null;
  57424. collider._retry = 0;
  57425. collider._initialVelocity = this._scaledVelocity;
  57426. collider._initialPosition = this._scaledPosition;
  57427. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  57428. this._finalPosition.multiplyInPlace(collider._radius);
  57429. //run the callback
  57430. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  57431. };
  57432. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  57433. this._scene = scene;
  57434. };
  57435. CollisionCoordinatorLegacy.prototype.destroy = function () {
  57436. //Legacy need no destruction method.
  57437. };
  57438. //No update in legacy mode
  57439. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  57440. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  57441. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  57442. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  57443. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  57444. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  57445. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  57446. if (excludedMesh === void 0) { excludedMesh = null; }
  57447. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  57448. if (collider._retry >= maximumRetry) {
  57449. finalPosition.copyFrom(position);
  57450. return;
  57451. }
  57452. // Check if this is a mesh else camera or -1
  57453. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  57454. collider._initialize(position, velocity, closeDistance);
  57455. // Check all meshes
  57456. for (var index = 0; index < this._scene.meshes.length; index++) {
  57457. var mesh = this._scene.meshes[index];
  57458. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  57459. mesh._checkCollision(collider);
  57460. }
  57461. }
  57462. if (!collider.collisionFound) {
  57463. position.addToRef(velocity, finalPosition);
  57464. return;
  57465. }
  57466. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  57467. collider._getResponse(position, velocity);
  57468. }
  57469. if (velocity.length() <= closeDistance) {
  57470. finalPosition.copyFrom(position);
  57471. return;
  57472. }
  57473. collider._retry++;
  57474. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  57475. };
  57476. return CollisionCoordinatorLegacy;
  57477. }());
  57478. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  57479. })(BABYLON || (BABYLON = {}));
  57480. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  57481. var BABYLON;
  57482. (function (BABYLON) {
  57483. /**
  57484. * A particle represents one of the element emitted by a particle system.
  57485. * This is mainly define by its coordinates, direction, velocity and age.
  57486. */
  57487. var Particle = /** @class */ (function () {
  57488. /**
  57489. * Creates a new instance Particle
  57490. * @param particleSystem the particle system the particle belongs to
  57491. */
  57492. function Particle(
  57493. /**
  57494. * The particle system the particle belongs to.
  57495. */
  57496. particleSystem) {
  57497. this.particleSystem = particleSystem;
  57498. /**
  57499. * The world position of the particle in the scene.
  57500. */
  57501. this.position = BABYLON.Vector3.Zero();
  57502. /**
  57503. * The world direction of the particle in the scene.
  57504. */
  57505. this.direction = BABYLON.Vector3.Zero();
  57506. /**
  57507. * The color of the particle.
  57508. */
  57509. this.color = new BABYLON.Color4(0, 0, 0, 0);
  57510. /**
  57511. * The color change of the particle per step.
  57512. */
  57513. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  57514. /**
  57515. * Defines how long will the life of the particle be.
  57516. */
  57517. this.lifeTime = 1.0;
  57518. /**
  57519. * The current age of the particle.
  57520. */
  57521. this.age = 0;
  57522. /**
  57523. * The current size of the particle.
  57524. */
  57525. this.size = 0;
  57526. /**
  57527. * The current scale of the particle.
  57528. */
  57529. this.scale = new BABYLON.Vector2(1, 1);
  57530. /**
  57531. * The current angle of the particle.
  57532. */
  57533. this.angle = 0;
  57534. /**
  57535. * Defines how fast is the angle changing.
  57536. */
  57537. this.angularSpeed = 0;
  57538. /**
  57539. * Defines the cell index used by the particle to be rendered from a sprite.
  57540. */
  57541. this.cellIndex = 0;
  57542. /** @hidden */
  57543. this._attachedSubEmitters = null;
  57544. /** @hidden */
  57545. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  57546. /** @hidden */
  57547. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  57548. /** @hidden */
  57549. this._currentSize1 = 0;
  57550. /** @hidden */
  57551. this._currentSize2 = 0;
  57552. /** @hidden */
  57553. this._currentAngularSpeed1 = 0;
  57554. /** @hidden */
  57555. this._currentAngularSpeed2 = 0;
  57556. /** @hidden */
  57557. this._currentVelocity1 = 0;
  57558. /** @hidden */
  57559. this._currentVelocity2 = 0;
  57560. /** @hidden */
  57561. this._currentLimitVelocity1 = 0;
  57562. /** @hidden */
  57563. this._currentLimitVelocity2 = 0;
  57564. /** @hidden */
  57565. this._currentDrag1 = 0;
  57566. /** @hidden */
  57567. this._currentDrag2 = 0;
  57568. this.id = Particle._Count++;
  57569. if (!this.particleSystem.isAnimationSheetEnabled) {
  57570. return;
  57571. }
  57572. this.updateCellInfoFromSystem();
  57573. }
  57574. Particle.prototype.updateCellInfoFromSystem = function () {
  57575. this.cellIndex = this.particleSystem.startSpriteCellID;
  57576. };
  57577. /**
  57578. * Defines how the sprite cell index is updated for the particle
  57579. */
  57580. Particle.prototype.updateCellIndex = function () {
  57581. var offsetAge = this.age;
  57582. var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
  57583. if (this.particleSystem.spriteRandomStartCell) {
  57584. if (this._randomCellOffset === undefined) {
  57585. this._randomCellOffset = Math.random() * this.lifeTime;
  57586. }
  57587. if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
  57588. changeSpeed = 1;
  57589. offsetAge = this._randomCellOffset;
  57590. }
  57591. else {
  57592. offsetAge += this._randomCellOffset;
  57593. }
  57594. }
  57595. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  57596. var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
  57597. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  57598. };
  57599. /** @hidden */
  57600. Particle.prototype._inheritParticleInfoToSubEmitter = function (subEmitter) {
  57601. if (subEmitter.particleSystem.emitter.position) {
  57602. var emitterMesh = subEmitter.particleSystem.emitter;
  57603. emitterMesh.position.copyFrom(this.position);
  57604. if (subEmitter.inheritDirection) {
  57605. emitterMesh.position.subtractToRef(this.direction, BABYLON.Tmp.Vector3[0]);
  57606. // Look at using Y as forward
  57607. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  57608. }
  57609. }
  57610. else {
  57611. var emitterPosition = subEmitter.particleSystem.emitter;
  57612. emitterPosition.copyFrom(this.position);
  57613. }
  57614. // Set inheritedVelocityOffset to be used when new particles are created
  57615. this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  57616. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  57617. };
  57618. /** @hidden */
  57619. Particle.prototype._inheritParticleInfoToSubEmitters = function () {
  57620. var _this = this;
  57621. if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {
  57622. this._attachedSubEmitters.forEach(function (subEmitter) {
  57623. _this._inheritParticleInfoToSubEmitter(subEmitter);
  57624. });
  57625. }
  57626. };
  57627. /** @hidden */
  57628. Particle.prototype._reset = function () {
  57629. this.age = 0;
  57630. this._currentColorGradient = null;
  57631. this._currentSizeGradient = null;
  57632. this._currentAngularSpeedGradient = null;
  57633. this._currentVelocityGradient = null;
  57634. this._currentLimitVelocityGradient = null;
  57635. this._currentDragGradient = null;
  57636. this.cellIndex = this.particleSystem.startSpriteCellID;
  57637. this._randomCellOffset = undefined;
  57638. };
  57639. /**
  57640. * Copy the properties of particle to another one.
  57641. * @param other the particle to copy the information to.
  57642. */
  57643. Particle.prototype.copyTo = function (other) {
  57644. other.position.copyFrom(this.position);
  57645. if (this._initialDirection) {
  57646. if (other._initialDirection) {
  57647. other._initialDirection.copyFrom(this._initialDirection);
  57648. }
  57649. else {
  57650. other._initialDirection = this._initialDirection.clone();
  57651. }
  57652. }
  57653. else {
  57654. other._initialDirection = null;
  57655. }
  57656. other.direction.copyFrom(this.direction);
  57657. other.color.copyFrom(this.color);
  57658. other.colorStep.copyFrom(this.colorStep);
  57659. other.lifeTime = this.lifeTime;
  57660. other.age = this.age;
  57661. other._randomCellOffset = this._randomCellOffset;
  57662. other.size = this.size;
  57663. other.scale.copyFrom(this.scale);
  57664. other.angle = this.angle;
  57665. other.angularSpeed = this.angularSpeed;
  57666. other.particleSystem = this.particleSystem;
  57667. other.cellIndex = this.cellIndex;
  57668. other.id = this.id;
  57669. other._attachedSubEmitters = this._attachedSubEmitters;
  57670. if (this._currentColorGradient) {
  57671. other._currentColorGradient = this._currentColorGradient;
  57672. other._currentColor1.copyFrom(this._currentColor1);
  57673. other._currentColor2.copyFrom(this._currentColor2);
  57674. }
  57675. if (this._currentSizeGradient) {
  57676. other._currentSizeGradient = this._currentSizeGradient;
  57677. other._currentSize1 = this._currentSize1;
  57678. other._currentSize2 = this._currentSize2;
  57679. }
  57680. if (this._currentAngularSpeedGradient) {
  57681. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  57682. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  57683. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  57684. }
  57685. if (this._currentVelocityGradient) {
  57686. other._currentVelocityGradient = this._currentVelocityGradient;
  57687. other._currentVelocity1 = this._currentVelocity1;
  57688. other._currentVelocity2 = this._currentVelocity2;
  57689. }
  57690. if (this._currentLimitVelocityGradient) {
  57691. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  57692. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  57693. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  57694. }
  57695. if (this._currentDragGradient) {
  57696. other._currentDragGradient = this._currentDragGradient;
  57697. other._currentDrag1 = this._currentDrag1;
  57698. other._currentDrag2 = this._currentDrag2;
  57699. }
  57700. if (this.particleSystem.isAnimationSheetEnabled) {
  57701. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  57702. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  57703. }
  57704. if (this.particleSystem.useRampGradients) {
  57705. other.remapData.copyFrom(this.remapData);
  57706. }
  57707. if (this._randomNoiseCoordinates1) {
  57708. if (other._randomNoiseCoordinates1) {
  57709. other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1);
  57710. other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2);
  57711. }
  57712. else {
  57713. other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone();
  57714. other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone();
  57715. }
  57716. }
  57717. };
  57718. Particle._Count = 0;
  57719. return Particle;
  57720. }());
  57721. BABYLON.Particle = Particle;
  57722. })(BABYLON || (BABYLON = {}));
  57723. //# sourceMappingURL=babylon.particle.js.map
  57724. var BABYLON;
  57725. (function (BABYLON) {
  57726. /**
  57727. * This represents the base class for particle system in Babylon.
  57728. * 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.
  57729. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  57730. * @example https://doc.babylonjs.com/babylon101/particles
  57731. */
  57732. var BaseParticleSystem = /** @class */ (function () {
  57733. /**
  57734. * Instantiates a particle system.
  57735. * 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.
  57736. * @param name The name of the particle system
  57737. */
  57738. function BaseParticleSystem(name) {
  57739. /**
  57740. * List of animations used by the particle system.
  57741. */
  57742. this.animations = [];
  57743. /**
  57744. * The rendering group used by the Particle system to chose when to render.
  57745. */
  57746. this.renderingGroupId = 0;
  57747. /**
  57748. * The emitter represents the Mesh or position we are attaching the particle system to.
  57749. */
  57750. this.emitter = null;
  57751. /**
  57752. * The maximum number of particles to emit per frame
  57753. */
  57754. this.emitRate = 10;
  57755. /**
  57756. * If you want to launch only a few particles at once, that can be done, as well.
  57757. */
  57758. this.manualEmitCount = -1;
  57759. /**
  57760. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57761. */
  57762. this.updateSpeed = 0.01;
  57763. /**
  57764. * The amount of time the particle system is running (depends of the overall update speed).
  57765. */
  57766. this.targetStopDuration = 0;
  57767. /**
  57768. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  57769. */
  57770. this.disposeOnStop = false;
  57771. /**
  57772. * Minimum power of emitting particles.
  57773. */
  57774. this.minEmitPower = 1;
  57775. /**
  57776. * Maximum power of emitting particles.
  57777. */
  57778. this.maxEmitPower = 1;
  57779. /**
  57780. * Minimum life time of emitting particles.
  57781. */
  57782. this.minLifeTime = 1;
  57783. /**
  57784. * Maximum life time of emitting particles.
  57785. */
  57786. this.maxLifeTime = 1;
  57787. /**
  57788. * Minimum Size of emitting particles.
  57789. */
  57790. this.minSize = 1;
  57791. /**
  57792. * Maximum Size of emitting particles.
  57793. */
  57794. this.maxSize = 1;
  57795. /**
  57796. * Minimum scale of emitting particles on X axis.
  57797. */
  57798. this.minScaleX = 1;
  57799. /**
  57800. * Maximum scale of emitting particles on X axis.
  57801. */
  57802. this.maxScaleX = 1;
  57803. /**
  57804. * Minimum scale of emitting particles on Y axis.
  57805. */
  57806. this.minScaleY = 1;
  57807. /**
  57808. * Maximum scale of emitting particles on Y axis.
  57809. */
  57810. this.maxScaleY = 1;
  57811. /**
  57812. * Gets or sets the minimal initial rotation in radians.
  57813. */
  57814. this.minInitialRotation = 0;
  57815. /**
  57816. * Gets or sets the maximal initial rotation in radians.
  57817. */
  57818. this.maxInitialRotation = 0;
  57819. /**
  57820. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  57821. */
  57822. this.minAngularSpeed = 0;
  57823. /**
  57824. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  57825. */
  57826. this.maxAngularSpeed = 0;
  57827. /**
  57828. * The layer mask we are rendering the particles through.
  57829. */
  57830. this.layerMask = 0x0FFFFFFF;
  57831. /**
  57832. * This can help using your own shader to render the particle system.
  57833. * The according effect will be created
  57834. */
  57835. this.customShader = null;
  57836. /**
  57837. * By default particle system starts as soon as they are created. This prevents the
  57838. * automatic start to happen and let you decide when to start emitting particles.
  57839. */
  57840. this.preventAutoStart = false;
  57841. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  57842. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  57843. /**
  57844. * Callback triggered when the particle animation is ending.
  57845. */
  57846. this.onAnimationEnd = null;
  57847. /**
  57848. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57849. */
  57850. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57851. /**
  57852. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57853. * to override the particles.
  57854. */
  57855. this.forceDepthWrite = false;
  57856. /** 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 */
  57857. this.preWarmCycles = 0;
  57858. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  57859. this.preWarmStepOffset = 1;
  57860. /**
  57861. * 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)
  57862. */
  57863. this.spriteCellChangeSpeed = 1;
  57864. /**
  57865. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  57866. */
  57867. this.startSpriteCellID = 0;
  57868. /**
  57869. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  57870. */
  57871. this.endSpriteCellID = 0;
  57872. /**
  57873. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  57874. */
  57875. this.spriteCellWidth = 0;
  57876. /**
  57877. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  57878. */
  57879. this.spriteCellHeight = 0;
  57880. /**
  57881. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  57882. */
  57883. this.spriteRandomStartCell = false;
  57884. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  57885. this.translationPivot = new BABYLON.Vector2(0, 0);
  57886. /**
  57887. * Gets or sets a boolean indicating that hosted animations (in the system.animations array) must be started when system.start() is called
  57888. */
  57889. this.beginAnimationOnStart = false;
  57890. /**
  57891. * Gets or sets the frame to start the animation from when beginAnimationOnStart is true
  57892. */
  57893. this.beginAnimationFrom = 0;
  57894. /**
  57895. * Gets or sets the frame to end the animation on when beginAnimationOnStart is true
  57896. */
  57897. this.beginAnimationTo = 60;
  57898. /**
  57899. * Gets or sets a boolean indicating if animations must loop when beginAnimationOnStart is true
  57900. */
  57901. this.beginAnimationLoop = false;
  57902. /**
  57903. * You can use gravity if you want to give an orientation to your particles.
  57904. */
  57905. this.gravity = BABYLON.Vector3.Zero();
  57906. this._colorGradients = null;
  57907. this._sizeGradients = null;
  57908. this._lifeTimeGradients = null;
  57909. this._angularSpeedGradients = null;
  57910. this._velocityGradients = null;
  57911. this._limitVelocityGradients = null;
  57912. this._dragGradients = null;
  57913. this._emitRateGradients = null;
  57914. this._startSizeGradients = null;
  57915. this._rampGradients = null;
  57916. this._colorRemapGradients = null;
  57917. this._alphaRemapGradients = null;
  57918. /**
  57919. * Defines the delay in milliseconds before starting the system (0 by default)
  57920. */
  57921. this.startDelay = 0;
  57922. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  57923. this.limitVelocityDamping = 0.4;
  57924. /**
  57925. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  57926. */
  57927. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57928. /**
  57929. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  57930. */
  57931. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57932. /**
  57933. * Color the particle will have at the end of its lifetime
  57934. */
  57935. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  57936. /**
  57937. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  57938. */
  57939. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57940. /** @hidden */
  57941. this._isSubEmitter = false;
  57942. /**
  57943. * Gets or sets the billboard mode to use when isBillboardBased = true.
  57944. * Value can be: ParticleSystem.BILLBOARDMODE_ALL, ParticleSystem.BILLBOARDMODE_Y, ParticleSystem.BILLBOARDMODE_STRETCHED
  57945. */
  57946. this.billboardMode = BABYLON.ParticleSystem.BILLBOARDMODE_ALL;
  57947. this._isBillboardBased = true;
  57948. /**
  57949. * Local cache of defines for image processing.
  57950. */
  57951. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  57952. this.id = name;
  57953. this.name = name;
  57954. }
  57955. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  57956. /**
  57957. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  57958. */
  57959. get: function () {
  57960. return this._isAnimationSheetEnabled;
  57961. },
  57962. set: function (value) {
  57963. if (this._isAnimationSheetEnabled == value) {
  57964. return;
  57965. }
  57966. this._isAnimationSheetEnabled = value;
  57967. this._reset();
  57968. },
  57969. enumerable: true,
  57970. configurable: true
  57971. });
  57972. /**
  57973. * Get hosting scene
  57974. * @returns the scene
  57975. */
  57976. BaseParticleSystem.prototype.getScene = function () {
  57977. return this._scene;
  57978. };
  57979. BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
  57980. return (this._startSizeGradients && this._startSizeGradients.length > 0)
  57981. || (this._emitRateGradients && this._emitRateGradients.length > 0)
  57982. || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
  57983. };
  57984. /**
  57985. * Gets the current list of drag gradients.
  57986. * You must use addDragGradient and removeDragGradient to udpate this list
  57987. * @returns the list of drag gradients
  57988. */
  57989. BaseParticleSystem.prototype.getDragGradients = function () {
  57990. return this._dragGradients;
  57991. };
  57992. /**
  57993. * Gets the current list of limit velocity gradients.
  57994. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  57995. * @returns the list of limit velocity gradients
  57996. */
  57997. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  57998. return this._limitVelocityGradients;
  57999. };
  58000. /**
  58001. * Gets the current list of color gradients.
  58002. * You must use addColorGradient and removeColorGradient to udpate this list
  58003. * @returns the list of color gradients
  58004. */
  58005. BaseParticleSystem.prototype.getColorGradients = function () {
  58006. return this._colorGradients;
  58007. };
  58008. /**
  58009. * Gets the current list of size gradients.
  58010. * You must use addSizeGradient and removeSizeGradient to udpate this list
  58011. * @returns the list of size gradients
  58012. */
  58013. BaseParticleSystem.prototype.getSizeGradients = function () {
  58014. return this._sizeGradients;
  58015. };
  58016. /**
  58017. * Gets the current list of color remap gradients.
  58018. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  58019. * @returns the list of color remap gradients
  58020. */
  58021. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  58022. return this._colorRemapGradients;
  58023. };
  58024. /**
  58025. * Gets the current list of alpha remap gradients.
  58026. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  58027. * @returns the list of alpha remap gradients
  58028. */
  58029. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  58030. return this._alphaRemapGradients;
  58031. };
  58032. /**
  58033. * Gets the current list of life time gradients.
  58034. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  58035. * @returns the list of life time gradients
  58036. */
  58037. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  58038. return this._lifeTimeGradients;
  58039. };
  58040. /**
  58041. * Gets the current list of angular speed gradients.
  58042. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  58043. * @returns the list of angular speed gradients
  58044. */
  58045. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  58046. return this._angularSpeedGradients;
  58047. };
  58048. /**
  58049. * Gets the current list of velocity gradients.
  58050. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  58051. * @returns the list of velocity gradients
  58052. */
  58053. BaseParticleSystem.prototype.getVelocityGradients = function () {
  58054. return this._velocityGradients;
  58055. };
  58056. /**
  58057. * Gets the current list of start size gradients.
  58058. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  58059. * @returns the list of start size gradients
  58060. */
  58061. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  58062. return this._startSizeGradients;
  58063. };
  58064. /**
  58065. * Gets the current list of emit rate gradients.
  58066. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  58067. * @returns the list of emit rate gradients
  58068. */
  58069. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  58070. return this._emitRateGradients;
  58071. };
  58072. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  58073. /**
  58074. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58075. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58076. */
  58077. get: function () {
  58078. if (this.particleEmitterType.direction1) {
  58079. return this.particleEmitterType.direction1;
  58080. }
  58081. return BABYLON.Vector3.Zero();
  58082. },
  58083. set: function (value) {
  58084. if (this.particleEmitterType.direction1) {
  58085. this.particleEmitterType.direction1 = value;
  58086. }
  58087. },
  58088. enumerable: true,
  58089. configurable: true
  58090. });
  58091. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  58092. /**
  58093. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58094. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58095. */
  58096. get: function () {
  58097. if (this.particleEmitterType.direction2) {
  58098. return this.particleEmitterType.direction2;
  58099. }
  58100. return BABYLON.Vector3.Zero();
  58101. },
  58102. set: function (value) {
  58103. if (this.particleEmitterType.direction2) {
  58104. this.particleEmitterType.direction2 = value;
  58105. }
  58106. },
  58107. enumerable: true,
  58108. configurable: true
  58109. });
  58110. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  58111. /**
  58112. * 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.
  58113. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58114. */
  58115. get: function () {
  58116. if (this.particleEmitterType.minEmitBox) {
  58117. return this.particleEmitterType.minEmitBox;
  58118. }
  58119. return BABYLON.Vector3.Zero();
  58120. },
  58121. set: function (value) {
  58122. if (this.particleEmitterType.minEmitBox) {
  58123. this.particleEmitterType.minEmitBox = value;
  58124. }
  58125. },
  58126. enumerable: true,
  58127. configurable: true
  58128. });
  58129. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  58130. /**
  58131. * 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.
  58132. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58133. */
  58134. get: function () {
  58135. if (this.particleEmitterType.maxEmitBox) {
  58136. return this.particleEmitterType.maxEmitBox;
  58137. }
  58138. return BABYLON.Vector3.Zero();
  58139. },
  58140. set: function (value) {
  58141. if (this.particleEmitterType.maxEmitBox) {
  58142. this.particleEmitterType.maxEmitBox = value;
  58143. }
  58144. },
  58145. enumerable: true,
  58146. configurable: true
  58147. });
  58148. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  58149. /**
  58150. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  58151. */
  58152. get: function () {
  58153. return this._isBillboardBased;
  58154. },
  58155. set: function (value) {
  58156. if (this._isBillboardBased === value) {
  58157. return;
  58158. }
  58159. this._isBillboardBased = value;
  58160. this._reset();
  58161. },
  58162. enumerable: true,
  58163. configurable: true
  58164. });
  58165. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  58166. /**
  58167. * Gets the image processing configuration used either in this material.
  58168. */
  58169. get: function () {
  58170. return this._imageProcessingConfiguration;
  58171. },
  58172. /**
  58173. * Sets the Default image processing configuration used either in the this material.
  58174. *
  58175. * If sets to null, the scene one is in use.
  58176. */
  58177. set: function (value) {
  58178. this._attachImageProcessingConfiguration(value);
  58179. },
  58180. enumerable: true,
  58181. configurable: true
  58182. });
  58183. /**
  58184. * Attaches a new image processing configuration to the Standard Material.
  58185. * @param configuration
  58186. */
  58187. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  58188. if (configuration === this._imageProcessingConfiguration) {
  58189. return;
  58190. }
  58191. // Pick the scene configuration if needed.
  58192. if (!configuration) {
  58193. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  58194. }
  58195. else {
  58196. this._imageProcessingConfiguration = configuration;
  58197. }
  58198. };
  58199. /** @hidden */
  58200. BaseParticleSystem.prototype._reset = function () {
  58201. };
  58202. /** @hidden */
  58203. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  58204. if (!gradients) {
  58205. return this;
  58206. }
  58207. var index = 0;
  58208. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  58209. var valueGradient = gradients_1[_i];
  58210. if (valueGradient.gradient === gradient) {
  58211. gradients.splice(index, 1);
  58212. break;
  58213. }
  58214. index++;
  58215. }
  58216. if (texture) {
  58217. texture.dispose();
  58218. }
  58219. return this;
  58220. };
  58221. /**
  58222. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  58223. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  58224. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  58225. * @returns the emitter
  58226. */
  58227. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  58228. var particleEmitter = new BABYLON.PointParticleEmitter();
  58229. particleEmitter.direction1 = direction1;
  58230. particleEmitter.direction2 = direction2;
  58231. this.particleEmitterType = particleEmitter;
  58232. return particleEmitter;
  58233. };
  58234. /**
  58235. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  58236. * @param radius The radius of the hemisphere to emit from
  58237. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  58238. * @returns the emitter
  58239. */
  58240. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  58241. if (radius === void 0) { radius = 1; }
  58242. if (radiusRange === void 0) { radiusRange = 1; }
  58243. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  58244. this.particleEmitterType = particleEmitter;
  58245. return particleEmitter;
  58246. };
  58247. /**
  58248. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  58249. * @param radius The radius of the sphere to emit from
  58250. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  58251. * @returns the emitter
  58252. */
  58253. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  58254. if (radius === void 0) { radius = 1; }
  58255. if (radiusRange === void 0) { radiusRange = 1; }
  58256. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  58257. this.particleEmitterType = particleEmitter;
  58258. return particleEmitter;
  58259. };
  58260. /**
  58261. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  58262. * @param radius The radius of the sphere to emit from
  58263. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  58264. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  58265. * @returns the emitter
  58266. */
  58267. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  58268. if (radius === void 0) { radius = 1; }
  58269. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  58270. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  58271. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  58272. this.particleEmitterType = particleEmitter;
  58273. return particleEmitter;
  58274. };
  58275. /**
  58276. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  58277. * @param radius The radius of the emission cylinder
  58278. * @param height The height of the emission cylinder
  58279. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  58280. * @param directionRandomizer How much to randomize the particle direction [0-1]
  58281. * @returns the emitter
  58282. */
  58283. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  58284. if (radius === void 0) { radius = 1; }
  58285. if (height === void 0) { height = 1; }
  58286. if (radiusRange === void 0) { radiusRange = 1; }
  58287. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58288. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  58289. this.particleEmitterType = particleEmitter;
  58290. return particleEmitter;
  58291. };
  58292. /**
  58293. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  58294. * @param radius The radius of the cylinder to emit from
  58295. * @param height The height of the emission cylinder
  58296. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58297. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  58298. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  58299. * @returns the emitter
  58300. */
  58301. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  58302. if (radius === void 0) { radius = 1; }
  58303. if (height === void 0) { height = 1; }
  58304. if (radiusRange === void 0) { radiusRange = 1; }
  58305. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  58306. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  58307. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  58308. this.particleEmitterType = particleEmitter;
  58309. return particleEmitter;
  58310. };
  58311. /**
  58312. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  58313. * @param radius The radius of the cone to emit from
  58314. * @param angle The base angle of the cone
  58315. * @returns the emitter
  58316. */
  58317. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  58318. if (radius === void 0) { radius = 1; }
  58319. if (angle === void 0) { angle = Math.PI / 4; }
  58320. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  58321. this.particleEmitterType = particleEmitter;
  58322. return particleEmitter;
  58323. };
  58324. /**
  58325. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  58326. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  58327. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  58328. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  58329. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  58330. * @returns the emitter
  58331. */
  58332. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  58333. var particleEmitter = new BABYLON.BoxParticleEmitter();
  58334. this.particleEmitterType = particleEmitter;
  58335. this.direction1 = direction1;
  58336. this.direction2 = direction2;
  58337. this.minEmitBox = minEmitBox;
  58338. this.maxEmitBox = maxEmitBox;
  58339. return particleEmitter;
  58340. };
  58341. /**
  58342. * Source color is added to the destination color without alpha affecting the result
  58343. */
  58344. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  58345. /**
  58346. * Blend current color and particle color using particle’s alpha
  58347. */
  58348. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  58349. /**
  58350. * Add current color and particle color multiplied by particle’s alpha
  58351. */
  58352. BaseParticleSystem.BLENDMODE_ADD = 2;
  58353. /**
  58354. * Multiply current color with particle color
  58355. */
  58356. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  58357. /**
  58358. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  58359. */
  58360. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  58361. return BaseParticleSystem;
  58362. }());
  58363. BABYLON.BaseParticleSystem = BaseParticleSystem;
  58364. })(BABYLON || (BABYLON = {}));
  58365. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  58366. var BABYLON;
  58367. (function (BABYLON) {
  58368. /**
  58369. * This represents a particle system in Babylon.
  58370. * 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.
  58371. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  58372. * @example https://doc.babylonjs.com/babylon101/particles
  58373. */
  58374. var ParticleSystem = /** @class */ (function (_super) {
  58375. __extends(ParticleSystem, _super);
  58376. /**
  58377. * Instantiates a particle system.
  58378. * 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.
  58379. * @param name The name of the particle system
  58380. * @param capacity The max number of particles alive at the same time
  58381. * @param scene The scene the particle system belongs to
  58382. * @param customEffect a custom effect used to change the way particles are rendered by default
  58383. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  58384. * @param epsilon Offset used to render the particles
  58385. */
  58386. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  58387. if (customEffect === void 0) { customEffect = null; }
  58388. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  58389. if (epsilon === void 0) { epsilon = 0.01; }
  58390. var _this = _super.call(this, name) || this;
  58391. /**
  58392. * @hidden
  58393. */
  58394. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  58395. /**
  58396. * An event triggered when the system is disposed
  58397. */
  58398. _this.onDisposeObservable = new BABYLON.Observable();
  58399. _this._particles = new Array();
  58400. _this._stockParticles = new Array();
  58401. _this._newPartsExcess = 0;
  58402. _this._vertexBuffers = {};
  58403. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  58404. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  58405. _this._scaledDirection = BABYLON.Vector3.Zero();
  58406. _this._scaledGravity = BABYLON.Vector3.Zero();
  58407. _this._currentRenderId = -1;
  58408. _this._useInstancing = false;
  58409. _this._started = false;
  58410. _this._stopped = false;
  58411. _this._actualFrame = 0;
  58412. /** @hidden */
  58413. _this._currentEmitRate1 = 0;
  58414. /** @hidden */
  58415. _this._currentEmitRate2 = 0;
  58416. /** @hidden */
  58417. _this._currentStartSize1 = 0;
  58418. /** @hidden */
  58419. _this._currentStartSize2 = 0;
  58420. _this._rawTextureWidth = 256;
  58421. _this._useRampGradients = false;
  58422. /**
  58423. * @hidden
  58424. * If the particle systems emitter should be disposed when the particle system is disposed
  58425. */
  58426. _this._disposeEmitterOnDispose = false;
  58427. // start of sub system methods
  58428. /**
  58429. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  58430. * Its lifetime will start back at 0.
  58431. */
  58432. _this.recycleParticle = function (particle) {
  58433. // move particle from activeParticle list to stock particles
  58434. var lastParticle = _this._particles.pop();
  58435. if (lastParticle !== particle) {
  58436. lastParticle.copyTo(particle);
  58437. }
  58438. _this._stockParticles.push(lastParticle);
  58439. };
  58440. _this._createParticle = function () {
  58441. var particle;
  58442. if (_this._stockParticles.length !== 0) {
  58443. particle = _this._stockParticles.pop();
  58444. particle._reset();
  58445. }
  58446. else {
  58447. particle = new BABYLON.Particle(_this);
  58448. }
  58449. // Attach emitters
  58450. if (_this._subEmitters && _this._subEmitters.length > 0) {
  58451. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  58452. particle._attachedSubEmitters = [];
  58453. subEmitters.forEach(function (subEmitter) {
  58454. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  58455. var newEmitter = subEmitter.clone();
  58456. particle._attachedSubEmitters.push(newEmitter);
  58457. newEmitter.particleSystem.start();
  58458. }
  58459. });
  58460. }
  58461. return particle;
  58462. };
  58463. _this._emitFromParticle = function (particle) {
  58464. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  58465. return;
  58466. }
  58467. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  58468. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  58469. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  58470. var subSystem = subEmitter.clone();
  58471. particle._inheritParticleInfoToSubEmitter(subSystem);
  58472. subSystem.particleSystem._rootParticleSystem = _this;
  58473. _this.activeSubSystems.push(subSystem.particleSystem);
  58474. subSystem.particleSystem.start();
  58475. }
  58476. });
  58477. };
  58478. _this._capacity = capacity;
  58479. _this._epsilon = epsilon;
  58480. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  58481. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58482. // Setup the default processing configuration to the scene.
  58483. _this._attachImageProcessingConfiguration(null);
  58484. _this._customEffect = customEffect;
  58485. _this._scene.particleSystems.push(_this);
  58486. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  58487. _this._createIndexBuffer();
  58488. _this._createVertexBuffers();
  58489. // Default emitter type
  58490. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  58491. // Update
  58492. _this.updateFunction = function (particles) {
  58493. var noiseTextureSize = null;
  58494. var noiseTextureData = null;
  58495. if (_this.noiseTexture) { // We need to get texture data back to CPU
  58496. noiseTextureSize = _this.noiseTexture.getSize();
  58497. noiseTextureData = (_this.noiseTexture.getContent());
  58498. }
  58499. var _loop_1 = function () {
  58500. particle = particles[index];
  58501. var scaledUpdateSpeed = _this._scaledUpdateSpeed;
  58502. var previousAge = particle.age;
  58503. particle.age += scaledUpdateSpeed;
  58504. // Evaluate step to death
  58505. if (particle.age > particle.lifeTime) {
  58506. var diff = particle.age - previousAge;
  58507. var oldDiff = particle.lifeTime - previousAge;
  58508. scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff;
  58509. particle.age = particle.lifeTime;
  58510. }
  58511. var ratio = particle.age / particle.lifeTime;
  58512. // Color
  58513. if (_this._colorGradients && _this._colorGradients.length > 0) {
  58514. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  58515. if (currentGradient !== particle._currentColorGradient) {
  58516. particle._currentColor1.copyFrom(particle._currentColor2);
  58517. nextGradient.getColorToRef(particle._currentColor2);
  58518. particle._currentColorGradient = currentGradient;
  58519. }
  58520. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  58521. });
  58522. }
  58523. else {
  58524. particle.colorStep.scaleToRef(scaledUpdateSpeed, _this._scaledColorStep);
  58525. particle.color.addInPlace(_this._scaledColorStep);
  58526. if (particle.color.a < 0) {
  58527. particle.color.a = 0;
  58528. }
  58529. }
  58530. // Angular speed
  58531. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  58532. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  58533. if (currentGradient !== particle._currentAngularSpeedGradient) {
  58534. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  58535. particle._currentAngularSpeed2 = nextGradient.getFactor();
  58536. particle._currentAngularSpeedGradient = currentGradient;
  58537. }
  58538. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  58539. });
  58540. }
  58541. particle.angle += particle.angularSpeed * scaledUpdateSpeed;
  58542. // Direction
  58543. var directionScale = scaledUpdateSpeed;
  58544. /// Velocity
  58545. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  58546. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  58547. if (currentGradient !== particle._currentVelocityGradient) {
  58548. particle._currentVelocity1 = particle._currentVelocity2;
  58549. particle._currentVelocity2 = nextGradient.getFactor();
  58550. particle._currentVelocityGradient = currentGradient;
  58551. }
  58552. directionScale *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  58553. });
  58554. }
  58555. particle.direction.scaleToRef(directionScale, _this._scaledDirection);
  58556. /// Limit velocity
  58557. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  58558. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  58559. if (currentGradient !== particle._currentLimitVelocityGradient) {
  58560. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  58561. particle._currentLimitVelocity2 = nextGradient.getFactor();
  58562. particle._currentLimitVelocityGradient = currentGradient;
  58563. }
  58564. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  58565. var currentVelocity = particle.direction.length();
  58566. if (currentVelocity > limitVelocity) {
  58567. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  58568. }
  58569. });
  58570. }
  58571. /// Drag
  58572. if (_this._dragGradients && _this._dragGradients.length > 0) {
  58573. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  58574. if (currentGradient !== particle._currentDragGradient) {
  58575. particle._currentDrag1 = particle._currentDrag2;
  58576. particle._currentDrag2 = nextGradient.getFactor();
  58577. particle._currentDragGradient = currentGradient;
  58578. }
  58579. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  58580. _this._scaledDirection.scaleInPlace(1.0 - drag);
  58581. });
  58582. }
  58583. particle.position.addInPlace(_this._scaledDirection);
  58584. // Noise
  58585. if (noiseTextureData && noiseTextureSize) {
  58586. var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  58587. var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  58588. var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  58589. var force = BABYLON.Tmp.Vector3[0];
  58590. var scaledForce = BABYLON.Tmp.Vector3[1];
  58591. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  58592. force.scaleToRef(scaledUpdateSpeed, scaledForce);
  58593. particle.direction.addInPlace(scaledForce);
  58594. }
  58595. // Gravity
  58596. _this.gravity.scaleToRef(scaledUpdateSpeed, _this._scaledGravity);
  58597. particle.direction.addInPlace(_this._scaledGravity);
  58598. // Size
  58599. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  58600. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  58601. if (currentGradient !== particle._currentSizeGradient) {
  58602. particle._currentSize1 = particle._currentSize2;
  58603. particle._currentSize2 = nextGradient.getFactor();
  58604. particle._currentSizeGradient = currentGradient;
  58605. }
  58606. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  58607. });
  58608. }
  58609. // Remap data
  58610. if (_this._useRampGradients) {
  58611. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  58612. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  58613. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  58614. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  58615. particle.remapData.x = min;
  58616. particle.remapData.y = max - min;
  58617. });
  58618. }
  58619. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  58620. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  58621. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  58622. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  58623. particle.remapData.z = min;
  58624. particle.remapData.w = max - min;
  58625. });
  58626. }
  58627. }
  58628. if (_this._isAnimationSheetEnabled) {
  58629. particle.updateCellIndex();
  58630. }
  58631. // Update the position of the attached sub-emitters to match their attached particle
  58632. particle._inheritParticleInfoToSubEmitters();
  58633. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  58634. _this._emitFromParticle(particle);
  58635. if (particle._attachedSubEmitters) {
  58636. particle._attachedSubEmitters.forEach(function (subEmitter) {
  58637. subEmitter.particleSystem.disposeOnStop = true;
  58638. subEmitter.particleSystem.stop();
  58639. });
  58640. particle._attachedSubEmitters = null;
  58641. }
  58642. _this.recycleParticle(particle);
  58643. index--;
  58644. return "continue";
  58645. }
  58646. };
  58647. var particle;
  58648. for (var index = 0; index < particles.length; index++) {
  58649. _loop_1();
  58650. }
  58651. };
  58652. return _this;
  58653. }
  58654. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  58655. /**
  58656. * Sets a callback that will be triggered when the system is disposed
  58657. */
  58658. set: function (callback) {
  58659. if (this._onDisposeObserver) {
  58660. this.onDisposeObservable.remove(this._onDisposeObserver);
  58661. }
  58662. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  58663. },
  58664. enumerable: true,
  58665. configurable: true
  58666. });
  58667. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  58668. /** Gets or sets a boolean indicating that ramp gradients must be used
  58669. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  58670. */
  58671. get: function () {
  58672. return this._useRampGradients;
  58673. },
  58674. set: function (value) {
  58675. if (this._useRampGradients === value) {
  58676. return;
  58677. }
  58678. this._useRampGradients = value;
  58679. this._resetEffect();
  58680. },
  58681. enumerable: true,
  58682. configurable: true
  58683. });
  58684. Object.defineProperty(ParticleSystem.prototype, "particles", {
  58685. //end of Sub-emitter
  58686. /**
  58687. * Gets the current list of active particles
  58688. */
  58689. get: function () {
  58690. return this._particles;
  58691. },
  58692. enumerable: true,
  58693. configurable: true
  58694. });
  58695. /**
  58696. * Returns the string "ParticleSystem"
  58697. * @returns a string containing the class name
  58698. */
  58699. ParticleSystem.prototype.getClassName = function () {
  58700. return "ParticleSystem";
  58701. };
  58702. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  58703. var newGradient = new BABYLON.FactorGradient();
  58704. newGradient.gradient = gradient;
  58705. newGradient.factor1 = factor;
  58706. newGradient.factor2 = factor2;
  58707. factorGradients.push(newGradient);
  58708. factorGradients.sort(function (a, b) {
  58709. if (a.gradient < b.gradient) {
  58710. return -1;
  58711. }
  58712. else if (a.gradient > b.gradient) {
  58713. return 1;
  58714. }
  58715. return 0;
  58716. });
  58717. };
  58718. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  58719. if (!factorGradients) {
  58720. return;
  58721. }
  58722. var index = 0;
  58723. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  58724. var factorGradient = factorGradients_1[_i];
  58725. if (factorGradient.gradient === gradient) {
  58726. factorGradients.splice(index, 1);
  58727. break;
  58728. }
  58729. index++;
  58730. }
  58731. };
  58732. /**
  58733. * Adds a new life time gradient
  58734. * @param gradient defines the gradient to use (between 0 and 1)
  58735. * @param factor defines the life time factor to affect to the specified gradient
  58736. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58737. * @returns the current particle system
  58738. */
  58739. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  58740. if (!this._lifeTimeGradients) {
  58741. this._lifeTimeGradients = [];
  58742. }
  58743. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  58744. return this;
  58745. };
  58746. /**
  58747. * Remove a specific life time gradient
  58748. * @param gradient defines the gradient to remove
  58749. * @returns the current particle system
  58750. */
  58751. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  58752. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  58753. return this;
  58754. };
  58755. /**
  58756. * Adds a new size gradient
  58757. * @param gradient defines the gradient to use (between 0 and 1)
  58758. * @param factor defines the size factor to affect to the specified gradient
  58759. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58760. * @returns the current particle system
  58761. */
  58762. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  58763. if (!this._sizeGradients) {
  58764. this._sizeGradients = [];
  58765. }
  58766. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  58767. return this;
  58768. };
  58769. /**
  58770. * Remove a specific size gradient
  58771. * @param gradient defines the gradient to remove
  58772. * @returns the current particle system
  58773. */
  58774. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  58775. this._removeFactorGradient(this._sizeGradients, gradient);
  58776. return this;
  58777. };
  58778. /**
  58779. * Adds a new color remap gradient
  58780. * @param gradient defines the gradient to use (between 0 and 1)
  58781. * @param min defines the color remap minimal range
  58782. * @param max defines the color remap maximal range
  58783. * @returns the current particle system
  58784. */
  58785. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  58786. if (!this._colorRemapGradients) {
  58787. this._colorRemapGradients = [];
  58788. }
  58789. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  58790. return this;
  58791. };
  58792. /**
  58793. * Remove a specific color remap gradient
  58794. * @param gradient defines the gradient to remove
  58795. * @returns the current particle system
  58796. */
  58797. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  58798. this._removeFactorGradient(this._colorRemapGradients, gradient);
  58799. return this;
  58800. };
  58801. /**
  58802. * Adds a new alpha remap gradient
  58803. * @param gradient defines the gradient to use (between 0 and 1)
  58804. * @param min defines the alpha remap minimal range
  58805. * @param max defines the alpha remap maximal range
  58806. * @returns the current particle system
  58807. */
  58808. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  58809. if (!this._alphaRemapGradients) {
  58810. this._alphaRemapGradients = [];
  58811. }
  58812. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  58813. return this;
  58814. };
  58815. /**
  58816. * Remove a specific alpha remap gradient
  58817. * @param gradient defines the gradient to remove
  58818. * @returns the current particle system
  58819. */
  58820. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  58821. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  58822. return this;
  58823. };
  58824. /**
  58825. * Adds a new angular speed gradient
  58826. * @param gradient defines the gradient to use (between 0 and 1)
  58827. * @param factor defines the angular speed to affect to the specified gradient
  58828. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58829. * @returns the current particle system
  58830. */
  58831. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  58832. if (!this._angularSpeedGradients) {
  58833. this._angularSpeedGradients = [];
  58834. }
  58835. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  58836. return this;
  58837. };
  58838. /**
  58839. * Remove a specific angular speed gradient
  58840. * @param gradient defines the gradient to remove
  58841. * @returns the current particle system
  58842. */
  58843. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  58844. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  58845. return this;
  58846. };
  58847. /**
  58848. * Adds a new velocity gradient
  58849. * @param gradient defines the gradient to use (between 0 and 1)
  58850. * @param factor defines the velocity to affect to the specified gradient
  58851. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58852. * @returns the current particle system
  58853. */
  58854. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  58855. if (!this._velocityGradients) {
  58856. this._velocityGradients = [];
  58857. }
  58858. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  58859. return this;
  58860. };
  58861. /**
  58862. * Remove a specific velocity gradient
  58863. * @param gradient defines the gradient to remove
  58864. * @returns the current particle system
  58865. */
  58866. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  58867. this._removeFactorGradient(this._velocityGradients, gradient);
  58868. return this;
  58869. };
  58870. /**
  58871. * Adds a new limit velocity gradient
  58872. * @param gradient defines the gradient to use (between 0 and 1)
  58873. * @param factor defines the limit velocity value to affect to the specified gradient
  58874. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58875. * @returns the current particle system
  58876. */
  58877. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  58878. if (!this._limitVelocityGradients) {
  58879. this._limitVelocityGradients = [];
  58880. }
  58881. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  58882. return this;
  58883. };
  58884. /**
  58885. * Remove a specific limit velocity gradient
  58886. * @param gradient defines the gradient to remove
  58887. * @returns the current particle system
  58888. */
  58889. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  58890. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  58891. return this;
  58892. };
  58893. /**
  58894. * Adds a new drag gradient
  58895. * @param gradient defines the gradient to use (between 0 and 1)
  58896. * @param factor defines the drag value to affect to the specified gradient
  58897. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58898. * @returns the current particle system
  58899. */
  58900. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  58901. if (!this._dragGradients) {
  58902. this._dragGradients = [];
  58903. }
  58904. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  58905. return this;
  58906. };
  58907. /**
  58908. * Remove a specific drag gradient
  58909. * @param gradient defines the gradient to remove
  58910. * @returns the current particle system
  58911. */
  58912. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  58913. this._removeFactorGradient(this._dragGradients, gradient);
  58914. return this;
  58915. };
  58916. /**
  58917. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  58918. * @param gradient defines the gradient to use (between 0 and 1)
  58919. * @param factor defines the emit rate value to affect to the specified gradient
  58920. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58921. * @returns the current particle system
  58922. */
  58923. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  58924. if (!this._emitRateGradients) {
  58925. this._emitRateGradients = [];
  58926. }
  58927. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  58928. if (!this._currentEmitRateGradient) {
  58929. this._currentEmitRateGradient = this._emitRateGradients[0];
  58930. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  58931. this._currentEmitRate2 = this._currentEmitRate1;
  58932. }
  58933. if (this._emitRateGradients.length === 2) {
  58934. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  58935. }
  58936. return this;
  58937. };
  58938. /**
  58939. * Remove a specific emit rate gradient
  58940. * @param gradient defines the gradient to remove
  58941. * @returns the current particle system
  58942. */
  58943. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  58944. this._removeFactorGradient(this._emitRateGradients, gradient);
  58945. return this;
  58946. };
  58947. /**
  58948. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  58949. * @param gradient defines the gradient to use (between 0 and 1)
  58950. * @param factor defines the start size value to affect to the specified gradient
  58951. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58952. * @returns the current particle system
  58953. */
  58954. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  58955. if (!this._startSizeGradients) {
  58956. this._startSizeGradients = [];
  58957. }
  58958. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  58959. if (!this._currentStartSizeGradient) {
  58960. this._currentStartSizeGradient = this._startSizeGradients[0];
  58961. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  58962. this._currentStartSize2 = this._currentStartSize1;
  58963. }
  58964. if (this._startSizeGradients.length === 2) {
  58965. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  58966. }
  58967. return this;
  58968. };
  58969. /**
  58970. * Remove a specific start size gradient
  58971. * @param gradient defines the gradient to remove
  58972. * @returns the current particle system
  58973. */
  58974. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  58975. this._removeFactorGradient(this._emitRateGradients, gradient);
  58976. return this;
  58977. };
  58978. ParticleSystem.prototype._createRampGradientTexture = function () {
  58979. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  58980. return;
  58981. }
  58982. var data = new Uint8Array(this._rawTextureWidth * 4);
  58983. var tmpColor = BABYLON.Tmp.Color3[0];
  58984. for (var x = 0; x < this._rawTextureWidth; x++) {
  58985. var ratio = x / this._rawTextureWidth;
  58986. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  58987. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  58988. data[x * 4] = tmpColor.r * 255;
  58989. data[x * 4 + 1] = tmpColor.g * 255;
  58990. data[x * 4 + 2] = tmpColor.b * 255;
  58991. data[x * 4 + 3] = 255;
  58992. });
  58993. }
  58994. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  58995. };
  58996. /**
  58997. * Gets the current list of ramp gradients.
  58998. * You must use addRampGradient and removeRampGradient to udpate this list
  58999. * @returns the list of ramp gradients
  59000. */
  59001. ParticleSystem.prototype.getRampGradients = function () {
  59002. return this._rampGradients;
  59003. };
  59004. /**
  59005. * Adds a new ramp gradient used to remap particle colors
  59006. * @param gradient defines the gradient to use (between 0 and 1)
  59007. * @param color defines the color to affect to the specified gradient
  59008. * @returns the current particle system
  59009. */
  59010. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  59011. if (!this._rampGradients) {
  59012. this._rampGradients = [];
  59013. }
  59014. var rampGradient = new BABYLON.Color3Gradient();
  59015. rampGradient.gradient = gradient;
  59016. rampGradient.color = color;
  59017. this._rampGradients.push(rampGradient);
  59018. this._rampGradients.sort(function (a, b) {
  59019. if (a.gradient < b.gradient) {
  59020. return -1;
  59021. }
  59022. else if (a.gradient > b.gradient) {
  59023. return 1;
  59024. }
  59025. return 0;
  59026. });
  59027. if (this._rampGradientsTexture) {
  59028. this._rampGradientsTexture.dispose();
  59029. this._rampGradientsTexture = null;
  59030. }
  59031. this._createRampGradientTexture();
  59032. return this;
  59033. };
  59034. /**
  59035. * Remove a specific ramp gradient
  59036. * @param gradient defines the gradient to remove
  59037. * @returns the current particle system
  59038. */
  59039. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  59040. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  59041. this._rampGradientsTexture = null;
  59042. if (this._rampGradients && this._rampGradients.length > 0) {
  59043. this._createRampGradientTexture();
  59044. }
  59045. return this;
  59046. };
  59047. /**
  59048. * Adds a new color gradient
  59049. * @param gradient defines the gradient to use (between 0 and 1)
  59050. * @param color1 defines the color to affect to the specified gradient
  59051. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  59052. * @returns this particle system
  59053. */
  59054. ParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  59055. if (!this._colorGradients) {
  59056. this._colorGradients = [];
  59057. }
  59058. var colorGradient = new BABYLON.ColorGradient();
  59059. colorGradient.gradient = gradient;
  59060. colorGradient.color1 = color1;
  59061. colorGradient.color2 = color2;
  59062. this._colorGradients.push(colorGradient);
  59063. this._colorGradients.sort(function (a, b) {
  59064. if (a.gradient < b.gradient) {
  59065. return -1;
  59066. }
  59067. else if (a.gradient > b.gradient) {
  59068. return 1;
  59069. }
  59070. return 0;
  59071. });
  59072. return this;
  59073. };
  59074. /**
  59075. * Remove a specific color gradient
  59076. * @param gradient defines the gradient to remove
  59077. * @returns this particle system
  59078. */
  59079. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  59080. if (!this._colorGradients) {
  59081. return this;
  59082. }
  59083. var index = 0;
  59084. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  59085. var colorGradient = _a[_i];
  59086. if (colorGradient.gradient === gradient) {
  59087. this._colorGradients.splice(index, 1);
  59088. break;
  59089. }
  59090. index++;
  59091. }
  59092. return this;
  59093. };
  59094. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  59095. u = Math.abs(u) * 0.5 + 0.5;
  59096. v = Math.abs(v) * 0.5 + 0.5;
  59097. var wrappedU = ((u * width) % width) | 0;
  59098. var wrappedV = ((v * height) % height) | 0;
  59099. var position = (wrappedU + wrappedV * width) * 4;
  59100. return pixels[position] / 255;
  59101. };
  59102. ParticleSystem.prototype._reset = function () {
  59103. this._resetEffect();
  59104. };
  59105. ParticleSystem.prototype._resetEffect = function () {
  59106. if (this._vertexBuffer) {
  59107. this._vertexBuffer.dispose();
  59108. this._vertexBuffer = null;
  59109. }
  59110. if (this._spriteBuffer) {
  59111. this._spriteBuffer.dispose();
  59112. this._spriteBuffer = null;
  59113. }
  59114. this._createVertexBuffers();
  59115. };
  59116. ParticleSystem.prototype._createVertexBuffers = function () {
  59117. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  59118. if (this._isAnimationSheetEnabled) {
  59119. this._vertexBufferSize += 1;
  59120. }
  59121. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  59122. this._vertexBufferSize += 3;
  59123. }
  59124. if (this._useRampGradients) {
  59125. this._vertexBufferSize += 4;
  59126. }
  59127. var engine = this._scene.getEngine();
  59128. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  59129. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  59130. var dataOffset = 0;
  59131. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  59132. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  59133. dataOffset += 3;
  59134. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  59135. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  59136. dataOffset += 4;
  59137. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  59138. this._vertexBuffers["angle"] = options;
  59139. dataOffset += 1;
  59140. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  59141. this._vertexBuffers["size"] = size;
  59142. dataOffset += 2;
  59143. if (this._isAnimationSheetEnabled) {
  59144. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  59145. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  59146. dataOffset += 1;
  59147. }
  59148. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  59149. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  59150. this._vertexBuffers["direction"] = directionBuffer;
  59151. dataOffset += 3;
  59152. }
  59153. if (this._useRampGradients) {
  59154. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  59155. this._vertexBuffers["remapData"] = rampDataBuffer;
  59156. dataOffset += 4;
  59157. }
  59158. var offsets;
  59159. if (this._useInstancing) {
  59160. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  59161. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  59162. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  59163. }
  59164. else {
  59165. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  59166. dataOffset += 2;
  59167. }
  59168. this._vertexBuffers["offset"] = offsets;
  59169. };
  59170. ParticleSystem.prototype._createIndexBuffer = function () {
  59171. if (this._useInstancing) {
  59172. return;
  59173. }
  59174. var indices = [];
  59175. var index = 0;
  59176. for (var count = 0; count < this._capacity; count++) {
  59177. indices.push(index);
  59178. indices.push(index + 1);
  59179. indices.push(index + 2);
  59180. indices.push(index);
  59181. indices.push(index + 2);
  59182. indices.push(index + 3);
  59183. index += 4;
  59184. }
  59185. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  59186. };
  59187. /**
  59188. * Gets the maximum number of particles active at the same time.
  59189. * @returns The max number of active particles.
  59190. */
  59191. ParticleSystem.prototype.getCapacity = function () {
  59192. return this._capacity;
  59193. };
  59194. /**
  59195. * Gets whether there are still active particles in the system.
  59196. * @returns True if it is alive, otherwise false.
  59197. */
  59198. ParticleSystem.prototype.isAlive = function () {
  59199. return this._alive;
  59200. };
  59201. /**
  59202. * Gets if the system has been started. (Note: this will still be true after stop is called)
  59203. * @returns True if it has been started, otherwise false.
  59204. */
  59205. ParticleSystem.prototype.isStarted = function () {
  59206. return this._started;
  59207. };
  59208. ParticleSystem.prototype._prepareSubEmitterInternalArray = function () {
  59209. var _this = this;
  59210. this._subEmitters = new Array();
  59211. if (this.subEmitters) {
  59212. this.subEmitters.forEach(function (subEmitter) {
  59213. if (subEmitter instanceof ParticleSystem) {
  59214. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  59215. }
  59216. else if (subEmitter instanceof BABYLON.SubEmitter) {
  59217. _this._subEmitters.push([subEmitter]);
  59218. }
  59219. else if (subEmitter instanceof Array) {
  59220. _this._subEmitters.push(subEmitter);
  59221. }
  59222. });
  59223. }
  59224. };
  59225. /**
  59226. * Starts the particle system and begins to emit
  59227. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  59228. */
  59229. ParticleSystem.prototype.start = function (delay) {
  59230. var _this = this;
  59231. if (delay === void 0) { delay = this.startDelay; }
  59232. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  59233. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  59234. }
  59235. if (delay) {
  59236. setTimeout(function () {
  59237. _this.start(0);
  59238. }, delay);
  59239. return;
  59240. }
  59241. // Convert the subEmitters field to the constant type field _subEmitters
  59242. this._prepareSubEmitterInternalArray();
  59243. this._started = true;
  59244. this._stopped = false;
  59245. this._actualFrame = 0;
  59246. if (this._subEmitters && this._subEmitters.length != 0) {
  59247. this.activeSubSystems = new Array();
  59248. }
  59249. if (this.preWarmCycles) {
  59250. if (this.emitter instanceof BABYLON.AbstractMesh) {
  59251. this.emitter.computeWorldMatrix(true);
  59252. }
  59253. var noiseTextureAsProcedural_1 = this.noiseTexture;
  59254. if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
  59255. noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
  59256. setTimeout(function () {
  59257. for (var index = 0; index < _this.preWarmCycles; index++) {
  59258. _this.animate(true);
  59259. noiseTextureAsProcedural_1.render();
  59260. }
  59261. });
  59262. });
  59263. }
  59264. else {
  59265. for (var index = 0; index < this.preWarmCycles; index++) {
  59266. this.animate(true);
  59267. }
  59268. }
  59269. }
  59270. // Animations
  59271. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  59272. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  59273. }
  59274. };
  59275. /**
  59276. * Stops the particle system.
  59277. * @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.
  59278. */
  59279. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  59280. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  59281. this._stopped = true;
  59282. if (stopSubEmitters) {
  59283. this._stopSubEmitters();
  59284. }
  59285. };
  59286. // animation sheet
  59287. /**
  59288. * Remove all active particles
  59289. */
  59290. ParticleSystem.prototype.reset = function () {
  59291. this._stockParticles = [];
  59292. this._particles = [];
  59293. };
  59294. /**
  59295. * @hidden (for internal use only)
  59296. */
  59297. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  59298. var offset = index * this._vertexBufferSize;
  59299. this._vertexData[offset++] = particle.position.x;
  59300. this._vertexData[offset++] = particle.position.y;
  59301. this._vertexData[offset++] = particle.position.z;
  59302. this._vertexData[offset++] = particle.color.r;
  59303. this._vertexData[offset++] = particle.color.g;
  59304. this._vertexData[offset++] = particle.color.b;
  59305. this._vertexData[offset++] = particle.color.a;
  59306. this._vertexData[offset++] = particle.angle;
  59307. this._vertexData[offset++] = particle.scale.x * particle.size;
  59308. this._vertexData[offset++] = particle.scale.y * particle.size;
  59309. if (this._isAnimationSheetEnabled) {
  59310. this._vertexData[offset++] = particle.cellIndex;
  59311. }
  59312. if (!this._isBillboardBased) {
  59313. if (particle._initialDirection) {
  59314. this._vertexData[offset++] = particle._initialDirection.x;
  59315. this._vertexData[offset++] = particle._initialDirection.y;
  59316. this._vertexData[offset++] = particle._initialDirection.z;
  59317. }
  59318. else {
  59319. this._vertexData[offset++] = particle.direction.x;
  59320. this._vertexData[offset++] = particle.direction.y;
  59321. this._vertexData[offset++] = particle.direction.z;
  59322. }
  59323. }
  59324. else if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  59325. this._vertexData[offset++] = particle.direction.x;
  59326. this._vertexData[offset++] = particle.direction.y;
  59327. this._vertexData[offset++] = particle.direction.z;
  59328. }
  59329. if (this._useRampGradients) {
  59330. this._vertexData[offset++] = particle.remapData.x;
  59331. this._vertexData[offset++] = particle.remapData.y;
  59332. this._vertexData[offset++] = particle.remapData.z;
  59333. this._vertexData[offset++] = particle.remapData.w;
  59334. }
  59335. if (!this._useInstancing) {
  59336. if (this._isAnimationSheetEnabled) {
  59337. if (offsetX === 0)
  59338. offsetX = this._epsilon;
  59339. else if (offsetX === 1)
  59340. offsetX = 1 - this._epsilon;
  59341. if (offsetY === 0)
  59342. offsetY = this._epsilon;
  59343. else if (offsetY === 1)
  59344. offsetY = 1 - this._epsilon;
  59345. }
  59346. this._vertexData[offset++] = offsetX;
  59347. this._vertexData[offset++] = offsetY;
  59348. }
  59349. };
  59350. ParticleSystem.prototype._stopSubEmitters = function () {
  59351. if (!this.activeSubSystems) {
  59352. return;
  59353. }
  59354. this.activeSubSystems.forEach(function (subSystem) {
  59355. subSystem.stop(true);
  59356. });
  59357. this.activeSubSystems = new Array();
  59358. };
  59359. ParticleSystem.prototype._removeFromRoot = function () {
  59360. if (!this._rootParticleSystem) {
  59361. return;
  59362. }
  59363. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  59364. if (index !== -1) {
  59365. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  59366. }
  59367. this._rootParticleSystem = null;
  59368. };
  59369. // End of sub system methods
  59370. ParticleSystem.prototype._update = function (newParticles) {
  59371. var _this = this;
  59372. // Update current
  59373. this._alive = this._particles.length > 0;
  59374. if (this.emitter.position) {
  59375. var emitterMesh = this.emitter;
  59376. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  59377. }
  59378. else {
  59379. var emitterPosition = this.emitter;
  59380. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  59381. }
  59382. this.updateFunction(this._particles);
  59383. // Add new ones
  59384. var particle;
  59385. var _loop_2 = function () {
  59386. if (this_1._particles.length === this_1._capacity) {
  59387. return "break";
  59388. }
  59389. particle = this_1._createParticle();
  59390. this_1._particles.push(particle);
  59391. // Emitter
  59392. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  59393. if (this_1.startPositionFunction) {
  59394. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  59395. }
  59396. else {
  59397. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  59398. }
  59399. if (this_1.startDirectionFunction) {
  59400. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  59401. }
  59402. else {
  59403. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  59404. }
  59405. if (emitPower === 0) {
  59406. if (!particle._initialDirection) {
  59407. particle._initialDirection = particle.direction.clone();
  59408. }
  59409. else {
  59410. particle._initialDirection.copyFrom(particle.direction);
  59411. }
  59412. }
  59413. else {
  59414. particle._initialDirection = null;
  59415. }
  59416. particle.direction.scaleInPlace(emitPower);
  59417. // Life time
  59418. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  59419. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  59420. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  59421. var factorGradient1 = currentGradient;
  59422. var factorGradient2 = nextGradient;
  59423. var lifeTime1 = factorGradient1.getFactor();
  59424. var lifeTime2 = factorGradient2.getFactor();
  59425. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  59426. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  59427. });
  59428. }
  59429. else {
  59430. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  59431. }
  59432. // Size
  59433. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  59434. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  59435. }
  59436. else {
  59437. particle._currentSizeGradient = this_1._sizeGradients[0];
  59438. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  59439. particle.size = particle._currentSize1;
  59440. if (this_1._sizeGradients.length > 1) {
  59441. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  59442. }
  59443. else {
  59444. particle._currentSize2 = particle._currentSize1;
  59445. }
  59446. }
  59447. // Size and scale
  59448. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  59449. // Adjust scale by start size
  59450. if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
  59451. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  59452. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  59453. if (currentGradient !== _this._currentStartSizeGradient) {
  59454. _this._currentStartSize1 = _this._currentStartSize2;
  59455. _this._currentStartSize2 = nextGradient.getFactor();
  59456. _this._currentStartSizeGradient = currentGradient;
  59457. }
  59458. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  59459. particle.scale.scaleInPlace(value);
  59460. });
  59461. }
  59462. // Angle
  59463. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  59464. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  59465. }
  59466. else {
  59467. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  59468. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  59469. particle._currentAngularSpeed1 = particle.angularSpeed;
  59470. if (this_1._angularSpeedGradients.length > 1) {
  59471. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  59472. }
  59473. else {
  59474. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  59475. }
  59476. }
  59477. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  59478. // Velocity
  59479. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  59480. particle._currentVelocityGradient = this_1._velocityGradients[0];
  59481. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  59482. if (this_1._velocityGradients.length > 1) {
  59483. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  59484. }
  59485. else {
  59486. particle._currentVelocity2 = particle._currentVelocity1;
  59487. }
  59488. }
  59489. // Limit velocity
  59490. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  59491. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  59492. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  59493. if (this_1._limitVelocityGradients.length > 1) {
  59494. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  59495. }
  59496. else {
  59497. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  59498. }
  59499. }
  59500. // Drag
  59501. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  59502. particle._currentDragGradient = this_1._dragGradients[0];
  59503. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  59504. if (this_1._dragGradients.length > 1) {
  59505. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  59506. }
  59507. else {
  59508. particle._currentDrag2 = particle._currentDrag1;
  59509. }
  59510. }
  59511. // Color
  59512. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  59513. step = BABYLON.Scalar.RandomRange(0, 1.0);
  59514. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  59515. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  59516. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  59517. }
  59518. else {
  59519. particle._currentColorGradient = this_1._colorGradients[0];
  59520. particle._currentColorGradient.getColorToRef(particle.color);
  59521. particle._currentColor1.copyFrom(particle.color);
  59522. if (this_1._colorGradients.length > 1) {
  59523. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  59524. }
  59525. else {
  59526. particle._currentColor2.copyFrom(particle.color);
  59527. }
  59528. }
  59529. // Sheet
  59530. if (this_1._isAnimationSheetEnabled) {
  59531. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  59532. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  59533. }
  59534. // Inherited Velocity
  59535. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  59536. // Ramp
  59537. if (this_1._useRampGradients) {
  59538. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  59539. }
  59540. // Noise texture coordinates
  59541. if (this_1.noiseTexture) {
  59542. if (particle._randomNoiseCoordinates1) {
  59543. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  59544. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  59545. }
  59546. else {
  59547. particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  59548. particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  59549. }
  59550. }
  59551. // Update the position of the attached sub-emitters to match their attached particle
  59552. particle._inheritParticleInfoToSubEmitters();
  59553. };
  59554. var this_1 = this, step;
  59555. for (var index = 0; index < newParticles; index++) {
  59556. var state_1 = _loop_2();
  59557. if (state_1 === "break")
  59558. break;
  59559. }
  59560. };
  59561. /** @hidden */
  59562. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  59563. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  59564. if (isBillboardBased === void 0) { isBillboardBased = false; }
  59565. if (useRampGradients === void 0) { useRampGradients = false; }
  59566. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  59567. if (isAnimationSheetEnabled) {
  59568. attributeNamesOrOptions.push("cellIndex");
  59569. }
  59570. if (!isBillboardBased) {
  59571. attributeNamesOrOptions.push("direction");
  59572. }
  59573. if (useRampGradients) {
  59574. attributeNamesOrOptions.push("remapData");
  59575. }
  59576. return attributeNamesOrOptions;
  59577. };
  59578. /** @hidden */
  59579. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  59580. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  59581. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  59582. if (isAnimationSheetEnabled) {
  59583. effectCreationOption.push("particlesInfos");
  59584. }
  59585. return effectCreationOption;
  59586. };
  59587. /** @hidden */
  59588. ParticleSystem.prototype._getEffect = function (blendMode) {
  59589. if (this._customEffect) {
  59590. return this._customEffect;
  59591. }
  59592. ;
  59593. var defines = [];
  59594. if (this._scene.clipPlane) {
  59595. defines.push("#define CLIPPLANE");
  59596. }
  59597. if (this._scene.clipPlane2) {
  59598. defines.push("#define CLIPPLANE2");
  59599. }
  59600. if (this._scene.clipPlane3) {
  59601. defines.push("#define CLIPPLANE3");
  59602. }
  59603. if (this._scene.clipPlane4) {
  59604. defines.push("#define CLIPPLANE4");
  59605. }
  59606. if (this._isAnimationSheetEnabled) {
  59607. defines.push("#define ANIMATESHEET");
  59608. }
  59609. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  59610. defines.push("#define BLENDMULTIPLYMODE");
  59611. }
  59612. if (this._useRampGradients) {
  59613. defines.push("#define RAMPGRADIENT");
  59614. }
  59615. if (this._isBillboardBased) {
  59616. defines.push("#define BILLBOARD");
  59617. switch (this.billboardMode) {
  59618. case ParticleSystem.BILLBOARDMODE_Y:
  59619. defines.push("#define BILLBOARDY");
  59620. break;
  59621. case ParticleSystem.BILLBOARDMODE_STRETCHED:
  59622. defines.push("#define BILLBOARDSTRETCHED");
  59623. break;
  59624. case ParticleSystem.BILLBOARDMODE_ALL:
  59625. default:
  59626. break;
  59627. }
  59628. }
  59629. if (this._imageProcessingConfiguration) {
  59630. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  59631. defines.push(this._imageProcessingConfigurationDefines.toString());
  59632. }
  59633. // Effect
  59634. var join = defines.join("\n");
  59635. if (this._cachedDefines !== join) {
  59636. this._cachedDefines = join;
  59637. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED, this._useRampGradients);
  59638. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  59639. var samplers = ["diffuseSampler", "rampSampler"];
  59640. if (BABYLON.ImageProcessingConfiguration) {
  59641. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  59642. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  59643. }
  59644. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  59645. }
  59646. return this._effect;
  59647. };
  59648. /**
  59649. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  59650. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  59651. */
  59652. ParticleSystem.prototype.animate = function (preWarmOnly) {
  59653. var _this = this;
  59654. if (preWarmOnly === void 0) { preWarmOnly = false; }
  59655. if (!this._started)
  59656. return;
  59657. if (!preWarmOnly) {
  59658. // Check
  59659. if (!this.isReady())
  59660. return;
  59661. if (this._currentRenderId === this._scene.getRenderId()) {
  59662. return;
  59663. }
  59664. this._currentRenderId = this._scene.getRenderId();
  59665. }
  59666. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  59667. // Determine the number of particles we need to create
  59668. var newParticles;
  59669. if (this.manualEmitCount > -1) {
  59670. newParticles = this.manualEmitCount;
  59671. this._newPartsExcess = 0;
  59672. this.manualEmitCount = 0;
  59673. }
  59674. else {
  59675. var rate_1 = this.emitRate;
  59676. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  59677. var ratio = this._actualFrame / this.targetStopDuration;
  59678. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  59679. if (currentGradient !== _this._currentEmitRateGradient) {
  59680. _this._currentEmitRate1 = _this._currentEmitRate2;
  59681. _this._currentEmitRate2 = nextGradient.getFactor();
  59682. _this._currentEmitRateGradient = currentGradient;
  59683. }
  59684. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  59685. });
  59686. }
  59687. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  59688. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  59689. }
  59690. if (this._newPartsExcess > 1.0) {
  59691. newParticles += this._newPartsExcess >> 0;
  59692. this._newPartsExcess -= this._newPartsExcess >> 0;
  59693. }
  59694. this._alive = false;
  59695. if (!this._stopped) {
  59696. this._actualFrame += this._scaledUpdateSpeed;
  59697. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  59698. this.stop();
  59699. }
  59700. else {
  59701. newParticles = 0;
  59702. }
  59703. this._update(newParticles);
  59704. // Stopped?
  59705. if (this._stopped) {
  59706. if (!this._alive) {
  59707. this._started = false;
  59708. if (this.onAnimationEnd) {
  59709. this.onAnimationEnd();
  59710. }
  59711. if (this.disposeOnStop) {
  59712. this._scene._toBeDisposed.push(this);
  59713. }
  59714. }
  59715. }
  59716. if (!preWarmOnly) {
  59717. // Update VBO
  59718. var offset = 0;
  59719. for (var index = 0; index < this._particles.length; index++) {
  59720. var particle = this._particles[index];
  59721. this._appendParticleVertices(offset, particle);
  59722. offset += this._useInstancing ? 1 : 4;
  59723. }
  59724. if (this._vertexBuffer) {
  59725. this._vertexBuffer.update(this._vertexData);
  59726. }
  59727. }
  59728. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  59729. this.stop();
  59730. }
  59731. };
  59732. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  59733. this._appendParticleVertex(offset++, particle, 0, 0);
  59734. if (!this._useInstancing) {
  59735. this._appendParticleVertex(offset++, particle, 1, 0);
  59736. this._appendParticleVertex(offset++, particle, 1, 1);
  59737. this._appendParticleVertex(offset++, particle, 0, 1);
  59738. }
  59739. };
  59740. /**
  59741. * Rebuilds the particle system.
  59742. */
  59743. ParticleSystem.prototype.rebuild = function () {
  59744. this._createIndexBuffer();
  59745. if (this._vertexBuffer) {
  59746. this._vertexBuffer._rebuild();
  59747. }
  59748. };
  59749. /**
  59750. * Is this system ready to be used/rendered
  59751. * @return true if the system is ready
  59752. */
  59753. ParticleSystem.prototype.isReady = function () {
  59754. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  59755. return false;
  59756. }
  59757. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  59758. if (!this._getEffect(this.blendMode).isReady()) {
  59759. return false;
  59760. }
  59761. }
  59762. else {
  59763. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  59764. return false;
  59765. }
  59766. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  59767. return false;
  59768. }
  59769. }
  59770. return true;
  59771. };
  59772. ParticleSystem.prototype._render = function (blendMode) {
  59773. var effect = this._getEffect(blendMode);
  59774. var engine = this._scene.getEngine();
  59775. // Render
  59776. engine.enableEffect(effect);
  59777. var viewMatrix = this._scene.getViewMatrix();
  59778. effect.setTexture("diffuseSampler", this.particleTexture);
  59779. effect.setMatrix("view", viewMatrix);
  59780. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  59781. if (this._isAnimationSheetEnabled && this.particleTexture) {
  59782. var baseSize = this.particleTexture.getBaseSize();
  59783. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  59784. }
  59785. effect.setVector2("translationPivot", this.translationPivot);
  59786. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  59787. if (this._isBillboardBased) {
  59788. var camera = this._scene.activeCamera;
  59789. effect.setVector3("eyePosition", camera.globalPosition);
  59790. }
  59791. if (this._rampGradientsTexture) {
  59792. effect.setTexture("rampSampler", this._rampGradientsTexture);
  59793. }
  59794. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  59795. var invView = viewMatrix.clone();
  59796. invView.invert();
  59797. effect.setMatrix("invView", invView);
  59798. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  59799. }
  59800. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  59801. // image processing
  59802. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  59803. this._imageProcessingConfiguration.bind(effect);
  59804. }
  59805. // Draw order
  59806. switch (blendMode) {
  59807. case ParticleSystem.BLENDMODE_ADD:
  59808. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  59809. break;
  59810. case ParticleSystem.BLENDMODE_ONEONE:
  59811. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  59812. break;
  59813. case ParticleSystem.BLENDMODE_STANDARD:
  59814. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  59815. break;
  59816. case ParticleSystem.BLENDMODE_MULTIPLY:
  59817. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  59818. break;
  59819. }
  59820. if (this._useInstancing) {
  59821. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  59822. }
  59823. else {
  59824. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  59825. }
  59826. return this._particles.length;
  59827. };
  59828. /**
  59829. * Renders the particle system in its current state.
  59830. * @returns the current number of particles
  59831. */
  59832. ParticleSystem.prototype.render = function () {
  59833. // Check
  59834. if (!this.isReady() || !this._particles.length) {
  59835. return 0;
  59836. }
  59837. var engine = this._scene.getEngine();
  59838. engine.setState(false);
  59839. if (this.forceDepthWrite) {
  59840. engine.setDepthWrite(true);
  59841. }
  59842. var outparticles = 0;
  59843. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  59844. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  59845. }
  59846. outparticles = this._render(this.blendMode);
  59847. engine.unbindInstanceAttributes();
  59848. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  59849. return outparticles;
  59850. };
  59851. /**
  59852. * Disposes the particle system and free the associated resources
  59853. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  59854. */
  59855. ParticleSystem.prototype.dispose = function (disposeTexture) {
  59856. if (disposeTexture === void 0) { disposeTexture = true; }
  59857. if (this._vertexBuffer) {
  59858. this._vertexBuffer.dispose();
  59859. this._vertexBuffer = null;
  59860. }
  59861. if (this._spriteBuffer) {
  59862. this._spriteBuffer.dispose();
  59863. this._spriteBuffer = null;
  59864. }
  59865. if (this._indexBuffer) {
  59866. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  59867. this._indexBuffer = null;
  59868. }
  59869. if (disposeTexture && this.particleTexture) {
  59870. this.particleTexture.dispose();
  59871. this.particleTexture = null;
  59872. }
  59873. if (disposeTexture && this.noiseTexture) {
  59874. this.noiseTexture.dispose();
  59875. this.noiseTexture = null;
  59876. }
  59877. if (this._rampGradientsTexture) {
  59878. this._rampGradientsTexture.dispose();
  59879. this._rampGradientsTexture = null;
  59880. }
  59881. this._removeFromRoot();
  59882. if (this._subEmitters && this._subEmitters.length) {
  59883. for (var index = 0; index < this._subEmitters.length; index++) {
  59884. for (var _i = 0, _a = this._subEmitters[index]; _i < _a.length; _i++) {
  59885. var subEmitter = _a[_i];
  59886. subEmitter.dispose();
  59887. }
  59888. }
  59889. this._subEmitters = [];
  59890. this.subEmitters = [];
  59891. }
  59892. if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
  59893. this.emitter.dispose(true);
  59894. }
  59895. // Remove from scene
  59896. var index = this._scene.particleSystems.indexOf(this);
  59897. if (index > -1) {
  59898. this._scene.particleSystems.splice(index, 1);
  59899. }
  59900. this._scene._activeParticleSystems.dispose();
  59901. // Callback
  59902. this.onDisposeObservable.notifyObservers(this);
  59903. this.onDisposeObservable.clear();
  59904. this.reset();
  59905. };
  59906. // Clone
  59907. /**
  59908. * Clones the particle system.
  59909. * @param name The name of the cloned object
  59910. * @param newEmitter The new emitter to use
  59911. * @returns the cloned particle system
  59912. */
  59913. ParticleSystem.prototype.clone = function (name, newEmitter) {
  59914. var custom = null;
  59915. var program = null;
  59916. if (this.customShader != null) {
  59917. program = this.customShader;
  59918. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  59919. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  59920. }
  59921. else if (this._customEffect) {
  59922. custom = this._customEffect;
  59923. }
  59924. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  59925. result.customShader = program;
  59926. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
  59927. if (newEmitter === undefined) {
  59928. newEmitter = this.emitter;
  59929. }
  59930. result.noiseTexture = this.noiseTexture;
  59931. result.emitter = newEmitter;
  59932. if (this.particleTexture) {
  59933. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  59934. }
  59935. // Clone gradients
  59936. if (this._colorGradients) {
  59937. this._colorGradients.forEach(function (v) {
  59938. result.addColorGradient(v.gradient, v.color1, v.color2);
  59939. });
  59940. }
  59941. if (this._dragGradients) {
  59942. this._dragGradients.forEach(function (v) {
  59943. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  59944. });
  59945. }
  59946. if (this._angularSpeedGradients) {
  59947. this._angularSpeedGradients.forEach(function (v) {
  59948. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  59949. });
  59950. }
  59951. if (this._emitRateGradients) {
  59952. this._emitRateGradients.forEach(function (v) {
  59953. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  59954. });
  59955. }
  59956. if (this._lifeTimeGradients) {
  59957. this._lifeTimeGradients.forEach(function (v) {
  59958. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  59959. });
  59960. }
  59961. if (this._limitVelocityGradients) {
  59962. this._limitVelocityGradients.forEach(function (v) {
  59963. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  59964. });
  59965. }
  59966. if (this._sizeGradients) {
  59967. this._sizeGradients.forEach(function (v) {
  59968. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  59969. });
  59970. }
  59971. if (this._startSizeGradients) {
  59972. this._startSizeGradients.forEach(function (v) {
  59973. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  59974. });
  59975. }
  59976. if (this._velocityGradients) {
  59977. this._velocityGradients.forEach(function (v) {
  59978. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  59979. });
  59980. }
  59981. if (this._rampGradients) {
  59982. this._rampGradients.forEach(function (v) {
  59983. result.addRampGradient(v.gradient, v.color);
  59984. });
  59985. }
  59986. if (this._colorRemapGradients) {
  59987. this._colorRemapGradients.forEach(function (v) {
  59988. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  59989. });
  59990. }
  59991. if (this._alphaRemapGradients) {
  59992. this._alphaRemapGradients.forEach(function (v) {
  59993. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  59994. });
  59995. }
  59996. if (!this.preventAutoStart) {
  59997. result.start();
  59998. }
  59999. return result;
  60000. };
  60001. /**
  60002. * Serializes the particle system to a JSON object.
  60003. * @returns the JSON object
  60004. */
  60005. ParticleSystem.prototype.serialize = function () {
  60006. var serializationObject = {};
  60007. ParticleSystem._Serialize(serializationObject, this);
  60008. serializationObject.textureMask = this.textureMask.asArray();
  60009. serializationObject.customShader = this.customShader;
  60010. serializationObject.preventAutoStart = this.preventAutoStart;
  60011. // SubEmitters
  60012. if (this.subEmitters) {
  60013. serializationObject.subEmitters = [];
  60014. if (!this._subEmitters) {
  60015. this._prepareSubEmitterInternalArray();
  60016. }
  60017. for (var _i = 0, _a = this._subEmitters; _i < _a.length; _i++) {
  60018. var subs = _a[_i];
  60019. var cell = [];
  60020. for (var _b = 0, subs_1 = subs; _b < subs_1.length; _b++) {
  60021. var sub = subs_1[_b];
  60022. cell.push(sub.serialize());
  60023. }
  60024. serializationObject.subEmitters.push(cell);
  60025. }
  60026. }
  60027. return serializationObject;
  60028. };
  60029. /** @hidden */
  60030. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  60031. serializationObject.name = particleSystem.name;
  60032. serializationObject.id = particleSystem.id;
  60033. serializationObject.capacity = particleSystem.getCapacity();
  60034. // Emitter
  60035. if (particleSystem.emitter.position) {
  60036. var emitterMesh = particleSystem.emitter;
  60037. serializationObject.emitterId = emitterMesh.id;
  60038. }
  60039. else {
  60040. var emitterPosition = particleSystem.emitter;
  60041. serializationObject.emitter = emitterPosition.asArray();
  60042. }
  60043. // Emitter
  60044. if (particleSystem.particleEmitterType) {
  60045. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  60046. }
  60047. if (particleSystem.particleTexture) {
  60048. serializationObject.textureName = particleSystem.particleTexture.name;
  60049. serializationObject.invertY = particleSystem.particleTexture._invertY;
  60050. }
  60051. // Animations
  60052. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  60053. serializationObject.beginAnimationOnStart = particleSystem.beginAnimationOnStart;
  60054. serializationObject.beginAnimationFrom = particleSystem.beginAnimationFrom;
  60055. serializationObject.beginAnimationTo = particleSystem.beginAnimationTo;
  60056. serializationObject.beginAnimationLoop = particleSystem.beginAnimationLoop;
  60057. // Particle system
  60058. serializationObject.startDelay = particleSystem.startDelay;
  60059. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  60060. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  60061. serializationObject.billboardMode = particleSystem.billboardMode;
  60062. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  60063. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  60064. serializationObject.minSize = particleSystem.minSize;
  60065. serializationObject.maxSize = particleSystem.maxSize;
  60066. serializationObject.minScaleX = particleSystem.minScaleX;
  60067. serializationObject.maxScaleX = particleSystem.maxScaleX;
  60068. serializationObject.minScaleY = particleSystem.minScaleY;
  60069. serializationObject.maxScaleY = particleSystem.maxScaleY;
  60070. serializationObject.minEmitPower = particleSystem.minEmitPower;
  60071. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  60072. serializationObject.minLifeTime = particleSystem.minLifeTime;
  60073. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  60074. serializationObject.emitRate = particleSystem.emitRate;
  60075. serializationObject.gravity = particleSystem.gravity.asArray();
  60076. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  60077. serializationObject.color1 = particleSystem.color1.asArray();
  60078. serializationObject.color2 = particleSystem.color2.asArray();
  60079. serializationObject.colorDead = particleSystem.colorDead.asArray();
  60080. serializationObject.updateSpeed = particleSystem.updateSpeed;
  60081. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  60082. serializationObject.blendMode = particleSystem.blendMode;
  60083. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  60084. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  60085. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  60086. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  60087. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  60088. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  60089. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  60090. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  60091. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  60092. serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell;
  60093. serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled;
  60094. var colorGradients = particleSystem.getColorGradients();
  60095. if (colorGradients) {
  60096. serializationObject.colorGradients = [];
  60097. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  60098. var colorGradient = colorGradients_1[_i];
  60099. var serializedGradient = {
  60100. gradient: colorGradient.gradient,
  60101. color1: colorGradient.color1.asArray()
  60102. };
  60103. if (colorGradient.color2) {
  60104. serializedGradient.color2 = colorGradient.color2.asArray();
  60105. }
  60106. serializationObject.colorGradients.push(serializedGradient);
  60107. }
  60108. }
  60109. var rampGradients = particleSystem.getRampGradients();
  60110. if (rampGradients) {
  60111. serializationObject.rampGradients = [];
  60112. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  60113. var rampGradient = rampGradients_1[_a];
  60114. var serializedGradient = {
  60115. gradient: rampGradient.gradient,
  60116. color: rampGradient.color.asArray()
  60117. };
  60118. serializationObject.rampGradients.push(serializedGradient);
  60119. }
  60120. serializationObject.useRampGradients = particleSystem.useRampGradients;
  60121. }
  60122. var colorRemapGradients = particleSystem.getColorRemapGradients();
  60123. if (colorRemapGradients) {
  60124. serializationObject.colorRemapGradients = [];
  60125. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  60126. var colorRemapGradient = colorRemapGradients_1[_b];
  60127. var serializedGradient = {
  60128. gradient: colorRemapGradient.gradient,
  60129. factor1: colorRemapGradient.factor1
  60130. };
  60131. if (colorRemapGradient.factor2 !== undefined) {
  60132. serializedGradient.factor2 = colorRemapGradient.factor2;
  60133. }
  60134. serializationObject.colorRemapGradients.push(serializedGradient);
  60135. }
  60136. }
  60137. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  60138. if (alphaRemapGradients) {
  60139. serializationObject.alphaRemapGradients = [];
  60140. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  60141. var alphaRemapGradient = alphaRemapGradients_1[_c];
  60142. var serializedGradient = {
  60143. gradient: alphaRemapGradient.gradient,
  60144. factor1: alphaRemapGradient.factor1
  60145. };
  60146. if (alphaRemapGradient.factor2 !== undefined) {
  60147. serializedGradient.factor2 = alphaRemapGradient.factor2;
  60148. }
  60149. serializationObject.alphaRemapGradients.push(serializedGradient);
  60150. }
  60151. }
  60152. var sizeGradients = particleSystem.getSizeGradients();
  60153. if (sizeGradients) {
  60154. serializationObject.sizeGradients = [];
  60155. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  60156. var sizeGradient = sizeGradients_1[_d];
  60157. var serializedGradient = {
  60158. gradient: sizeGradient.gradient,
  60159. factor1: sizeGradient.factor1
  60160. };
  60161. if (sizeGradient.factor2 !== undefined) {
  60162. serializedGradient.factor2 = sizeGradient.factor2;
  60163. }
  60164. serializationObject.sizeGradients.push(serializedGradient);
  60165. }
  60166. }
  60167. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  60168. if (angularSpeedGradients) {
  60169. serializationObject.angularSpeedGradients = [];
  60170. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  60171. var angularSpeedGradient = angularSpeedGradients_1[_e];
  60172. var serializedGradient = {
  60173. gradient: angularSpeedGradient.gradient,
  60174. factor1: angularSpeedGradient.factor1
  60175. };
  60176. if (angularSpeedGradient.factor2 !== undefined) {
  60177. serializedGradient.factor2 = angularSpeedGradient.factor2;
  60178. }
  60179. serializationObject.angularSpeedGradients.push(serializedGradient);
  60180. }
  60181. }
  60182. var velocityGradients = particleSystem.getVelocityGradients();
  60183. if (velocityGradients) {
  60184. serializationObject.velocityGradients = [];
  60185. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  60186. var velocityGradient = velocityGradients_1[_f];
  60187. var serializedGradient = {
  60188. gradient: velocityGradient.gradient,
  60189. factor1: velocityGradient.factor1
  60190. };
  60191. if (velocityGradient.factor2 !== undefined) {
  60192. serializedGradient.factor2 = velocityGradient.factor2;
  60193. }
  60194. serializationObject.velocityGradients.push(serializedGradient);
  60195. }
  60196. }
  60197. var dragGradients = particleSystem.getDragGradients();
  60198. if (dragGradients) {
  60199. serializationObject.dragyGradients = [];
  60200. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  60201. var dragGradient = dragGradients_1[_g];
  60202. var serializedGradient = {
  60203. gradient: dragGradient.gradient,
  60204. factor1: dragGradient.factor1
  60205. };
  60206. if (dragGradient.factor2 !== undefined) {
  60207. serializedGradient.factor2 = dragGradient.factor2;
  60208. }
  60209. serializationObject.dragGradients.push(serializedGradient);
  60210. }
  60211. }
  60212. var emitRateGradients = particleSystem.getEmitRateGradients();
  60213. if (emitRateGradients) {
  60214. serializationObject.emitRateGradients = [];
  60215. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  60216. var emitRateGradient = emitRateGradients_1[_h];
  60217. var serializedGradient = {
  60218. gradient: emitRateGradient.gradient,
  60219. factor1: emitRateGradient.factor1
  60220. };
  60221. if (emitRateGradient.factor2 !== undefined) {
  60222. serializedGradient.factor2 = emitRateGradient.factor2;
  60223. }
  60224. serializationObject.emitRateGradients.push(serializedGradient);
  60225. }
  60226. }
  60227. var startSizeGradients = particleSystem.getStartSizeGradients();
  60228. if (startSizeGradients) {
  60229. serializationObject.startSizeGradients = [];
  60230. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  60231. var startSizeGradient = startSizeGradients_1[_j];
  60232. var serializedGradient = {
  60233. gradient: startSizeGradient.gradient,
  60234. factor1: startSizeGradient.factor1
  60235. };
  60236. if (startSizeGradient.factor2 !== undefined) {
  60237. serializedGradient.factor2 = startSizeGradient.factor2;
  60238. }
  60239. serializationObject.startSizeGradients.push(serializedGradient);
  60240. }
  60241. }
  60242. var lifeTimeGradients = particleSystem.getLifeTimeGradients();
  60243. if (lifeTimeGradients) {
  60244. serializationObject.lifeTimeGradients = [];
  60245. for (var _k = 0, lifeTimeGradients_1 = lifeTimeGradients; _k < lifeTimeGradients_1.length; _k++) {
  60246. var lifeTimeGradient = lifeTimeGradients_1[_k];
  60247. var serializedGradient = {
  60248. gradient: lifeTimeGradient.gradient,
  60249. factor1: lifeTimeGradient.factor1
  60250. };
  60251. if (lifeTimeGradient.factor2 !== undefined) {
  60252. serializedGradient.factor2 = lifeTimeGradient.factor2;
  60253. }
  60254. serializationObject.lifeTimeGradients.push(serializedGradient);
  60255. }
  60256. }
  60257. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  60258. if (limitVelocityGradients) {
  60259. serializationObject.limitVelocityGradients = [];
  60260. for (var _l = 0, limitVelocityGradients_1 = limitVelocityGradients; _l < limitVelocityGradients_1.length; _l++) {
  60261. var limitVelocityGradient = limitVelocityGradients_1[_l];
  60262. var serializedGradient = {
  60263. gradient: limitVelocityGradient.gradient,
  60264. factor1: limitVelocityGradient.factor1
  60265. };
  60266. if (limitVelocityGradient.factor2 !== undefined) {
  60267. serializedGradient.factor2 = limitVelocityGradient.factor2;
  60268. }
  60269. serializationObject.limitVelocityGradients.push(serializedGradient);
  60270. }
  60271. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  60272. }
  60273. if (particleSystem.noiseTexture) {
  60274. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  60275. }
  60276. };
  60277. /** @hidden */
  60278. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  60279. // Texture
  60280. if (parsedParticleSystem.textureName) {
  60281. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== undefined ? parsedParticleSystem.invertY : true);
  60282. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  60283. }
  60284. // Emitter
  60285. if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === undefined) {
  60286. particleSystem.emitter = BABYLON.Vector3.Zero();
  60287. }
  60288. else if (parsedParticleSystem.emitterId) {
  60289. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  60290. }
  60291. else {
  60292. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  60293. }
  60294. // Misc.
  60295. if (parsedParticleSystem.renderingGroupId !== undefined) {
  60296. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  60297. }
  60298. if (parsedParticleSystem.isBillboardBased !== undefined) {
  60299. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  60300. }
  60301. if (parsedParticleSystem.billboardMode !== undefined) {
  60302. particleSystem.billboardMode = parsedParticleSystem.billboardMode;
  60303. }
  60304. // Animations
  60305. if (parsedParticleSystem.animations) {
  60306. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  60307. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  60308. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  60309. }
  60310. particleSystem.beginAnimationOnStart = parsedParticleSystem.beginAnimationOnStart;
  60311. particleSystem.beginAnimationFrom = parsedParticleSystem.beginAnimationFrom;
  60312. particleSystem.beginAnimationTo = parsedParticleSystem.beginAnimationTo;
  60313. particleSystem.beginAnimationLoop = parsedParticleSystem.beginAnimationLoop;
  60314. }
  60315. if (parsedParticleSystem.autoAnimate) {
  60316. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  60317. }
  60318. // Particle system
  60319. particleSystem.startDelay = parsedParticleSystem.startDelay | 0;
  60320. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  60321. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  60322. particleSystem.minSize = parsedParticleSystem.minSize;
  60323. particleSystem.maxSize = parsedParticleSystem.maxSize;
  60324. if (parsedParticleSystem.minScaleX) {
  60325. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  60326. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  60327. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  60328. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  60329. }
  60330. if (parsedParticleSystem.preWarmCycles !== undefined) {
  60331. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  60332. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  60333. }
  60334. if (parsedParticleSystem.minInitialRotation !== undefined) {
  60335. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  60336. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  60337. }
  60338. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  60339. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  60340. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  60341. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  60342. particleSystem.emitRate = parsedParticleSystem.emitRate;
  60343. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  60344. if (parsedParticleSystem.noiseStrength) {
  60345. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  60346. }
  60347. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  60348. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  60349. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  60350. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  60351. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  60352. particleSystem.blendMode = parsedParticleSystem.blendMode;
  60353. if (parsedParticleSystem.colorGradients) {
  60354. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  60355. var colorGradient = _a[_i];
  60356. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  60357. }
  60358. }
  60359. if (parsedParticleSystem.rampGradients) {
  60360. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  60361. var rampGradient = _c[_b];
  60362. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color));
  60363. }
  60364. particleSystem.useRampGradients = parsedParticleSystem.useRampGradients;
  60365. }
  60366. if (parsedParticleSystem.colorRemapGradients) {
  60367. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  60368. var colorRemapGradient = _e[_d];
  60369. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  60370. }
  60371. }
  60372. if (parsedParticleSystem.alphaRemapGradients) {
  60373. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  60374. var alphaRemapGradient = _g[_f];
  60375. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  60376. }
  60377. }
  60378. if (parsedParticleSystem.sizeGradients) {
  60379. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  60380. var sizeGradient = _j[_h];
  60381. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  60382. }
  60383. }
  60384. if (parsedParticleSystem.sizeGradients) {
  60385. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  60386. var sizeGradient = _l[_k];
  60387. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  60388. }
  60389. }
  60390. if (parsedParticleSystem.angularSpeedGradients) {
  60391. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  60392. var angularSpeedGradient = _o[_m];
  60393. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  60394. }
  60395. }
  60396. if (parsedParticleSystem.velocityGradients) {
  60397. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  60398. var velocityGradient = _q[_p];
  60399. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  60400. }
  60401. }
  60402. if (parsedParticleSystem.dragGradients) {
  60403. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  60404. var dragGradient = _s[_r];
  60405. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  60406. }
  60407. }
  60408. if (parsedParticleSystem.emitRateGradients) {
  60409. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  60410. var emitRateGradient = _u[_t];
  60411. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  60412. }
  60413. }
  60414. if (parsedParticleSystem.startSizeGradients) {
  60415. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  60416. var startSizeGradient = _w[_v];
  60417. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  60418. }
  60419. }
  60420. if (parsedParticleSystem.lifeTimeGradients) {
  60421. for (var _x = 0, _y = parsedParticleSystem.lifeTimeGradients; _x < _y.length; _x++) {
  60422. var lifeTimeGradient = _y[_x];
  60423. particleSystem.addLifeTimeGradient(lifeTimeGradient.gradient, lifeTimeGradient.factor1 !== undefined ? lifeTimeGradient.factor1 : lifeTimeGradient.factor, lifeTimeGradient.factor2);
  60424. }
  60425. }
  60426. if (parsedParticleSystem.limitVelocityGradients) {
  60427. for (var _z = 0, _0 = parsedParticleSystem.limitVelocityGradients; _z < _0.length; _z++) {
  60428. var limitVelocityGradient = _0[_z];
  60429. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  60430. }
  60431. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  60432. }
  60433. if (parsedParticleSystem.noiseTexture) {
  60434. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  60435. }
  60436. // Emitter
  60437. var emitterType;
  60438. if (parsedParticleSystem.particleEmitterType) {
  60439. switch (parsedParticleSystem.particleEmitterType.type) {
  60440. case "SphereParticleEmitter":
  60441. emitterType = new BABYLON.SphereParticleEmitter();
  60442. break;
  60443. case "SphereDirectedParticleEmitter":
  60444. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  60445. break;
  60446. case "ConeEmitter":
  60447. case "ConeParticleEmitter":
  60448. emitterType = new BABYLON.ConeParticleEmitter();
  60449. break;
  60450. case "CylinderParticleEmitter":
  60451. emitterType = new BABYLON.CylinderParticleEmitter();
  60452. break;
  60453. case "HemisphericParticleEmitter":
  60454. emitterType = new BABYLON.HemisphericParticleEmitter();
  60455. break;
  60456. case "BoxEmitter":
  60457. case "BoxParticleEmitter":
  60458. default:
  60459. emitterType = new BABYLON.BoxParticleEmitter();
  60460. break;
  60461. }
  60462. emitterType.parse(parsedParticleSystem.particleEmitterType);
  60463. }
  60464. else {
  60465. emitterType = new BABYLON.BoxParticleEmitter();
  60466. emitterType.parse(parsedParticleSystem);
  60467. }
  60468. particleSystem.particleEmitterType = emitterType;
  60469. // Animation sheet
  60470. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  60471. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  60472. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  60473. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  60474. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  60475. particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell;
  60476. };
  60477. /**
  60478. * Parses a JSON object to create a particle system.
  60479. * @param parsedParticleSystem The JSON object to parse
  60480. * @param scene The scene to create the particle system in
  60481. * @param rootUrl The root url to use to load external dependencies like texture
  60482. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  60483. * @returns the Parsed particle system
  60484. */
  60485. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  60486. if (doNotStart === void 0) { doNotStart = false; }
  60487. var name = parsedParticleSystem.name;
  60488. var custom = null;
  60489. var program = null;
  60490. if (parsedParticleSystem.customShader) {
  60491. program = parsedParticleSystem.customShader;
  60492. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  60493. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  60494. }
  60495. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  60496. particleSystem.customShader = program;
  60497. if (parsedParticleSystem.id) {
  60498. particleSystem.id = parsedParticleSystem.id;
  60499. }
  60500. // SubEmitters
  60501. if (parsedParticleSystem.subEmitters) {
  60502. particleSystem.subEmitters = [];
  60503. for (var _i = 0, _a = parsedParticleSystem.subEmitters; _i < _a.length; _i++) {
  60504. var cell = _a[_i];
  60505. var cellArray = [];
  60506. for (var _b = 0, cell_1 = cell; _b < cell_1.length; _b++) {
  60507. var sub = cell_1[_b];
  60508. cellArray.push(BABYLON.SubEmitter.Parse(sub, scene, rootUrl));
  60509. }
  60510. particleSystem.subEmitters.push(cellArray);
  60511. }
  60512. }
  60513. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  60514. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  60515. // Auto start
  60516. if (parsedParticleSystem.preventAutoStart) {
  60517. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  60518. }
  60519. if (!doNotStart && !particleSystem.preventAutoStart) {
  60520. particleSystem.start();
  60521. }
  60522. return particleSystem;
  60523. };
  60524. /**
  60525. * Billboard mode will only apply to Y axis
  60526. */
  60527. ParticleSystem.BILLBOARDMODE_Y = 2;
  60528. /**
  60529. * Billboard mode will apply to all axes
  60530. */
  60531. ParticleSystem.BILLBOARDMODE_ALL = 7;
  60532. /**
  60533. * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction
  60534. */
  60535. ParticleSystem.BILLBOARDMODE_STRETCHED = 8;
  60536. return ParticleSystem;
  60537. }(BABYLON.BaseParticleSystem));
  60538. BABYLON.ParticleSystem = ParticleSystem;
  60539. })(BABYLON || (BABYLON = {}));
  60540. //# sourceMappingURL=babylon.particleSystem.js.map
  60541. var BABYLON;
  60542. (function (BABYLON) {
  60543. /**
  60544. * Particle emitter emitting particles from the inside of a box.
  60545. * It emits the particles randomly between 2 given directions.
  60546. */
  60547. var BoxParticleEmitter = /** @class */ (function () {
  60548. /**
  60549. * Creates a new instance BoxParticleEmitter
  60550. */
  60551. function BoxParticleEmitter() {
  60552. /**
  60553. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60554. */
  60555. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  60556. /**
  60557. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60558. */
  60559. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  60560. /**
  60561. * 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.
  60562. */
  60563. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  60564. /**
  60565. * 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.
  60566. */
  60567. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  60568. }
  60569. /**
  60570. * Called by the particle System when the direction is computed for the created particle.
  60571. * @param worldMatrix is the world matrix of the particle system
  60572. * @param directionToUpdate is the direction vector to update with the result
  60573. * @param particle is the particle we are computed the direction for
  60574. */
  60575. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60576. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  60577. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  60578. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  60579. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  60580. };
  60581. /**
  60582. * Called by the particle System when the position is computed for the created particle.
  60583. * @param worldMatrix is the world matrix of the particle system
  60584. * @param positionToUpdate is the position vector to update with the result
  60585. * @param particle is the particle we are computed the position for
  60586. */
  60587. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60588. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  60589. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  60590. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  60591. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  60592. };
  60593. /**
  60594. * Clones the current emitter and returns a copy of it
  60595. * @returns the new emitter
  60596. */
  60597. BoxParticleEmitter.prototype.clone = function () {
  60598. var newOne = new BoxParticleEmitter();
  60599. BABYLON.Tools.DeepCopy(this, newOne);
  60600. return newOne;
  60601. };
  60602. /**
  60603. * Called by the GPUParticleSystem to setup the update shader
  60604. * @param effect defines the update shader
  60605. */
  60606. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  60607. effect.setVector3("direction1", this.direction1);
  60608. effect.setVector3("direction2", this.direction2);
  60609. effect.setVector3("minEmitBox", this.minEmitBox);
  60610. effect.setVector3("maxEmitBox", this.maxEmitBox);
  60611. };
  60612. /**
  60613. * Returns a string to use to update the GPU particles update shader
  60614. * @returns a string containng the defines string
  60615. */
  60616. BoxParticleEmitter.prototype.getEffectDefines = function () {
  60617. return "#define BOXEMITTER";
  60618. };
  60619. /**
  60620. * Returns the string "BoxParticleEmitter"
  60621. * @returns a string containing the class name
  60622. */
  60623. BoxParticleEmitter.prototype.getClassName = function () {
  60624. return "BoxParticleEmitter";
  60625. };
  60626. /**
  60627. * Serializes the particle system to a JSON object.
  60628. * @returns the JSON object
  60629. */
  60630. BoxParticleEmitter.prototype.serialize = function () {
  60631. var serializationObject = {};
  60632. serializationObject.type = this.getClassName();
  60633. serializationObject.direction1 = this.direction1.asArray();
  60634. serializationObject.direction2 = this.direction2.asArray();
  60635. serializationObject.minEmitBox = this.minEmitBox.asArray();
  60636. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  60637. return serializationObject;
  60638. };
  60639. /**
  60640. * Parse properties from a JSON object
  60641. * @param serializationObject defines the JSON object
  60642. */
  60643. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  60644. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  60645. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  60646. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  60647. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  60648. };
  60649. return BoxParticleEmitter;
  60650. }());
  60651. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  60652. })(BABYLON || (BABYLON = {}));
  60653. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  60654. var BABYLON;
  60655. (function (BABYLON) {
  60656. /**
  60657. * Particle emitter emitting particles from the inside of a cylinder.
  60658. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  60659. */
  60660. var CylinderParticleEmitter = /** @class */ (function () {
  60661. /**
  60662. * Creates a new instance CylinderParticleEmitter
  60663. * @param radius the radius of the emission cylinder (1 by default)
  60664. * @param height the height of the emission cylinder (1 by default)
  60665. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60666. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  60667. */
  60668. function CylinderParticleEmitter(
  60669. /**
  60670. * The radius of the emission cylinder.
  60671. */
  60672. radius,
  60673. /**
  60674. * The height of the emission cylinder.
  60675. */
  60676. height,
  60677. /**
  60678. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  60679. */
  60680. radiusRange,
  60681. /**
  60682. * How much to randomize the particle direction [0-1].
  60683. */
  60684. directionRandomizer) {
  60685. if (radius === void 0) { radius = 1; }
  60686. if (height === void 0) { height = 1; }
  60687. if (radiusRange === void 0) { radiusRange = 1; }
  60688. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60689. this.radius = radius;
  60690. this.height = height;
  60691. this.radiusRange = radiusRange;
  60692. this.directionRandomizer = directionRandomizer;
  60693. }
  60694. /**
  60695. * Called by the particle System when the direction is computed for the created particle.
  60696. * @param worldMatrix is the world matrix of the particle system
  60697. * @param directionToUpdate is the direction vector to update with the result
  60698. * @param particle is the particle we are computed the direction for
  60699. */
  60700. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60701. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  60702. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  60703. var angle = Math.atan2(direction.x, direction.z);
  60704. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  60705. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  60706. direction.x = Math.sin(angle);
  60707. direction.z = Math.cos(angle);
  60708. direction.normalize();
  60709. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  60710. };
  60711. /**
  60712. * Called by the particle System when the position is computed for the created particle.
  60713. * @param worldMatrix is the world matrix of the particle system
  60714. * @param positionToUpdate is the position vector to update with the result
  60715. * @param particle is the particle we are computed the position for
  60716. */
  60717. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60718. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  60719. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  60720. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  60721. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  60722. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  60723. var xPos = positionRadius * Math.cos(angle);
  60724. var zPos = positionRadius * Math.sin(angle);
  60725. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  60726. };
  60727. /**
  60728. * Clones the current emitter and returns a copy of it
  60729. * @returns the new emitter
  60730. */
  60731. CylinderParticleEmitter.prototype.clone = function () {
  60732. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  60733. BABYLON.Tools.DeepCopy(this, newOne);
  60734. return newOne;
  60735. };
  60736. /**
  60737. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  60738. * @param effect defines the update shader
  60739. */
  60740. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  60741. effect.setFloat("radius", this.radius);
  60742. effect.setFloat("height", this.height);
  60743. effect.setFloat("radiusRange", this.radiusRange);
  60744. effect.setFloat("directionRandomizer", this.directionRandomizer);
  60745. };
  60746. /**
  60747. * Returns a string to use to update the GPU particles update shader
  60748. * @returns a string containng the defines string
  60749. */
  60750. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  60751. return "#define CYLINDEREMITTER";
  60752. };
  60753. /**
  60754. * Returns the string "CylinderParticleEmitter"
  60755. * @returns a string containing the class name
  60756. */
  60757. CylinderParticleEmitter.prototype.getClassName = function () {
  60758. return "CylinderParticleEmitter";
  60759. };
  60760. /**
  60761. * Serializes the particle system to a JSON object.
  60762. * @returns the JSON object
  60763. */
  60764. CylinderParticleEmitter.prototype.serialize = function () {
  60765. var serializationObject = {};
  60766. serializationObject.type = this.getClassName();
  60767. serializationObject.radius = this.radius;
  60768. serializationObject.height = this.height;
  60769. serializationObject.radiusRange = this.radiusRange;
  60770. serializationObject.directionRandomizer = this.directionRandomizer;
  60771. return serializationObject;
  60772. };
  60773. /**
  60774. * Parse properties from a JSON object
  60775. * @param serializationObject defines the JSON object
  60776. */
  60777. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  60778. this.radius = serializationObject.radius;
  60779. this.height = serializationObject.height;
  60780. this.radiusRange = serializationObject.radiusRange;
  60781. this.directionRandomizer = serializationObject.directionRandomizer;
  60782. };
  60783. return CylinderParticleEmitter;
  60784. }());
  60785. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  60786. /**
  60787. * Particle emitter emitting particles from the inside of a cylinder.
  60788. * It emits the particles randomly between two vectors.
  60789. */
  60790. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  60791. __extends(CylinderDirectedParticleEmitter, _super);
  60792. /**
  60793. * Creates a new instance CylinderDirectedParticleEmitter
  60794. * @param radius the radius of the emission cylinder (1 by default)
  60795. * @param height the height of the emission cylinder (1 by default)
  60796. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60797. * @param direction1 the min limit of the emission direction (up vector by default)
  60798. * @param direction2 the max limit of the emission direction (up vector by default)
  60799. */
  60800. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  60801. /**
  60802. * The min limit of the emission direction.
  60803. */
  60804. direction1,
  60805. /**
  60806. * The max limit of the emission direction.
  60807. */
  60808. direction2) {
  60809. if (radius === void 0) { radius = 1; }
  60810. if (height === void 0) { height = 1; }
  60811. if (radiusRange === void 0) { radiusRange = 1; }
  60812. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  60813. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  60814. var _this = _super.call(this, radius, height, radiusRange) || this;
  60815. _this.direction1 = direction1;
  60816. _this.direction2 = direction2;
  60817. return _this;
  60818. }
  60819. /**
  60820. * Called by the particle System when the direction is computed for the created particle.
  60821. * @param worldMatrix is the world matrix of the particle system
  60822. * @param directionToUpdate is the direction vector to update with the result
  60823. * @param particle is the particle we are computed the direction for
  60824. */
  60825. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60826. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  60827. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  60828. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  60829. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  60830. };
  60831. /**
  60832. * Clones the current emitter and returns a copy of it
  60833. * @returns the new emitter
  60834. */
  60835. CylinderDirectedParticleEmitter.prototype.clone = function () {
  60836. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  60837. BABYLON.Tools.DeepCopy(this, newOne);
  60838. return newOne;
  60839. };
  60840. /**
  60841. * Called by the GPUParticleSystem to setup the update shader
  60842. * @param effect defines the update shader
  60843. */
  60844. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  60845. effect.setFloat("radius", this.radius);
  60846. effect.setFloat("height", this.height);
  60847. effect.setFloat("radiusRange", this.radiusRange);
  60848. effect.setVector3("direction1", this.direction1);
  60849. effect.setVector3("direction2", this.direction2);
  60850. };
  60851. /**
  60852. * Returns a string to use to update the GPU particles update shader
  60853. * @returns a string containng the defines string
  60854. */
  60855. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  60856. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  60857. };
  60858. /**
  60859. * Returns the string "CylinderDirectedParticleEmitter"
  60860. * @returns a string containing the class name
  60861. */
  60862. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  60863. return "CylinderDirectedParticleEmitter";
  60864. };
  60865. /**
  60866. * Serializes the particle system to a JSON object.
  60867. * @returns the JSON object
  60868. */
  60869. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  60870. var serializationObject = _super.prototype.serialize.call(this);
  60871. serializationObject.direction1 = this.direction1.asArray();
  60872. serializationObject.direction2 = this.direction2.asArray();
  60873. return serializationObject;
  60874. };
  60875. /**
  60876. * Parse properties from a JSON object
  60877. * @param serializationObject defines the JSON object
  60878. */
  60879. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  60880. _super.prototype.parse.call(this, serializationObject);
  60881. this.direction1.copyFrom(serializationObject.direction1);
  60882. this.direction2.copyFrom(serializationObject.direction2);
  60883. };
  60884. return CylinderDirectedParticleEmitter;
  60885. }(CylinderParticleEmitter));
  60886. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  60887. })(BABYLON || (BABYLON = {}));
  60888. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  60889. var BABYLON;
  60890. (function (BABYLON) {
  60891. /**
  60892. * Particle emitter emitting particles from the inside of a cone.
  60893. * It emits the particles alongside the cone volume from the base to the particle.
  60894. * The emission direction might be randomized.
  60895. */
  60896. var ConeParticleEmitter = /** @class */ (function () {
  60897. /**
  60898. * Creates a new instance ConeParticleEmitter
  60899. * @param radius the radius of the emission cone (1 by default)
  60900. * @param angles the cone base angle (PI by default)
  60901. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  60902. */
  60903. function ConeParticleEmitter(radius, angle,
  60904. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  60905. directionRandomizer) {
  60906. if (radius === void 0) { radius = 1; }
  60907. if (angle === void 0) { angle = Math.PI; }
  60908. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60909. this.directionRandomizer = directionRandomizer;
  60910. /**
  60911. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  60912. */
  60913. this.radiusRange = 1;
  60914. /**
  60915. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  60916. */
  60917. this.heightRange = 1;
  60918. /**
  60919. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  60920. */
  60921. this.emitFromSpawnPointOnly = false;
  60922. this.angle = angle;
  60923. this.radius = radius;
  60924. }
  60925. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  60926. /**
  60927. * Gets or sets the radius of the emission cone
  60928. */
  60929. get: function () {
  60930. return this._radius;
  60931. },
  60932. set: function (value) {
  60933. this._radius = value;
  60934. this._buildHeight();
  60935. },
  60936. enumerable: true,
  60937. configurable: true
  60938. });
  60939. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  60940. /**
  60941. * Gets or sets the angle of the emission cone
  60942. */
  60943. get: function () {
  60944. return this._angle;
  60945. },
  60946. set: function (value) {
  60947. this._angle = value;
  60948. this._buildHeight();
  60949. },
  60950. enumerable: true,
  60951. configurable: true
  60952. });
  60953. ConeParticleEmitter.prototype._buildHeight = function () {
  60954. if (this._angle !== 0) {
  60955. this._height = this._radius / Math.tan(this._angle / 2);
  60956. }
  60957. else {
  60958. this._height = 1;
  60959. }
  60960. };
  60961. /**
  60962. * Called by the particle System when the direction is computed for the created particle.
  60963. * @param worldMatrix is the world matrix of the particle system
  60964. * @param directionToUpdate is the direction vector to update with the result
  60965. * @param particle is the particle we are computed the direction for
  60966. */
  60967. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60968. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  60969. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  60970. }
  60971. else {
  60972. // measure the direction Vector from the emitter to the particle.
  60973. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  60974. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60975. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60976. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60977. direction.x += randX;
  60978. direction.y += randY;
  60979. direction.z += randZ;
  60980. direction.normalize();
  60981. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  60982. }
  60983. };
  60984. /**
  60985. * Called by the particle System when the position is computed for the created particle.
  60986. * @param worldMatrix is the world matrix of the particle system
  60987. * @param positionToUpdate is the position vector to update with the result
  60988. * @param particle is the particle we are computed the position for
  60989. */
  60990. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60991. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  60992. var h;
  60993. if (!this.emitFromSpawnPointOnly) {
  60994. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  60995. // Better distribution in a cone at normal angles.
  60996. h = 1 - h * h;
  60997. }
  60998. else {
  60999. h = 0.0001;
  61000. }
  61001. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  61002. radius = radius * h;
  61003. var randX = radius * Math.sin(s);
  61004. var randZ = radius * Math.cos(s);
  61005. var randY = h * this._height;
  61006. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  61007. };
  61008. /**
  61009. * Clones the current emitter and returns a copy of it
  61010. * @returns the new emitter
  61011. */
  61012. ConeParticleEmitter.prototype.clone = function () {
  61013. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  61014. BABYLON.Tools.DeepCopy(this, newOne);
  61015. return newOne;
  61016. };
  61017. /**
  61018. * Called by the GPUParticleSystem to setup the update shader
  61019. * @param effect defines the update shader
  61020. */
  61021. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  61022. effect.setFloat2("radius", this._radius, this.radiusRange);
  61023. effect.setFloat("coneAngle", this._angle);
  61024. effect.setFloat2("height", this._height, this.heightRange);
  61025. effect.setFloat("directionRandomizer", this.directionRandomizer);
  61026. };
  61027. /**
  61028. * Returns a string to use to update the GPU particles update shader
  61029. * @returns a string containng the defines string
  61030. */
  61031. ConeParticleEmitter.prototype.getEffectDefines = function () {
  61032. var defines = "#define CONEEMITTER";
  61033. if (this.emitFromSpawnPointOnly) {
  61034. defines += "\n#define CONEEMITTERSPAWNPOINT";
  61035. }
  61036. return defines;
  61037. };
  61038. /**
  61039. * Returns the string "ConeParticleEmitter"
  61040. * @returns a string containing the class name
  61041. */
  61042. ConeParticleEmitter.prototype.getClassName = function () {
  61043. return "ConeParticleEmitter";
  61044. };
  61045. /**
  61046. * Serializes the particle system to a JSON object.
  61047. * @returns the JSON object
  61048. */
  61049. ConeParticleEmitter.prototype.serialize = function () {
  61050. var serializationObject = {};
  61051. serializationObject.type = this.getClassName();
  61052. serializationObject.radius = this._radius;
  61053. serializationObject.angle = this._angle;
  61054. serializationObject.directionRandomizer = this.directionRandomizer;
  61055. return serializationObject;
  61056. };
  61057. /**
  61058. * Parse properties from a JSON object
  61059. * @param serializationObject defines the JSON object
  61060. */
  61061. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  61062. this.radius = serializationObject.radius;
  61063. this.angle = serializationObject.angle;
  61064. this.directionRandomizer = serializationObject.directionRandomizer;
  61065. };
  61066. return ConeParticleEmitter;
  61067. }());
  61068. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  61069. })(BABYLON || (BABYLON = {}));
  61070. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  61071. var BABYLON;
  61072. (function (BABYLON) {
  61073. /**
  61074. * Particle emitter emitting particles from the inside of a sphere.
  61075. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  61076. */
  61077. var SphereParticleEmitter = /** @class */ (function () {
  61078. /**
  61079. * Creates a new instance SphereParticleEmitter
  61080. * @param radius the radius of the emission sphere (1 by default)
  61081. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  61082. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  61083. */
  61084. function SphereParticleEmitter(
  61085. /**
  61086. * The radius of the emission sphere.
  61087. */
  61088. radius,
  61089. /**
  61090. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  61091. */
  61092. radiusRange,
  61093. /**
  61094. * How much to randomize the particle direction [0-1].
  61095. */
  61096. directionRandomizer) {
  61097. if (radius === void 0) { radius = 1; }
  61098. if (radiusRange === void 0) { radiusRange = 1; }
  61099. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  61100. this.radius = radius;
  61101. this.radiusRange = radiusRange;
  61102. this.directionRandomizer = directionRandomizer;
  61103. }
  61104. /**
  61105. * Called by the particle System when the direction is computed for the created particle.
  61106. * @param worldMatrix is the world matrix of the particle system
  61107. * @param directionToUpdate is the direction vector to update with the result
  61108. * @param particle is the particle we are computed the direction for
  61109. */
  61110. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61111. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  61112. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61113. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61114. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61115. direction.x += randX;
  61116. direction.y += randY;
  61117. direction.z += randZ;
  61118. direction.normalize();
  61119. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  61120. };
  61121. /**
  61122. * Called by the particle System when the position is computed for the created particle.
  61123. * @param worldMatrix is the world matrix of the particle system
  61124. * @param positionToUpdate is the position vector to update with the result
  61125. * @param particle is the particle we are computed the position for
  61126. */
  61127. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61128. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  61129. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  61130. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  61131. var theta = Math.acos(2 * v - 1);
  61132. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  61133. var randY = randRadius * Math.cos(theta);
  61134. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  61135. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  61136. };
  61137. /**
  61138. * Clones the current emitter and returns a copy of it
  61139. * @returns the new emitter
  61140. */
  61141. SphereParticleEmitter.prototype.clone = function () {
  61142. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  61143. BABYLON.Tools.DeepCopy(this, newOne);
  61144. return newOne;
  61145. };
  61146. /**
  61147. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  61148. * @param effect defines the update shader
  61149. */
  61150. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  61151. effect.setFloat("radius", this.radius);
  61152. effect.setFloat("radiusRange", this.radiusRange);
  61153. effect.setFloat("directionRandomizer", this.directionRandomizer);
  61154. };
  61155. /**
  61156. * Returns a string to use to update the GPU particles update shader
  61157. * @returns a string containng the defines string
  61158. */
  61159. SphereParticleEmitter.prototype.getEffectDefines = function () {
  61160. return "#define SPHEREEMITTER";
  61161. };
  61162. /**
  61163. * Returns the string "SphereParticleEmitter"
  61164. * @returns a string containing the class name
  61165. */
  61166. SphereParticleEmitter.prototype.getClassName = function () {
  61167. return "SphereParticleEmitter";
  61168. };
  61169. /**
  61170. * Serializes the particle system to a JSON object.
  61171. * @returns the JSON object
  61172. */
  61173. SphereParticleEmitter.prototype.serialize = function () {
  61174. var serializationObject = {};
  61175. serializationObject.type = this.getClassName();
  61176. serializationObject.radius = this.radius;
  61177. serializationObject.radiusRange = this.radiusRange;
  61178. serializationObject.directionRandomizer = this.directionRandomizer;
  61179. return serializationObject;
  61180. };
  61181. /**
  61182. * Parse properties from a JSON object
  61183. * @param serializationObject defines the JSON object
  61184. */
  61185. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  61186. this.radius = serializationObject.radius;
  61187. this.radiusRange = serializationObject.radiusRange;
  61188. this.directionRandomizer = serializationObject.directionRandomizer;
  61189. };
  61190. return SphereParticleEmitter;
  61191. }());
  61192. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  61193. /**
  61194. * Particle emitter emitting particles from the inside of a sphere.
  61195. * It emits the particles randomly between two vectors.
  61196. */
  61197. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  61198. __extends(SphereDirectedParticleEmitter, _super);
  61199. /**
  61200. * Creates a new instance SphereDirectedParticleEmitter
  61201. * @param radius the radius of the emission sphere (1 by default)
  61202. * @param direction1 the min limit of the emission direction (up vector by default)
  61203. * @param direction2 the max limit of the emission direction (up vector by default)
  61204. */
  61205. function SphereDirectedParticleEmitter(radius,
  61206. /**
  61207. * The min limit of the emission direction.
  61208. */
  61209. direction1,
  61210. /**
  61211. * The max limit of the emission direction.
  61212. */
  61213. direction2) {
  61214. if (radius === void 0) { radius = 1; }
  61215. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  61216. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  61217. var _this = _super.call(this, radius) || this;
  61218. _this.direction1 = direction1;
  61219. _this.direction2 = direction2;
  61220. return _this;
  61221. }
  61222. /**
  61223. * Called by the particle System when the direction is computed for the created particle.
  61224. * @param worldMatrix is the world matrix of the particle system
  61225. * @param directionToUpdate is the direction vector to update with the result
  61226. * @param particle is the particle we are computed the direction for
  61227. */
  61228. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61229. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  61230. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  61231. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  61232. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  61233. };
  61234. /**
  61235. * Clones the current emitter and returns a copy of it
  61236. * @returns the new emitter
  61237. */
  61238. SphereDirectedParticleEmitter.prototype.clone = function () {
  61239. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  61240. BABYLON.Tools.DeepCopy(this, newOne);
  61241. return newOne;
  61242. };
  61243. /**
  61244. * Called by the GPUParticleSystem to setup the update shader
  61245. * @param effect defines the update shader
  61246. */
  61247. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  61248. effect.setFloat("radius", this.radius);
  61249. effect.setFloat("radiusRange", this.radiusRange);
  61250. effect.setVector3("direction1", this.direction1);
  61251. effect.setVector3("direction2", this.direction2);
  61252. };
  61253. /**
  61254. * Returns a string to use to update the GPU particles update shader
  61255. * @returns a string containng the defines string
  61256. */
  61257. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  61258. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  61259. };
  61260. /**
  61261. * Returns the string "SphereDirectedParticleEmitter"
  61262. * @returns a string containing the class name
  61263. */
  61264. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  61265. return "SphereDirectedParticleEmitter";
  61266. };
  61267. /**
  61268. * Serializes the particle system to a JSON object.
  61269. * @returns the JSON object
  61270. */
  61271. SphereDirectedParticleEmitter.prototype.serialize = function () {
  61272. var serializationObject = _super.prototype.serialize.call(this);
  61273. serializationObject.direction1 = this.direction1.asArray();
  61274. serializationObject.direction2 = this.direction2.asArray();
  61275. return serializationObject;
  61276. };
  61277. /**
  61278. * Parse properties from a JSON object
  61279. * @param serializationObject defines the JSON object
  61280. */
  61281. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  61282. _super.prototype.parse.call(this, serializationObject);
  61283. this.direction1.copyFrom(serializationObject.direction1);
  61284. this.direction2.copyFrom(serializationObject.direction2);
  61285. };
  61286. return SphereDirectedParticleEmitter;
  61287. }(SphereParticleEmitter));
  61288. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  61289. })(BABYLON || (BABYLON = {}));
  61290. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  61291. var BABYLON;
  61292. (function (BABYLON) {
  61293. /**
  61294. * Particle emitter emitting particles from the inside of a hemisphere.
  61295. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  61296. */
  61297. var HemisphericParticleEmitter = /** @class */ (function () {
  61298. /**
  61299. * Creates a new instance HemisphericParticleEmitter
  61300. * @param radius the radius of the emission hemisphere (1 by default)
  61301. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  61302. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  61303. */
  61304. function HemisphericParticleEmitter(
  61305. /**
  61306. * The radius of the emission hemisphere.
  61307. */
  61308. radius,
  61309. /**
  61310. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  61311. */
  61312. radiusRange,
  61313. /**
  61314. * How much to randomize the particle direction [0-1].
  61315. */
  61316. directionRandomizer) {
  61317. if (radius === void 0) { radius = 1; }
  61318. if (radiusRange === void 0) { radiusRange = 1; }
  61319. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  61320. this.radius = radius;
  61321. this.radiusRange = radiusRange;
  61322. this.directionRandomizer = directionRandomizer;
  61323. }
  61324. /**
  61325. * Called by the particle System when the direction is computed for the created particle.
  61326. * @param worldMatrix is the world matrix of the particle system
  61327. * @param directionToUpdate is the direction vector to update with the result
  61328. * @param particle is the particle we are computed the direction for
  61329. */
  61330. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61331. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  61332. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61333. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61334. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61335. direction.x += randX;
  61336. direction.y += randY;
  61337. direction.z += randZ;
  61338. direction.normalize();
  61339. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  61340. };
  61341. /**
  61342. * Called by the particle System when the position is computed for the created particle.
  61343. * @param worldMatrix is the world matrix of the particle system
  61344. * @param positionToUpdate is the position vector to update with the result
  61345. * @param particle is the particle we are computed the position for
  61346. */
  61347. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61348. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  61349. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  61350. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  61351. var theta = Math.acos(2 * v - 1);
  61352. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  61353. var randY = randRadius * Math.cos(theta);
  61354. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  61355. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  61356. };
  61357. /**
  61358. * Clones the current emitter and returns a copy of it
  61359. * @returns the new emitter
  61360. */
  61361. HemisphericParticleEmitter.prototype.clone = function () {
  61362. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  61363. BABYLON.Tools.DeepCopy(this, newOne);
  61364. return newOne;
  61365. };
  61366. /**
  61367. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  61368. * @param effect defines the update shader
  61369. */
  61370. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  61371. effect.setFloat("radius", this.radius);
  61372. effect.setFloat("radiusRange", this.radiusRange);
  61373. effect.setFloat("directionRandomizer", this.directionRandomizer);
  61374. };
  61375. /**
  61376. * Returns a string to use to update the GPU particles update shader
  61377. * @returns a string containng the defines string
  61378. */
  61379. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  61380. return "#define HEMISPHERICEMITTER";
  61381. };
  61382. /**
  61383. * Returns the string "HemisphericParticleEmitter"
  61384. * @returns a string containing the class name
  61385. */
  61386. HemisphericParticleEmitter.prototype.getClassName = function () {
  61387. return "HemisphericParticleEmitter";
  61388. };
  61389. /**
  61390. * Serializes the particle system to a JSON object.
  61391. * @returns the JSON object
  61392. */
  61393. HemisphericParticleEmitter.prototype.serialize = function () {
  61394. var serializationObject = {};
  61395. serializationObject.type = this.getClassName();
  61396. serializationObject.radius = this.radius;
  61397. serializationObject.radiusRange = this.radiusRange;
  61398. serializationObject.directionRandomizer = this.directionRandomizer;
  61399. return serializationObject;
  61400. };
  61401. /**
  61402. * Parse properties from a JSON object
  61403. * @param serializationObject defines the JSON object
  61404. */
  61405. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  61406. this.radius = serializationObject.radius;
  61407. this.radiusRange = serializationObject.radiusRange;
  61408. this.directionRandomizer = serializationObject.directionRandomizer;
  61409. };
  61410. return HemisphericParticleEmitter;
  61411. }());
  61412. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  61413. })(BABYLON || (BABYLON = {}));
  61414. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  61415. var BABYLON;
  61416. (function (BABYLON) {
  61417. /**
  61418. * Particle emitter emitting particles from a point.
  61419. * It emits the particles randomly between 2 given directions.
  61420. */
  61421. var PointParticleEmitter = /** @class */ (function () {
  61422. /**
  61423. * Creates a new instance PointParticleEmitter
  61424. */
  61425. function PointParticleEmitter() {
  61426. /**
  61427. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  61428. */
  61429. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  61430. /**
  61431. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  61432. */
  61433. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  61434. }
  61435. /**
  61436. * Called by the particle System when the direction is computed for the created particle.
  61437. * @param worldMatrix is the world matrix of the particle system
  61438. * @param directionToUpdate is the direction vector to update with the result
  61439. * @param particle is the particle we are computed the direction for
  61440. */
  61441. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61442. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  61443. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  61444. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  61445. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  61446. };
  61447. /**
  61448. * Called by the particle System when the position is computed for the created particle.
  61449. * @param worldMatrix is the world matrix of the particle system
  61450. * @param positionToUpdate is the position vector to update with the result
  61451. * @param particle is the particle we are computed the position for
  61452. */
  61453. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61454. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  61455. };
  61456. /**
  61457. * Clones the current emitter and returns a copy of it
  61458. * @returns the new emitter
  61459. */
  61460. PointParticleEmitter.prototype.clone = function () {
  61461. var newOne = new PointParticleEmitter();
  61462. BABYLON.Tools.DeepCopy(this, newOne);
  61463. return newOne;
  61464. };
  61465. /**
  61466. * Called by the GPUParticleSystem to setup the update shader
  61467. * @param effect defines the update shader
  61468. */
  61469. PointParticleEmitter.prototype.applyToShader = function (effect) {
  61470. effect.setVector3("direction1", this.direction1);
  61471. effect.setVector3("direction2", this.direction2);
  61472. };
  61473. /**
  61474. * Returns a string to use to update the GPU particles update shader
  61475. * @returns a string containng the defines string
  61476. */
  61477. PointParticleEmitter.prototype.getEffectDefines = function () {
  61478. return "#define POINTEMITTER";
  61479. };
  61480. /**
  61481. * Returns the string "PointParticleEmitter"
  61482. * @returns a string containing the class name
  61483. */
  61484. PointParticleEmitter.prototype.getClassName = function () {
  61485. return "PointParticleEmitter";
  61486. };
  61487. /**
  61488. * Serializes the particle system to a JSON object.
  61489. * @returns the JSON object
  61490. */
  61491. PointParticleEmitter.prototype.serialize = function () {
  61492. var serializationObject = {};
  61493. serializationObject.type = this.getClassName();
  61494. serializationObject.direction1 = this.direction1.asArray();
  61495. serializationObject.direction2 = this.direction2.asArray();
  61496. return serializationObject;
  61497. };
  61498. /**
  61499. * Parse properties from a JSON object
  61500. * @param serializationObject defines the JSON object
  61501. */
  61502. PointParticleEmitter.prototype.parse = function (serializationObject) {
  61503. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  61504. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  61505. };
  61506. return PointParticleEmitter;
  61507. }());
  61508. BABYLON.PointParticleEmitter = PointParticleEmitter;
  61509. })(BABYLON || (BABYLON = {}));
  61510. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  61511. var BABYLON;
  61512. (function (BABYLON) {
  61513. // Adds the parsers to the scene parsers.
  61514. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  61515. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  61516. if (!individualParser) {
  61517. return;
  61518. }
  61519. // Particles Systems
  61520. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61521. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61522. var parsedParticleSystem = parsedData.particleSystems[index];
  61523. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  61524. }
  61525. }
  61526. });
  61527. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  61528. if (parsedParticleSystem.activeParticleCount) {
  61529. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61530. return ps;
  61531. }
  61532. else {
  61533. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61534. return ps;
  61535. }
  61536. });
  61537. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  61538. if (uniformsNames === void 0) { uniformsNames = []; }
  61539. if (samplers === void 0) { samplers = []; }
  61540. if (defines === void 0) { defines = ""; }
  61541. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  61542. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  61543. if (defines.indexOf(" BILLBOARD") === -1) {
  61544. defines += "\n#define BILLBOARD\n";
  61545. }
  61546. if (samplers.indexOf("diffuseSampler") === -1) {
  61547. samplers.push("diffuseSampler");
  61548. }
  61549. return this.createEffect({
  61550. vertex: "particles",
  61551. fragmentElement: fragmentName
  61552. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  61553. };
  61554. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  61555. var results = new Array();
  61556. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  61557. var particleSystem = this.getScene().particleSystems[index];
  61558. if (particleSystem.emitter === this) {
  61559. results.push(particleSystem);
  61560. }
  61561. }
  61562. return results;
  61563. };
  61564. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  61565. var results = new Array();
  61566. var descendants = this.getDescendants();
  61567. descendants.push(this);
  61568. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  61569. var particleSystem = this.getScene().particleSystems[index];
  61570. var emitter = particleSystem.emitter;
  61571. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  61572. results.push(particleSystem);
  61573. }
  61574. }
  61575. return results;
  61576. };
  61577. })(BABYLON || (BABYLON = {}));
  61578. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  61579. var BABYLON;
  61580. (function (BABYLON) {
  61581. /**
  61582. * Type of sub emitter
  61583. */
  61584. var SubEmitterType;
  61585. (function (SubEmitterType) {
  61586. /**
  61587. * Attached to the particle over it's lifetime
  61588. */
  61589. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  61590. /**
  61591. * Created when the particle dies
  61592. */
  61593. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  61594. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  61595. /**
  61596. * Sub emitter class used to emit particles from an existing particle
  61597. */
  61598. var SubEmitter = /** @class */ (function () {
  61599. /**
  61600. * Creates a sub emitter
  61601. * @param particleSystem the particle system to be used by the sub emitter
  61602. */
  61603. function SubEmitter(
  61604. /**
  61605. * the particle system to be used by the sub emitter
  61606. */
  61607. particleSystem) {
  61608. this.particleSystem = particleSystem;
  61609. /**
  61610. * Type of the submitter (Default: END)
  61611. */
  61612. this.type = SubEmitterType.END;
  61613. /**
  61614. * 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)
  61615. * Note: This only is supported when using an emitter of type Mesh
  61616. */
  61617. this.inheritDirection = false;
  61618. /**
  61619. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  61620. */
  61621. this.inheritedVelocityAmount = 0;
  61622. }
  61623. /**
  61624. * Clones the sub emitter
  61625. * @returns the cloned sub emitter
  61626. */
  61627. SubEmitter.prototype.clone = function () {
  61628. // Clone particle system
  61629. var emitter = this.particleSystem.emitter;
  61630. if (!emitter) {
  61631. emitter = new BABYLON.Vector3();
  61632. }
  61633. else if (emitter instanceof BABYLON.Vector3) {
  61634. emitter = emitter.clone();
  61635. }
  61636. else if (emitter instanceof BABYLON.AbstractMesh) {
  61637. emitter = new BABYLON.Mesh("", emitter.getScene());
  61638. emitter.isVisible = false;
  61639. }
  61640. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  61641. // Clone properties
  61642. clone.type = this.type;
  61643. clone.inheritDirection = this.inheritDirection;
  61644. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  61645. clone.particleSystem._disposeEmitterOnDispose = true;
  61646. clone.particleSystem.disposeOnStop = true;
  61647. return clone;
  61648. };
  61649. /**
  61650. * Serialize current object to a JSON object
  61651. * @returns the serialized object
  61652. */
  61653. SubEmitter.prototype.serialize = function () {
  61654. var serializationObject = {};
  61655. serializationObject.type = this.type;
  61656. serializationObject.inheritDirection = this.inheritDirection;
  61657. serializationObject.inheritedVelocityAmount = this.inheritedVelocityAmount;
  61658. serializationObject.particleSystem = this.particleSystem.serialize();
  61659. return serializationObject;
  61660. };
  61661. /**
  61662. * Creates a new SubEmitter from a serialized JSON version
  61663. * @param serializationObject defines the JSON object to read from
  61664. * @param scene defines the hosting scene
  61665. * @param rootUrl defines the rootUrl for data loading
  61666. * @returns a new SubEmitter
  61667. */
  61668. SubEmitter.Parse = function (serializationObject, scene, rootUrl) {
  61669. var system = serializationObject.particleSystem;
  61670. var subEmitter = new SubEmitter(BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  61671. subEmitter.type = serializationObject.type;
  61672. subEmitter.inheritDirection = serializationObject.inheritDirection;
  61673. subEmitter.inheritedVelocityAmount = serializationObject.inheritedVelocityAmount;
  61674. subEmitter.particleSystem._isSubEmitter = true;
  61675. return subEmitter;
  61676. };
  61677. /** Release associated resources */
  61678. SubEmitter.prototype.dispose = function () {
  61679. this.particleSystem.dispose();
  61680. };
  61681. return SubEmitter;
  61682. }());
  61683. BABYLON.SubEmitter = SubEmitter;
  61684. })(BABYLON || (BABYLON = {}));
  61685. //# sourceMappingURL=babylon.subEmitter.js.map
  61686. var BABYLON;
  61687. (function (BABYLON) {
  61688. /**
  61689. * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh.
  61690. *
  61691. * This returned material effects how the mesh will look based on the code in the shaders.
  61692. *
  61693. * @see http://doc.babylonjs.com/how_to/shader_material
  61694. */
  61695. var ShaderMaterial = /** @class */ (function (_super) {
  61696. __extends(ShaderMaterial, _super);
  61697. /**
  61698. * Instantiate a new shader material.
  61699. * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh.
  61700. * This returned material effects how the mesh will look based on the code in the shaders.
  61701. * @see http://doc.babylonjs.com/how_to/shader_material
  61702. * @param name Define the name of the material in the scene
  61703. * @param scene Define the scene the material belongs to
  61704. * @param shaderPath Defines the route to the shader code in one of three ways:
  61705. * - object - { vertex: "custom", fragment: "custom" }, used with BABYLON.Effect.ShadersStore["customVertexShader"] and BABYLON.Effect.ShadersStore["customFragmentShader"]
  61706. * - object - { vertexElement: "vertexShaderCode", fragmentElement: "fragmentShaderCode" }, used with shader code in <script> tags
  61707. * - string - "./COMMON_NAME", used with external files COMMON_NAME.vertex.fx and COMMON_NAME.fragment.fx in index.html folder.
  61708. * @param options Define the options used to create the shader
  61709. */
  61710. function ShaderMaterial(name, scene, shaderPath, options) {
  61711. if (options === void 0) { options = {}; }
  61712. var _this = _super.call(this, name, scene) || this;
  61713. _this._textures = {};
  61714. _this._textureArrays = {};
  61715. _this._floats = {};
  61716. _this._ints = {};
  61717. _this._floatsArrays = {};
  61718. _this._colors3 = {};
  61719. _this._colors3Arrays = {};
  61720. _this._colors4 = {};
  61721. _this._vectors2 = {};
  61722. _this._vectors3 = {};
  61723. _this._vectors4 = {};
  61724. _this._matrices = {};
  61725. _this._matrices3x3 = {};
  61726. _this._matrices2x2 = {};
  61727. _this._vectors2Arrays = {};
  61728. _this._vectors3Arrays = {};
  61729. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  61730. _this._shaderPath = shaderPath;
  61731. _this._options = __assign({ needAlphaBlending: false, needAlphaTesting: false, attributes: ["position", "normal", "uv"], uniforms: ["worldViewProjection"], uniformBuffers: [], samplers: [], defines: [] }, options);
  61732. return _this;
  61733. }
  61734. /**
  61735. * Gets the current class name of the material e.g. "ShaderMaterial"
  61736. * Mainly use in serialization.
  61737. * @returns the class name
  61738. */
  61739. ShaderMaterial.prototype.getClassName = function () {
  61740. return "ShaderMaterial";
  61741. };
  61742. /**
  61743. * Specifies if the material will require alpha blending
  61744. * @returns a boolean specifying if alpha blending is needed
  61745. */
  61746. ShaderMaterial.prototype.needAlphaBlending = function () {
  61747. return (this.alpha < 1.0);
  61748. };
  61749. /**
  61750. * Specifies if this material should be rendered in alpha test mode
  61751. * @returns a boolean specifying if an alpha test is needed.
  61752. */
  61753. ShaderMaterial.prototype.needAlphaTesting = function () {
  61754. return this._options.needAlphaTesting;
  61755. };
  61756. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  61757. if (this._options.uniforms.indexOf(uniformName) === -1) {
  61758. this._options.uniforms.push(uniformName);
  61759. }
  61760. };
  61761. /**
  61762. * Set a texture in the shader.
  61763. * @param name Define the name of the uniform samplers as defined in the shader
  61764. * @param texture Define the texture to bind to this sampler
  61765. * @return the material itself allowing "fluent" like uniform updates
  61766. */
  61767. ShaderMaterial.prototype.setTexture = function (name, texture) {
  61768. if (this._options.samplers.indexOf(name) === -1) {
  61769. this._options.samplers.push(name);
  61770. }
  61771. this._textures[name] = texture;
  61772. return this;
  61773. };
  61774. /**
  61775. * Set a texture array in the shader.
  61776. * @param name Define the name of the uniform sampler array as defined in the shader
  61777. * @param textures Define the list of textures to bind to this sampler
  61778. * @return the material itself allowing "fluent" like uniform updates
  61779. */
  61780. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  61781. if (this._options.samplers.indexOf(name) === -1) {
  61782. this._options.samplers.push(name);
  61783. }
  61784. this._checkUniform(name);
  61785. this._textureArrays[name] = textures;
  61786. return this;
  61787. };
  61788. /**
  61789. * Set a float in the shader.
  61790. * @param name Define the name of the uniform as defined in the shader
  61791. * @param value Define the value to give to the uniform
  61792. * @return the material itself allowing "fluent" like uniform updates
  61793. */
  61794. ShaderMaterial.prototype.setFloat = function (name, value) {
  61795. this._checkUniform(name);
  61796. this._floats[name] = value;
  61797. return this;
  61798. };
  61799. /**
  61800. * Set a int in the shader.
  61801. * @param name Define the name of the uniform as defined in the shader
  61802. * @param value Define the value to give to the uniform
  61803. * @return the material itself allowing "fluent" like uniform updates
  61804. */
  61805. ShaderMaterial.prototype.setInt = function (name, value) {
  61806. this._checkUniform(name);
  61807. this._ints[name] = value;
  61808. return this;
  61809. };
  61810. /**
  61811. * Set an array of floats in the shader.
  61812. * @param name Define the name of the uniform as defined in the shader
  61813. * @param value Define the value to give to the uniform
  61814. * @return the material itself allowing "fluent" like uniform updates
  61815. */
  61816. ShaderMaterial.prototype.setFloats = function (name, value) {
  61817. this._checkUniform(name);
  61818. this._floatsArrays[name] = value;
  61819. return this;
  61820. };
  61821. /**
  61822. * Set a vec3 in the shader from a Color3.
  61823. * @param name Define the name of the uniform as defined in the shader
  61824. * @param value Define the value to give to the uniform
  61825. * @return the material itself allowing "fluent" like uniform updates
  61826. */
  61827. ShaderMaterial.prototype.setColor3 = function (name, value) {
  61828. this._checkUniform(name);
  61829. this._colors3[name] = value;
  61830. return this;
  61831. };
  61832. /**
  61833. * Set a vec3 array in the shader from a Color3 array.
  61834. * @param name Define the name of the uniform as defined in the shader
  61835. * @param value Define the value to give to the uniform
  61836. * @return the material itself allowing "fluent" like uniform updates
  61837. */
  61838. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  61839. this._checkUniform(name);
  61840. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  61841. color.toArray(arr, arr.length);
  61842. return arr;
  61843. }, []);
  61844. return this;
  61845. };
  61846. /**
  61847. * Set a vec4 in the shader from a Color4.
  61848. * @param name Define the name of the uniform as defined in the shader
  61849. * @param value Define the value to give to the uniform
  61850. * @return the material itself allowing "fluent" like uniform updates
  61851. */
  61852. ShaderMaterial.prototype.setColor4 = function (name, value) {
  61853. this._checkUniform(name);
  61854. this._colors4[name] = value;
  61855. return this;
  61856. };
  61857. /**
  61858. * Set a vec2 in the shader from a Vector2.
  61859. * @param name Define the name of the uniform as defined in the shader
  61860. * @param value Define the value to give to the uniform
  61861. * @return the material itself allowing "fluent" like uniform updates
  61862. */
  61863. ShaderMaterial.prototype.setVector2 = function (name, value) {
  61864. this._checkUniform(name);
  61865. this._vectors2[name] = value;
  61866. return this;
  61867. };
  61868. /**
  61869. * Set a vec3 in the shader from a Vector3.
  61870. * @param name Define the name of the uniform as defined in the shader
  61871. * @param value Define the value to give to the uniform
  61872. * @return the material itself allowing "fluent" like uniform updates
  61873. */
  61874. ShaderMaterial.prototype.setVector3 = function (name, value) {
  61875. this._checkUniform(name);
  61876. this._vectors3[name] = value;
  61877. return this;
  61878. };
  61879. /**
  61880. * Set a vec4 in the shader from a Vector4.
  61881. * @param name Define the name of the uniform as defined in the shader
  61882. * @param value Define the value to give to the uniform
  61883. * @return the material itself allowing "fluent" like uniform updates
  61884. */
  61885. ShaderMaterial.prototype.setVector4 = function (name, value) {
  61886. this._checkUniform(name);
  61887. this._vectors4[name] = value;
  61888. return this;
  61889. };
  61890. /**
  61891. * Set a mat4 in the shader from a Matrix.
  61892. * @param name Define the name of the uniform as defined in the shader
  61893. * @param value Define the value to give to the uniform
  61894. * @return the material itself allowing "fluent" like uniform updates
  61895. */
  61896. ShaderMaterial.prototype.setMatrix = function (name, value) {
  61897. this._checkUniform(name);
  61898. this._matrices[name] = value;
  61899. return this;
  61900. };
  61901. /**
  61902. * Set a mat3 in the shader from a Float32Array.
  61903. * @param name Define the name of the uniform as defined in the shader
  61904. * @param value Define the value to give to the uniform
  61905. * @return the material itself allowing "fluent" like uniform updates
  61906. */
  61907. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  61908. this._checkUniform(name);
  61909. this._matrices3x3[name] = value;
  61910. return this;
  61911. };
  61912. /**
  61913. * Set a mat2 in the shader from a Float32Array.
  61914. * @param name Define the name of the uniform as defined in the shader
  61915. * @param value Define the value to give to the uniform
  61916. * @return the material itself allowing "fluent" like uniform updates
  61917. */
  61918. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  61919. this._checkUniform(name);
  61920. this._matrices2x2[name] = value;
  61921. return this;
  61922. };
  61923. /**
  61924. * Set a vec2 array in the shader from a number array.
  61925. * @param name Define the name of the uniform as defined in the shader
  61926. * @param value Define the value to give to the uniform
  61927. * @return the material itself allowing "fluent" like uniform updates
  61928. */
  61929. ShaderMaterial.prototype.setArray2 = function (name, value) {
  61930. this._checkUniform(name);
  61931. this._vectors2Arrays[name] = value;
  61932. return this;
  61933. };
  61934. /**
  61935. * Set a vec3 array in the shader from a number array.
  61936. * @param name Define the name of the uniform as defined in the shader
  61937. * @param value Define the value to give to the uniform
  61938. * @return the material itself allowing "fluent" like uniform updates
  61939. */
  61940. ShaderMaterial.prototype.setArray3 = function (name, value) {
  61941. this._checkUniform(name);
  61942. this._vectors3Arrays[name] = value;
  61943. return this;
  61944. };
  61945. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  61946. if (!mesh) {
  61947. return true;
  61948. }
  61949. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  61950. return false;
  61951. }
  61952. return false;
  61953. };
  61954. /**
  61955. * Checks if the material is ready to render the requested mesh
  61956. * @param mesh Define the mesh to render
  61957. * @param useInstances Define whether or not the material is used with instances
  61958. * @returns true if ready, otherwise false
  61959. */
  61960. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  61961. var scene = this.getScene();
  61962. var engine = scene.getEngine();
  61963. if (!this.checkReadyOnEveryCall) {
  61964. if (this._renderId === scene.getRenderId()) {
  61965. if (this._checkCache(scene, mesh, useInstances)) {
  61966. return true;
  61967. }
  61968. }
  61969. }
  61970. // Instances
  61971. var defines = [];
  61972. var attribs = [];
  61973. var fallbacks = new BABYLON.EffectFallbacks();
  61974. for (var index = 0; index < this._options.defines.length; index++) {
  61975. defines.push(this._options.defines[index]);
  61976. }
  61977. for (var index = 0; index < this._options.attributes.length; index++) {
  61978. attribs.push(this._options.attributes[index]);
  61979. }
  61980. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  61981. attribs.push(BABYLON.VertexBuffer.ColorKind);
  61982. defines.push("#define VERTEXCOLOR");
  61983. }
  61984. if (useInstances) {
  61985. defines.push("#define INSTANCES");
  61986. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  61987. }
  61988. // Bones
  61989. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  61990. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61991. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61992. if (mesh.numBoneInfluencers > 4) {
  61993. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61994. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61995. }
  61996. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61997. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  61998. fallbacks.addCPUSkinningFallback(0, mesh);
  61999. if (this._options.uniforms.indexOf("mBones") === -1) {
  62000. this._options.uniforms.push("mBones");
  62001. }
  62002. }
  62003. else {
  62004. defines.push("#define NUM_BONE_INFLUENCERS 0");
  62005. }
  62006. // Textures
  62007. for (var name in this._textures) {
  62008. if (!this._textures[name].isReady()) {
  62009. return false;
  62010. }
  62011. }
  62012. // Alpha test
  62013. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  62014. defines.push("#define ALPHATEST");
  62015. }
  62016. var previousEffect = this._effect;
  62017. var join = defines.join("\n");
  62018. this._effect = engine.createEffect(this._shaderPath, {
  62019. attributes: attribs,
  62020. uniformsNames: this._options.uniforms,
  62021. uniformBuffersNames: this._options.uniformBuffers,
  62022. samplers: this._options.samplers,
  62023. defines: join,
  62024. fallbacks: fallbacks,
  62025. onCompiled: this.onCompiled,
  62026. onError: this.onError
  62027. }, engine);
  62028. if (!this._effect.isReady()) {
  62029. return false;
  62030. }
  62031. if (previousEffect !== this._effect) {
  62032. scene.resetCachedMaterial();
  62033. }
  62034. this._renderId = scene.getRenderId();
  62035. return true;
  62036. };
  62037. /**
  62038. * Binds the world matrix to the material
  62039. * @param world defines the world transformation matrix
  62040. */
  62041. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  62042. var scene = this.getScene();
  62043. if (!this._effect) {
  62044. return;
  62045. }
  62046. if (this._options.uniforms.indexOf("world") !== -1) {
  62047. this._effect.setMatrix("world", world);
  62048. }
  62049. if (this._options.uniforms.indexOf("worldView") !== -1) {
  62050. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  62051. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  62052. }
  62053. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  62054. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  62055. }
  62056. };
  62057. /**
  62058. * Binds the material to the mesh
  62059. * @param world defines the world transformation matrix
  62060. * @param mesh defines the mesh to bind the material to
  62061. */
  62062. ShaderMaterial.prototype.bind = function (world, mesh) {
  62063. // Std values
  62064. this.bindOnlyWorldMatrix(world);
  62065. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  62066. if (this._options.uniforms.indexOf("view") !== -1) {
  62067. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  62068. }
  62069. if (this._options.uniforms.indexOf("projection") !== -1) {
  62070. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  62071. }
  62072. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  62073. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  62074. }
  62075. // Bones
  62076. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  62077. var name;
  62078. // Texture
  62079. for (name in this._textures) {
  62080. this._effect.setTexture(name, this._textures[name]);
  62081. }
  62082. // Texture arrays
  62083. for (name in this._textureArrays) {
  62084. this._effect.setTextureArray(name, this._textureArrays[name]);
  62085. }
  62086. // Int
  62087. for (name in this._ints) {
  62088. this._effect.setInt(name, this._ints[name]);
  62089. }
  62090. // Float
  62091. for (name in this._floats) {
  62092. this._effect.setFloat(name, this._floats[name]);
  62093. }
  62094. // Floats
  62095. for (name in this._floatsArrays) {
  62096. this._effect.setArray(name, this._floatsArrays[name]);
  62097. }
  62098. // Color3
  62099. for (name in this._colors3) {
  62100. this._effect.setColor3(name, this._colors3[name]);
  62101. }
  62102. for (name in this._colors3Arrays) {
  62103. this._effect.setArray3(name, this._colors3Arrays[name]);
  62104. }
  62105. // Color4
  62106. for (name in this._colors4) {
  62107. var color = this._colors4[name];
  62108. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  62109. }
  62110. // Vector2
  62111. for (name in this._vectors2) {
  62112. this._effect.setVector2(name, this._vectors2[name]);
  62113. }
  62114. // Vector3
  62115. for (name in this._vectors3) {
  62116. this._effect.setVector3(name, this._vectors3[name]);
  62117. }
  62118. // Vector4
  62119. for (name in this._vectors4) {
  62120. this._effect.setVector4(name, this._vectors4[name]);
  62121. }
  62122. // Matrix
  62123. for (name in this._matrices) {
  62124. this._effect.setMatrix(name, this._matrices[name]);
  62125. }
  62126. // Matrix 3x3
  62127. for (name in this._matrices3x3) {
  62128. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  62129. }
  62130. // Matrix 2x2
  62131. for (name in this._matrices2x2) {
  62132. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  62133. }
  62134. // Vector2Array
  62135. for (name in this._vectors2Arrays) {
  62136. this._effect.setArray2(name, this._vectors2Arrays[name]);
  62137. }
  62138. // Vector3Array
  62139. for (name in this._vectors3Arrays) {
  62140. this._effect.setArray3(name, this._vectors3Arrays[name]);
  62141. }
  62142. }
  62143. this._afterBind(mesh);
  62144. };
  62145. /**
  62146. * Gets the active textures from the material
  62147. * @returns an array of textures
  62148. */
  62149. ShaderMaterial.prototype.getActiveTextures = function () {
  62150. var activeTextures = _super.prototype.getActiveTextures.call(this);
  62151. for (var name in this._textures) {
  62152. activeTextures.push(this._textures[name]);
  62153. }
  62154. for (var name in this._textureArrays) {
  62155. var array = this._textureArrays[name];
  62156. for (var index = 0; index < array.length; index++) {
  62157. activeTextures.push(array[index]);
  62158. }
  62159. }
  62160. return activeTextures;
  62161. };
  62162. /**
  62163. * Specifies if the material uses a texture
  62164. * @param texture defines the texture to check against the material
  62165. * @returns a boolean specifying if the material uses the texture
  62166. */
  62167. ShaderMaterial.prototype.hasTexture = function (texture) {
  62168. if (_super.prototype.hasTexture.call(this, texture)) {
  62169. return true;
  62170. }
  62171. for (var name in this._textures) {
  62172. if (this._textures[name] === texture) {
  62173. return true;
  62174. }
  62175. }
  62176. for (var name in this._textureArrays) {
  62177. var array = this._textureArrays[name];
  62178. for (var index = 0; index < array.length; index++) {
  62179. if (array[index] === texture) {
  62180. return true;
  62181. }
  62182. }
  62183. }
  62184. return false;
  62185. };
  62186. /**
  62187. * Makes a duplicate of the material, and gives it a new name
  62188. * @param name defines the new name for the duplicated material
  62189. * @returns the cloned material
  62190. */
  62191. ShaderMaterial.prototype.clone = function (name) {
  62192. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  62193. return newShaderMaterial;
  62194. };
  62195. /**
  62196. * Disposes the material
  62197. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  62198. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  62199. */
  62200. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  62201. if (forceDisposeTextures) {
  62202. var name;
  62203. for (name in this._textures) {
  62204. this._textures[name].dispose();
  62205. }
  62206. for (name in this._textureArrays) {
  62207. var array = this._textureArrays[name];
  62208. for (var index = 0; index < array.length; index++) {
  62209. array[index].dispose();
  62210. }
  62211. }
  62212. }
  62213. this._textures = {};
  62214. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  62215. };
  62216. /**
  62217. * Serializes this material in a JSON representation
  62218. * @returns the serialized material object
  62219. */
  62220. ShaderMaterial.prototype.serialize = function () {
  62221. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  62222. serializationObject.customType = "BABYLON.ShaderMaterial";
  62223. serializationObject.options = this._options;
  62224. serializationObject.shaderPath = this._shaderPath;
  62225. var name;
  62226. // Texture
  62227. serializationObject.textures = {};
  62228. for (name in this._textures) {
  62229. serializationObject.textures[name] = this._textures[name].serialize();
  62230. }
  62231. // Texture arrays
  62232. serializationObject.textureArrays = {};
  62233. for (name in this._textureArrays) {
  62234. serializationObject.textureArrays[name] = [];
  62235. var array = this._textureArrays[name];
  62236. for (var index = 0; index < array.length; index++) {
  62237. serializationObject.textureArrays[name].push(array[index].serialize());
  62238. }
  62239. }
  62240. // Float
  62241. serializationObject.floats = {};
  62242. for (name in this._floats) {
  62243. serializationObject.floats[name] = this._floats[name];
  62244. }
  62245. // Float s
  62246. serializationObject.FloatArrays = {};
  62247. for (name in this._floatsArrays) {
  62248. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  62249. }
  62250. // Color3
  62251. serializationObject.colors3 = {};
  62252. for (name in this._colors3) {
  62253. serializationObject.colors3[name] = this._colors3[name].asArray();
  62254. }
  62255. // Color3 array
  62256. serializationObject.colors3Arrays = {};
  62257. for (name in this._colors3Arrays) {
  62258. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  62259. }
  62260. // Color4
  62261. serializationObject.colors4 = {};
  62262. for (name in this._colors4) {
  62263. serializationObject.colors4[name] = this._colors4[name].asArray();
  62264. }
  62265. // Vector2
  62266. serializationObject.vectors2 = {};
  62267. for (name in this._vectors2) {
  62268. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  62269. }
  62270. // Vector3
  62271. serializationObject.vectors3 = {};
  62272. for (name in this._vectors3) {
  62273. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  62274. }
  62275. // Vector4
  62276. serializationObject.vectors4 = {};
  62277. for (name in this._vectors4) {
  62278. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  62279. }
  62280. // Matrix
  62281. serializationObject.matrices = {};
  62282. for (name in this._matrices) {
  62283. serializationObject.matrices[name] = this._matrices[name].asArray();
  62284. }
  62285. // Matrix 3x3
  62286. serializationObject.matrices3x3 = {};
  62287. for (name in this._matrices3x3) {
  62288. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  62289. }
  62290. // Matrix 2x2
  62291. serializationObject.matrices2x2 = {};
  62292. for (name in this._matrices2x2) {
  62293. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  62294. }
  62295. // Vector2Array
  62296. serializationObject.vectors2Arrays = {};
  62297. for (name in this._vectors2Arrays) {
  62298. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  62299. }
  62300. // Vector3Array
  62301. serializationObject.vectors3Arrays = {};
  62302. for (name in this._vectors3Arrays) {
  62303. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  62304. }
  62305. return serializationObject;
  62306. };
  62307. /**
  62308. * Creates a shader material from parsed shader material data
  62309. * @param source defines the JSON represnetation of the material
  62310. * @param scene defines the hosting scene
  62311. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  62312. * @returns a new material
  62313. */
  62314. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  62315. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  62316. var name;
  62317. // Texture
  62318. for (name in source.textures) {
  62319. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  62320. }
  62321. // Texture arrays
  62322. for (name in source.textureArrays) {
  62323. var array = source.textureArrays[name];
  62324. var textureArray = new Array();
  62325. for (var index = 0; index < array.length; index++) {
  62326. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  62327. }
  62328. material.setTextureArray(name, textureArray);
  62329. }
  62330. // Float
  62331. for (name in source.floats) {
  62332. material.setFloat(name, source.floats[name]);
  62333. }
  62334. // Float s
  62335. for (name in source.floatsArrays) {
  62336. material.setFloats(name, source.floatsArrays[name]);
  62337. }
  62338. // Color3
  62339. for (name in source.colors3) {
  62340. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  62341. }
  62342. // Color3 arrays
  62343. for (name in source.colors3Arrays) {
  62344. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  62345. if (i % 3 === 0) {
  62346. arr.push([num]);
  62347. }
  62348. else {
  62349. arr[arr.length - 1].push(num);
  62350. }
  62351. return arr;
  62352. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  62353. material.setColor3Array(name, colors);
  62354. }
  62355. // Color4
  62356. for (name in source.colors4) {
  62357. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  62358. }
  62359. // Vector2
  62360. for (name in source.vectors2) {
  62361. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  62362. }
  62363. // Vector3
  62364. for (name in source.vectors3) {
  62365. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  62366. }
  62367. // Vector4
  62368. for (name in source.vectors4) {
  62369. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  62370. }
  62371. // Matrix
  62372. for (name in source.matrices) {
  62373. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  62374. }
  62375. // Matrix 3x3
  62376. for (name in source.matrices3x3) {
  62377. material.setMatrix3x3(name, source.matrices3x3[name]);
  62378. }
  62379. // Matrix 2x2
  62380. for (name in source.matrices2x2) {
  62381. material.setMatrix2x2(name, source.matrices2x2[name]);
  62382. }
  62383. // Vector2Array
  62384. for (name in source.vectors2Arrays) {
  62385. material.setArray2(name, source.vectors2Arrays[name]);
  62386. }
  62387. // Vector3Array
  62388. for (name in source.vectors3Arrays) {
  62389. material.setArray3(name, source.vectors3Arrays[name]);
  62390. }
  62391. return material;
  62392. };
  62393. return ShaderMaterial;
  62394. }(BABYLON.Material));
  62395. BABYLON.ShaderMaterial = ShaderMaterial;
  62396. })(BABYLON || (BABYLON = {}));
  62397. //# sourceMappingURL=babylon.shaderMaterial.js.map
  62398. var BABYLON;
  62399. (function (BABYLON) {
  62400. var GroundMesh = /** @class */ (function (_super) {
  62401. __extends(GroundMesh, _super);
  62402. function GroundMesh(name, scene) {
  62403. var _this = _super.call(this, name, scene) || this;
  62404. _this.generateOctree = false;
  62405. return _this;
  62406. }
  62407. GroundMesh.prototype.getClassName = function () {
  62408. return "GroundMesh";
  62409. };
  62410. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  62411. get: function () {
  62412. return Math.min(this._subdivisionsX, this._subdivisionsY);
  62413. },
  62414. enumerable: true,
  62415. configurable: true
  62416. });
  62417. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  62418. get: function () {
  62419. return this._subdivisionsX;
  62420. },
  62421. enumerable: true,
  62422. configurable: true
  62423. });
  62424. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  62425. get: function () {
  62426. return this._subdivisionsY;
  62427. },
  62428. enumerable: true,
  62429. configurable: true
  62430. });
  62431. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  62432. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  62433. this._subdivisionsX = chunksCount;
  62434. this._subdivisionsY = chunksCount;
  62435. this.subdivide(chunksCount);
  62436. // Call the octree system optimization if it is defined.
  62437. var thisAsAny = this;
  62438. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  62439. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  62440. }
  62441. };
  62442. /**
  62443. * Returns a height (y) value in the Worl system :
  62444. * the ground altitude at the coordinates (x, z) expressed in the World system.
  62445. * Returns the ground y position if (x, z) are outside the ground surface.
  62446. */
  62447. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  62448. var world = this.getWorldMatrix();
  62449. var invMat = BABYLON.Tmp.Matrix[5];
  62450. world.invertToRef(invMat);
  62451. var tmpVect = BABYLON.Tmp.Vector3[8];
  62452. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  62453. x = tmpVect.x;
  62454. z = tmpVect.z;
  62455. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  62456. return this.position.y;
  62457. }
  62458. if (!this._heightQuads || this._heightQuads.length == 0) {
  62459. this._initHeightQuads();
  62460. this._computeHeightQuads();
  62461. }
  62462. var facet = this._getFacetAt(x, z);
  62463. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  62464. // return y in the World system
  62465. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  62466. return tmpVect.y;
  62467. };
  62468. /**
  62469. * Returns a normalized vector (Vector3) orthogonal to the ground
  62470. * at the ground coordinates (x, z) expressed in the World system.
  62471. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  62472. */
  62473. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  62474. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  62475. this.getNormalAtCoordinatesToRef(x, z, normal);
  62476. return normal;
  62477. };
  62478. /**
  62479. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  62480. * at the ground coordinates (x, z) expressed in the World system.
  62481. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  62482. * Returns the GroundMesh.
  62483. */
  62484. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  62485. var world = this.getWorldMatrix();
  62486. var tmpMat = BABYLON.Tmp.Matrix[5];
  62487. world.invertToRef(tmpMat);
  62488. var tmpVect = BABYLON.Tmp.Vector3[8];
  62489. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  62490. x = tmpVect.x;
  62491. z = tmpVect.z;
  62492. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  62493. return this;
  62494. }
  62495. if (!this._heightQuads || this._heightQuads.length == 0) {
  62496. this._initHeightQuads();
  62497. this._computeHeightQuads();
  62498. }
  62499. var facet = this._getFacetAt(x, z);
  62500. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  62501. return this;
  62502. };
  62503. /**
  62504. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  62505. * if the ground has been updated.
  62506. * This can be used in the render loop.
  62507. * Returns the GroundMesh.
  62508. */
  62509. GroundMesh.prototype.updateCoordinateHeights = function () {
  62510. if (!this._heightQuads || this._heightQuads.length == 0) {
  62511. this._initHeightQuads();
  62512. }
  62513. this._computeHeightQuads();
  62514. return this;
  62515. };
  62516. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  62517. GroundMesh.prototype._getFacetAt = function (x, z) {
  62518. // retrieve col and row from x, z coordinates in the ground local system
  62519. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  62520. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  62521. var quad = this._heightQuads[row * this._subdivisionsX + col];
  62522. var facet;
  62523. if (z < quad.slope.x * x + quad.slope.y) {
  62524. facet = quad.facet1;
  62525. }
  62526. else {
  62527. facet = quad.facet2;
  62528. }
  62529. return facet;
  62530. };
  62531. // Creates and populates the heightMap array with "facet" elements :
  62532. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  62533. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  62534. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  62535. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  62536. // Returns the GroundMesh.
  62537. GroundMesh.prototype._initHeightQuads = function () {
  62538. var subdivisionsX = this._subdivisionsX;
  62539. var subdivisionsY = this._subdivisionsY;
  62540. this._heightQuads = new Array();
  62541. for (var row = 0; row < subdivisionsY; row++) {
  62542. for (var col = 0; col < subdivisionsX; col++) {
  62543. 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) };
  62544. this._heightQuads[row * subdivisionsX + col] = quad;
  62545. }
  62546. }
  62547. return this;
  62548. };
  62549. // Compute each quad element values and update the the heightMap array :
  62550. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  62551. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  62552. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  62553. // Returns the GroundMesh.
  62554. GroundMesh.prototype._computeHeightQuads = function () {
  62555. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62556. if (!positions) {
  62557. return this;
  62558. }
  62559. var v1 = BABYLON.Tmp.Vector3[3];
  62560. var v2 = BABYLON.Tmp.Vector3[2];
  62561. var v3 = BABYLON.Tmp.Vector3[1];
  62562. var v4 = BABYLON.Tmp.Vector3[0];
  62563. var v1v2 = BABYLON.Tmp.Vector3[4];
  62564. var v1v3 = BABYLON.Tmp.Vector3[5];
  62565. var v1v4 = BABYLON.Tmp.Vector3[6];
  62566. var norm1 = BABYLON.Tmp.Vector3[7];
  62567. var norm2 = BABYLON.Tmp.Vector3[8];
  62568. var i = 0;
  62569. var j = 0;
  62570. var k = 0;
  62571. var cd = 0; // 2D slope coefficient : z = cd * x + h
  62572. var h = 0;
  62573. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  62574. var d2 = 0;
  62575. var subdivisionsX = this._subdivisionsX;
  62576. var subdivisionsY = this._subdivisionsY;
  62577. for (var row = 0; row < subdivisionsY; row++) {
  62578. for (var col = 0; col < subdivisionsX; col++) {
  62579. i = col * 3;
  62580. j = row * (subdivisionsX + 1) * 3;
  62581. k = (row + 1) * (subdivisionsX + 1) * 3;
  62582. v1.x = positions[j + i];
  62583. v1.y = positions[j + i + 1];
  62584. v1.z = positions[j + i + 2];
  62585. v2.x = positions[j + i + 3];
  62586. v2.y = positions[j + i + 4];
  62587. v2.z = positions[j + i + 5];
  62588. v3.x = positions[k + i];
  62589. v3.y = positions[k + i + 1];
  62590. v3.z = positions[k + i + 2];
  62591. v4.x = positions[k + i + 3];
  62592. v4.y = positions[k + i + 4];
  62593. v4.z = positions[k + i + 5];
  62594. // 2D slope V1V4
  62595. cd = (v4.z - v1.z) / (v4.x - v1.x);
  62596. h = v1.z - cd * v1.x; // v1 belongs to the slope
  62597. // facet equations :
  62598. // we compute each facet normal vector
  62599. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  62600. // we compute the value d by applying the equation to v1 which belongs to the plane
  62601. // then we store the facet equation in a Vector4
  62602. v2.subtractToRef(v1, v1v2);
  62603. v3.subtractToRef(v1, v1v3);
  62604. v4.subtractToRef(v1, v1v4);
  62605. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  62606. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  62607. norm1.normalize();
  62608. norm2.normalize();
  62609. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  62610. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  62611. var quad = this._heightQuads[row * subdivisionsX + col];
  62612. quad.slope.copyFromFloats(cd, h);
  62613. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  62614. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  62615. }
  62616. }
  62617. return this;
  62618. };
  62619. GroundMesh.prototype.serialize = function (serializationObject) {
  62620. _super.prototype.serialize.call(this, serializationObject);
  62621. serializationObject.subdivisionsX = this._subdivisionsX;
  62622. serializationObject.subdivisionsY = this._subdivisionsY;
  62623. serializationObject.minX = this._minX;
  62624. serializationObject.maxX = this._maxX;
  62625. serializationObject.minZ = this._minZ;
  62626. serializationObject.maxZ = this._maxZ;
  62627. serializationObject.width = this._width;
  62628. serializationObject.height = this._height;
  62629. };
  62630. GroundMesh.Parse = function (parsedMesh, scene) {
  62631. var result = new GroundMesh(parsedMesh.name, scene);
  62632. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  62633. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  62634. result._minX = parsedMesh.minX;
  62635. result._maxX = parsedMesh.maxX;
  62636. result._minZ = parsedMesh.minZ;
  62637. result._maxZ = parsedMesh.maxZ;
  62638. result._width = parsedMesh.width;
  62639. result._height = parsedMesh.height;
  62640. return result;
  62641. };
  62642. return GroundMesh;
  62643. }(BABYLON.Mesh));
  62644. BABYLON.GroundMesh = GroundMesh;
  62645. })(BABYLON || (BABYLON = {}));
  62646. //# sourceMappingURL=babylon.groundMesh.js.map
  62647. var BABYLON;
  62648. (function (BABYLON) {
  62649. /**
  62650. * Creates an instance based on a source mesh.
  62651. */
  62652. var InstancedMesh = /** @class */ (function (_super) {
  62653. __extends(InstancedMesh, _super);
  62654. function InstancedMesh(name, source) {
  62655. var _this = _super.call(this, name, source.getScene()) || this;
  62656. source.instances.push(_this);
  62657. _this._sourceMesh = source;
  62658. _this.position.copyFrom(source.position);
  62659. _this.rotation.copyFrom(source.rotation);
  62660. _this.scaling.copyFrom(source.scaling);
  62661. if (source.rotationQuaternion) {
  62662. _this.rotationQuaternion = source.rotationQuaternion.clone();
  62663. }
  62664. _this.infiniteDistance = source.infiniteDistance;
  62665. _this.setPivotMatrix(source.getPivotMatrix());
  62666. _this.refreshBoundingInfo();
  62667. _this._syncSubMeshes();
  62668. return _this;
  62669. }
  62670. /**
  62671. * Returns the string "InstancedMesh".
  62672. */
  62673. InstancedMesh.prototype.getClassName = function () {
  62674. return "InstancedMesh";
  62675. };
  62676. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  62677. // Methods
  62678. get: function () {
  62679. return this._sourceMesh.receiveShadows;
  62680. },
  62681. enumerable: true,
  62682. configurable: true
  62683. });
  62684. Object.defineProperty(InstancedMesh.prototype, "material", {
  62685. get: function () {
  62686. return this._sourceMesh.material;
  62687. },
  62688. enumerable: true,
  62689. configurable: true
  62690. });
  62691. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  62692. get: function () {
  62693. return this._sourceMesh.visibility;
  62694. },
  62695. enumerable: true,
  62696. configurable: true
  62697. });
  62698. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  62699. get: function () {
  62700. return this._sourceMesh.skeleton;
  62701. },
  62702. enumerable: true,
  62703. configurable: true
  62704. });
  62705. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  62706. get: function () {
  62707. return this._sourceMesh.renderingGroupId;
  62708. },
  62709. set: function (value) {
  62710. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  62711. return;
  62712. }
  62713. //no-op with warning
  62714. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  62715. },
  62716. enumerable: true,
  62717. configurable: true
  62718. });
  62719. /**
  62720. * Returns the total number of vertices (integer).
  62721. */
  62722. InstancedMesh.prototype.getTotalVertices = function () {
  62723. return this._sourceMesh.getTotalVertices();
  62724. };
  62725. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  62726. get: function () {
  62727. return this._sourceMesh;
  62728. },
  62729. enumerable: true,
  62730. configurable: true
  62731. });
  62732. /**
  62733. * Is this node ready to be used/rendered
  62734. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  62735. * @return {boolean} is it ready
  62736. */
  62737. InstancedMesh.prototype.isReady = function (completeCheck) {
  62738. if (completeCheck === void 0) { completeCheck = false; }
  62739. return this._sourceMesh.isReady(completeCheck, true);
  62740. };
  62741. /**
  62742. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  62743. */
  62744. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  62745. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  62746. };
  62747. /**
  62748. * Sets the vertex data of the mesh geometry for the requested `kind`.
  62749. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  62750. * The `data` are either a numeric array either a Float32Array.
  62751. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  62752. * 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).
  62753. * Note that a new underlying VertexBuffer object is created each call.
  62754. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  62755. *
  62756. * Possible `kind` values :
  62757. * - BABYLON.VertexBuffer.PositionKind
  62758. * - BABYLON.VertexBuffer.UVKind
  62759. * - BABYLON.VertexBuffer.UV2Kind
  62760. * - BABYLON.VertexBuffer.UV3Kind
  62761. * - BABYLON.VertexBuffer.UV4Kind
  62762. * - BABYLON.VertexBuffer.UV5Kind
  62763. * - BABYLON.VertexBuffer.UV6Kind
  62764. * - BABYLON.VertexBuffer.ColorKind
  62765. * - BABYLON.VertexBuffer.MatricesIndicesKind
  62766. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  62767. * - BABYLON.VertexBuffer.MatricesWeightsKind
  62768. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  62769. *
  62770. * Returns the Mesh.
  62771. */
  62772. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  62773. if (this.sourceMesh) {
  62774. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  62775. }
  62776. return this.sourceMesh;
  62777. };
  62778. /**
  62779. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  62780. * If the mesh has no geometry, it is simply returned as it is.
  62781. * The `data` are either a numeric array either a Float32Array.
  62782. * No new underlying VertexBuffer object is created.
  62783. * 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.
  62784. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  62785. *
  62786. * Possible `kind` values :
  62787. * - BABYLON.VertexBuffer.PositionKind
  62788. * - BABYLON.VertexBuffer.UVKind
  62789. * - BABYLON.VertexBuffer.UV2Kind
  62790. * - BABYLON.VertexBuffer.UV3Kind
  62791. * - BABYLON.VertexBuffer.UV4Kind
  62792. * - BABYLON.VertexBuffer.UV5Kind
  62793. * - BABYLON.VertexBuffer.UV6Kind
  62794. * - BABYLON.VertexBuffer.ColorKind
  62795. * - BABYLON.VertexBuffer.MatricesIndicesKind
  62796. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  62797. * - BABYLON.VertexBuffer.MatricesWeightsKind
  62798. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  62799. *
  62800. * Returns the Mesh.
  62801. */
  62802. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  62803. if (this.sourceMesh) {
  62804. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  62805. }
  62806. return this.sourceMesh;
  62807. };
  62808. /**
  62809. * Sets the mesh indices.
  62810. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  62811. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  62812. * This method creates a new index buffer each call.
  62813. * Returns the Mesh.
  62814. */
  62815. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  62816. if (totalVertices === void 0) { totalVertices = null; }
  62817. if (this.sourceMesh) {
  62818. this.sourceMesh.setIndices(indices, totalVertices);
  62819. }
  62820. return this.sourceMesh;
  62821. };
  62822. /**
  62823. * Boolean : True if the mesh owns the requested kind of data.
  62824. */
  62825. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  62826. return this._sourceMesh.isVerticesDataPresent(kind);
  62827. };
  62828. /**
  62829. * Returns an array of indices (IndicesArray).
  62830. */
  62831. InstancedMesh.prototype.getIndices = function () {
  62832. return this._sourceMesh.getIndices();
  62833. };
  62834. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  62835. get: function () {
  62836. return this._sourceMesh._positions;
  62837. },
  62838. enumerable: true,
  62839. configurable: true
  62840. });
  62841. /**
  62842. * Sets a new updated BoundingInfo to the mesh.
  62843. * Returns the mesh.
  62844. */
  62845. InstancedMesh.prototype.refreshBoundingInfo = function () {
  62846. var meshBB = this._sourceMesh.getBoundingInfo();
  62847. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  62848. this._updateBoundingInfo();
  62849. return this;
  62850. };
  62851. /** @hidden */
  62852. InstancedMesh.prototype._preActivate = function () {
  62853. if (this._currentLOD) {
  62854. this._currentLOD._preActivate();
  62855. }
  62856. return this;
  62857. };
  62858. /** @hidden */
  62859. InstancedMesh.prototype._activate = function (renderId) {
  62860. if (this._currentLOD) {
  62861. this._currentLOD._registerInstanceForRenderId(this, renderId);
  62862. }
  62863. return this;
  62864. };
  62865. /**
  62866. * Returns the current associated LOD AbstractMesh.
  62867. */
  62868. InstancedMesh.prototype.getLOD = function (camera) {
  62869. if (!camera) {
  62870. return this;
  62871. }
  62872. var boundingInfo = this.getBoundingInfo();
  62873. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  62874. if (this._currentLOD === this.sourceMesh) {
  62875. return this;
  62876. }
  62877. return this._currentLOD;
  62878. };
  62879. /** @hidden */
  62880. InstancedMesh.prototype._syncSubMeshes = function () {
  62881. this.releaseSubMeshes();
  62882. if (this._sourceMesh.subMeshes) {
  62883. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  62884. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  62885. }
  62886. }
  62887. return this;
  62888. };
  62889. /** @hidden */
  62890. InstancedMesh.prototype._generatePointsArray = function () {
  62891. return this._sourceMesh._generatePointsArray();
  62892. };
  62893. /**
  62894. * Creates a new InstancedMesh from the current mesh.
  62895. * - name (string) : the cloned mesh name
  62896. * - newParent (optional Node) : the optional Node to parent the clone to.
  62897. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  62898. *
  62899. * Returns the clone.
  62900. */
  62901. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  62902. var result = this._sourceMesh.createInstance(name);
  62903. // Deep copy
  62904. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  62905. // Bounding info
  62906. this.refreshBoundingInfo();
  62907. // Parent
  62908. if (newParent) {
  62909. result.parent = newParent;
  62910. }
  62911. if (!doNotCloneChildren) {
  62912. // Children
  62913. for (var index = 0; index < this.getScene().meshes.length; index++) {
  62914. var mesh = this.getScene().meshes[index];
  62915. if (mesh.parent === this) {
  62916. mesh.clone(mesh.name, result);
  62917. }
  62918. }
  62919. }
  62920. result.computeWorldMatrix(true);
  62921. return result;
  62922. };
  62923. /**
  62924. * Disposes the InstancedMesh.
  62925. * Returns nothing.
  62926. */
  62927. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  62928. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  62929. // Remove from mesh
  62930. var index = this._sourceMesh.instances.indexOf(this);
  62931. this._sourceMesh.instances.splice(index, 1);
  62932. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  62933. };
  62934. return InstancedMesh;
  62935. }(BABYLON.AbstractMesh));
  62936. BABYLON.InstancedMesh = InstancedMesh;
  62937. })(BABYLON || (BABYLON = {}));
  62938. //# sourceMappingURL=babylon.instancedMesh.js.map
  62939. var BABYLON;
  62940. (function (BABYLON) {
  62941. var LinesMesh = /** @class */ (function (_super) {
  62942. __extends(LinesMesh, _super);
  62943. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  62944. if (scene === void 0) { scene = null; }
  62945. if (parent === void 0) { parent = null; }
  62946. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  62947. _this.useVertexColor = useVertexColor;
  62948. _this.useVertexAlpha = useVertexAlpha;
  62949. _this.color = new BABYLON.Color3(1, 1, 1);
  62950. _this.alpha = 1;
  62951. if (source) {
  62952. _this.color = source.color.clone();
  62953. _this.alpha = source.alpha;
  62954. _this.useVertexColor = source.useVertexColor;
  62955. _this.useVertexAlpha = source.useVertexAlpha;
  62956. }
  62957. _this._intersectionThreshold = 0.1;
  62958. var defines = [];
  62959. var options = {
  62960. attributes: [BABYLON.VertexBuffer.PositionKind, "world0", "world1", "world2", "world3"],
  62961. uniforms: ["world", "viewProjection"],
  62962. needAlphaBlending: true,
  62963. defines: defines
  62964. };
  62965. if (useVertexAlpha === false) {
  62966. options.needAlphaBlending = false;
  62967. }
  62968. if (!useVertexColor) {
  62969. options.uniforms.push("color");
  62970. }
  62971. else {
  62972. options.defines.push("#define VERTEXCOLOR");
  62973. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  62974. }
  62975. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  62976. return _this;
  62977. }
  62978. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  62979. /**
  62980. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  62981. * This margin is expressed in world space coordinates, so its value may vary.
  62982. * Default value is 0.1
  62983. * @returns the intersection Threshold value.
  62984. */
  62985. get: function () {
  62986. return this._intersectionThreshold;
  62987. },
  62988. /**
  62989. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  62990. * This margin is expressed in world space coordinates, so its value may vary.
  62991. * @param value the new threshold to apply
  62992. */
  62993. set: function (value) {
  62994. if (this._intersectionThreshold === value) {
  62995. return;
  62996. }
  62997. this._intersectionThreshold = value;
  62998. if (this.geometry) {
  62999. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  63000. }
  63001. },
  63002. enumerable: true,
  63003. configurable: true
  63004. });
  63005. /**
  63006. * Returns the string "LineMesh"
  63007. */
  63008. LinesMesh.prototype.getClassName = function () {
  63009. return "LinesMesh";
  63010. };
  63011. Object.defineProperty(LinesMesh.prototype, "material", {
  63012. /**
  63013. * @hidden
  63014. */
  63015. get: function () {
  63016. return this._colorShader;
  63017. },
  63018. /**
  63019. * @hidden
  63020. */
  63021. set: function (value) {
  63022. // Do nothing
  63023. },
  63024. enumerable: true,
  63025. configurable: true
  63026. });
  63027. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  63028. /**
  63029. * @hidden
  63030. */
  63031. get: function () {
  63032. return false;
  63033. },
  63034. enumerable: true,
  63035. configurable: true
  63036. });
  63037. /** @hidden */
  63038. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  63039. if (!this._geometry) {
  63040. return this;
  63041. }
  63042. // VBOs
  63043. this._geometry._bind(this._colorShader.getEffect());
  63044. // Color
  63045. if (!this.useVertexColor) {
  63046. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  63047. }
  63048. return this;
  63049. };
  63050. /** @hidden */
  63051. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  63052. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  63053. return this;
  63054. }
  63055. var engine = this.getScene().getEngine();
  63056. // Draw order
  63057. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  63058. return this;
  63059. };
  63060. LinesMesh.prototype.dispose = function (doNotRecurse) {
  63061. this._colorShader.dispose();
  63062. _super.prototype.dispose.call(this, doNotRecurse);
  63063. };
  63064. /**
  63065. * Returns a new LineMesh object cloned from the current one.
  63066. */
  63067. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  63068. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  63069. };
  63070. return LinesMesh;
  63071. }(BABYLON.Mesh));
  63072. BABYLON.LinesMesh = LinesMesh;
  63073. })(BABYLON || (BABYLON = {}));
  63074. //# sourceMappingURL=babylon.linesMesh.js.map
  63075. var BABYLON;
  63076. (function (BABYLON) {
  63077. /**
  63078. * This class implement a typical dictionary using a string as key and the generic type T as value.
  63079. * The underlying implementation relies on an associative array to ensure the best performances.
  63080. * The value can be anything including 'null' but except 'undefined'
  63081. */
  63082. var StringDictionary = /** @class */ (function () {
  63083. function StringDictionary() {
  63084. this._count = 0;
  63085. this._data = {};
  63086. }
  63087. /**
  63088. * This will clear this dictionary and copy the content from the 'source' one.
  63089. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  63090. * @param source the dictionary to take the content from and copy to this dictionary
  63091. */
  63092. StringDictionary.prototype.copyFrom = function (source) {
  63093. var _this = this;
  63094. this.clear();
  63095. source.forEach(function (t, v) { return _this.add(t, v); });
  63096. };
  63097. /**
  63098. * Get a value based from its key
  63099. * @param key the given key to get the matching value from
  63100. * @return the value if found, otherwise undefined is returned
  63101. */
  63102. StringDictionary.prototype.get = function (key) {
  63103. var val = this._data[key];
  63104. if (val !== undefined) {
  63105. return val;
  63106. }
  63107. return undefined;
  63108. };
  63109. /**
  63110. * Get a value from its key or add it if it doesn't exist.
  63111. * This method will ensure you that a given key/data will be present in the dictionary.
  63112. * @param key the given key to get the matching value from
  63113. * @param factory the factory that will create the value if the key is not present in the dictionary.
  63114. * The factory will only be invoked if there's no data for the given key.
  63115. * @return the value corresponding to the key.
  63116. */
  63117. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  63118. var val = this.get(key);
  63119. if (val !== undefined) {
  63120. return val;
  63121. }
  63122. val = factory(key);
  63123. if (val) {
  63124. this.add(key, val);
  63125. }
  63126. return val;
  63127. };
  63128. /**
  63129. * Get a value from its key if present in the dictionary otherwise add it
  63130. * @param key the key to get the value from
  63131. * @param val if there's no such key/value pair in the dictionary add it with this value
  63132. * @return the value corresponding to the key
  63133. */
  63134. StringDictionary.prototype.getOrAdd = function (key, val) {
  63135. var curVal = this.get(key);
  63136. if (curVal !== undefined) {
  63137. return curVal;
  63138. }
  63139. this.add(key, val);
  63140. return val;
  63141. };
  63142. /**
  63143. * Check if there's a given key in the dictionary
  63144. * @param key the key to check for
  63145. * @return true if the key is present, false otherwise
  63146. */
  63147. StringDictionary.prototype.contains = function (key) {
  63148. return this._data[key] !== undefined;
  63149. };
  63150. /**
  63151. * Add a new key and its corresponding value
  63152. * @param key the key to add
  63153. * @param value the value corresponding to the key
  63154. * @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
  63155. */
  63156. StringDictionary.prototype.add = function (key, value) {
  63157. if (this._data[key] !== undefined) {
  63158. return false;
  63159. }
  63160. this._data[key] = value;
  63161. ++this._count;
  63162. return true;
  63163. };
  63164. StringDictionary.prototype.set = function (key, value) {
  63165. if (this._data[key] === undefined) {
  63166. return false;
  63167. }
  63168. this._data[key] = value;
  63169. return true;
  63170. };
  63171. /**
  63172. * Get the element of the given key and remove it from the dictionary
  63173. * @param key
  63174. */
  63175. StringDictionary.prototype.getAndRemove = function (key) {
  63176. var val = this.get(key);
  63177. if (val !== undefined) {
  63178. delete this._data[key];
  63179. --this._count;
  63180. return val;
  63181. }
  63182. return null;
  63183. };
  63184. /**
  63185. * Remove a key/value from the dictionary.
  63186. * @param key the key to remove
  63187. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  63188. */
  63189. StringDictionary.prototype.remove = function (key) {
  63190. if (this.contains(key)) {
  63191. delete this._data[key];
  63192. --this._count;
  63193. return true;
  63194. }
  63195. return false;
  63196. };
  63197. /**
  63198. * Clear the whole content of the dictionary
  63199. */
  63200. StringDictionary.prototype.clear = function () {
  63201. this._data = {};
  63202. this._count = 0;
  63203. };
  63204. Object.defineProperty(StringDictionary.prototype, "count", {
  63205. get: function () {
  63206. return this._count;
  63207. },
  63208. enumerable: true,
  63209. configurable: true
  63210. });
  63211. /**
  63212. * Execute a callback on each key/val of the dictionary.
  63213. * Note that you can remove any element in this dictionary in the callback implementation
  63214. * @param callback the callback to execute on a given key/value pair
  63215. */
  63216. StringDictionary.prototype.forEach = function (callback) {
  63217. for (var cur in this._data) {
  63218. var val = this._data[cur];
  63219. callback(cur, val);
  63220. }
  63221. };
  63222. /**
  63223. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  63224. * If the callback returns null or undefined the method will iterate to the next key/value pair
  63225. * Note that you can remove any element in this dictionary in the callback implementation
  63226. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  63227. */
  63228. StringDictionary.prototype.first = function (callback) {
  63229. for (var cur in this._data) {
  63230. var val = this._data[cur];
  63231. var res = callback(cur, val);
  63232. if (res) {
  63233. return res;
  63234. }
  63235. }
  63236. return null;
  63237. };
  63238. return StringDictionary;
  63239. }());
  63240. BABYLON.StringDictionary = StringDictionary;
  63241. })(BABYLON || (BABYLON = {}));
  63242. //# sourceMappingURL=babylon.stringDictionary.js.map
  63243. var BABYLON;
  63244. (function (BABYLON) {
  63245. var Debug;
  63246. (function (Debug) {
  63247. /**
  63248. * Class used to render a debug view of a given skeleton
  63249. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  63250. */
  63251. var SkeletonViewer = /** @class */ (function () {
  63252. /**
  63253. * Creates a new SkeletonViewer
  63254. * @param skeleton defines the skeleton to render
  63255. * @param mesh defines the mesh attached to the skeleton
  63256. * @param scene defines the hosting scene
  63257. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  63258. * @param renderingGroupId defines the rendering group id to use with the viewer
  63259. */
  63260. function SkeletonViewer(
  63261. /** defines the skeleton to render */
  63262. skeleton,
  63263. /** defines the mesh attached to the skeleton */
  63264. mesh, scene,
  63265. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  63266. autoUpdateBonesMatrices,
  63267. /** defines the rendering group id to use with the viewer */
  63268. renderingGroupId) {
  63269. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  63270. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  63271. this.skeleton = skeleton;
  63272. this.mesh = mesh;
  63273. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  63274. this.renderingGroupId = renderingGroupId;
  63275. /** Gets or sets the color used to render the skeleton */
  63276. this.color = BABYLON.Color3.White();
  63277. this._debugLines = new Array();
  63278. this._isEnabled = false;
  63279. this._scene = scene;
  63280. this.update();
  63281. this._renderFunction = this.update.bind(this);
  63282. }
  63283. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  63284. get: function () {
  63285. return this._isEnabled;
  63286. },
  63287. /** Gets or sets a boolean indicating if the viewer is enabled */
  63288. set: function (value) {
  63289. if (this._isEnabled === value) {
  63290. return;
  63291. }
  63292. this._isEnabled = value;
  63293. if (value) {
  63294. this._scene.registerBeforeRender(this._renderFunction);
  63295. }
  63296. else {
  63297. this._scene.unregisterBeforeRender(this._renderFunction);
  63298. }
  63299. },
  63300. enumerable: true,
  63301. configurable: true
  63302. });
  63303. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  63304. if (x === void 0) { x = 0; }
  63305. if (y === void 0) { y = 0; }
  63306. if (z === void 0) { z = 0; }
  63307. var tmat = BABYLON.Tmp.Matrix[0];
  63308. var parentBone = bone.getParent();
  63309. tmat.copyFrom(bone.getLocalMatrix());
  63310. if (x !== 0 || y !== 0 || z !== 0) {
  63311. var tmat2 = BABYLON.Tmp.Matrix[1];
  63312. BABYLON.Matrix.IdentityToRef(tmat2);
  63313. tmat2.m[12] = x;
  63314. tmat2.m[13] = y;
  63315. tmat2.m[14] = z;
  63316. tmat2.multiplyToRef(tmat, tmat);
  63317. }
  63318. if (parentBone) {
  63319. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  63320. }
  63321. tmat.multiplyToRef(meshMat, tmat);
  63322. position.x = tmat.m[12];
  63323. position.y = tmat.m[13];
  63324. position.z = tmat.m[14];
  63325. };
  63326. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  63327. var len = bones.length;
  63328. var meshPos = this.mesh.position;
  63329. for (var i = 0; i < len; i++) {
  63330. var bone = bones[i];
  63331. var points = this._debugLines[i];
  63332. if (!points) {
  63333. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63334. this._debugLines[i] = points;
  63335. }
  63336. this._getBonePosition(points[0], bone, meshMat);
  63337. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  63338. points[0].subtractInPlace(meshPos);
  63339. points[1].subtractInPlace(meshPos);
  63340. }
  63341. };
  63342. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  63343. var len = bones.length;
  63344. var boneNum = 0;
  63345. var meshPos = this.mesh.position;
  63346. for (var i = len - 1; i >= 0; i--) {
  63347. var childBone = bones[i];
  63348. var parentBone = childBone.getParent();
  63349. if (!parentBone) {
  63350. continue;
  63351. }
  63352. var points = this._debugLines[boneNum];
  63353. if (!points) {
  63354. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63355. this._debugLines[boneNum] = points;
  63356. }
  63357. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  63358. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  63359. points[0].subtractInPlace(meshPos);
  63360. points[1].subtractInPlace(meshPos);
  63361. boneNum++;
  63362. }
  63363. };
  63364. /** Update the viewer to sync with current skeleton state */
  63365. SkeletonViewer.prototype.update = function () {
  63366. if (this.autoUpdateBonesMatrices) {
  63367. this.skeleton.computeAbsoluteTransforms();
  63368. }
  63369. if (this.skeleton.bones[0].length === undefined) {
  63370. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  63371. }
  63372. else {
  63373. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  63374. }
  63375. if (!this._debugMesh) {
  63376. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  63377. this._debugMesh.renderingGroupId = this.renderingGroupId;
  63378. }
  63379. else {
  63380. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  63381. }
  63382. this._debugMesh.position.copyFrom(this.mesh.position);
  63383. this._debugMesh.color = this.color;
  63384. };
  63385. /** Release associated resources */
  63386. SkeletonViewer.prototype.dispose = function () {
  63387. if (this._debugMesh) {
  63388. this.isEnabled = false;
  63389. this._debugMesh.dispose();
  63390. this._debugMesh = null;
  63391. }
  63392. };
  63393. return SkeletonViewer;
  63394. }());
  63395. Debug.SkeletonViewer = SkeletonViewer;
  63396. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63397. })(BABYLON || (BABYLON = {}));
  63398. //# sourceMappingURL=babylon.skeletonViewer.js.map
  63399. /**
  63400. * Module Debug contains the (visual) components to debug a scene correctly
  63401. */
  63402. var BABYLON;
  63403. (function (BABYLON) {
  63404. var Debug;
  63405. (function (Debug) {
  63406. /**
  63407. * The Axes viewer will show 3 axes in a specific point in space
  63408. */
  63409. var AxesViewer = /** @class */ (function () {
  63410. /**
  63411. * Creates a new AxesViewer
  63412. * @param scene defines the hosting scene
  63413. * @param scaleLines defines a number used to scale line length (1 by default)
  63414. */
  63415. function AxesViewer(scene, scaleLines) {
  63416. if (scaleLines === void 0) { scaleLines = 1; }
  63417. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63418. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63419. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63420. /**
  63421. * Gets or sets a number used to scale line length
  63422. */
  63423. this.scaleLines = 1;
  63424. this.scaleLines = scaleLines;
  63425. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  63426. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  63427. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  63428. this._xmesh.renderingGroupId = 2;
  63429. this._ymesh.renderingGroupId = 2;
  63430. this._zmesh.renderingGroupId = 2;
  63431. this._xmesh.material.checkReadyOnlyOnce = true;
  63432. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  63433. this._ymesh.material.checkReadyOnlyOnce = true;
  63434. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  63435. this._zmesh.material.checkReadyOnlyOnce = true;
  63436. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  63437. this.scene = scene;
  63438. }
  63439. /**
  63440. * Force the viewer to update
  63441. * @param position defines the position of the viewer
  63442. * @param xaxis defines the x axis of the viewer
  63443. * @param yaxis defines the y axis of the viewer
  63444. * @param zaxis defines the z axis of the viewer
  63445. */
  63446. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  63447. var scaleLines = this.scaleLines;
  63448. if (this._xmesh) {
  63449. this._xmesh.position.copyFrom(position);
  63450. }
  63451. if (this._ymesh) {
  63452. this._ymesh.position.copyFrom(position);
  63453. }
  63454. if (this._zmesh) {
  63455. this._zmesh.position.copyFrom(position);
  63456. }
  63457. var point2 = this._xline[1];
  63458. point2.x = xaxis.x * scaleLines;
  63459. point2.y = xaxis.y * scaleLines;
  63460. point2.z = xaxis.z * scaleLines;
  63461. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  63462. point2 = this._yline[1];
  63463. point2.x = yaxis.x * scaleLines;
  63464. point2.y = yaxis.y * scaleLines;
  63465. point2.z = yaxis.z * scaleLines;
  63466. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  63467. point2 = this._zline[1];
  63468. point2.x = zaxis.x * scaleLines;
  63469. point2.y = zaxis.y * scaleLines;
  63470. point2.z = zaxis.z * scaleLines;
  63471. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  63472. };
  63473. /** Releases resources */
  63474. AxesViewer.prototype.dispose = function () {
  63475. if (this._xmesh) {
  63476. this._xmesh.dispose();
  63477. }
  63478. if (this._ymesh) {
  63479. this._ymesh.dispose();
  63480. }
  63481. if (this._zmesh) {
  63482. this._zmesh.dispose();
  63483. }
  63484. this._xmesh = null;
  63485. this._ymesh = null;
  63486. this._zmesh = null;
  63487. this.scene = null;
  63488. };
  63489. return AxesViewer;
  63490. }());
  63491. Debug.AxesViewer = AxesViewer;
  63492. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63493. })(BABYLON || (BABYLON = {}));
  63494. //# sourceMappingURL=babylon.axesViewer.js.map
  63495. var BABYLON;
  63496. (function (BABYLON) {
  63497. var Debug;
  63498. (function (Debug) {
  63499. /**
  63500. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  63501. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  63502. */
  63503. var BoneAxesViewer = /** @class */ (function (_super) {
  63504. __extends(BoneAxesViewer, _super);
  63505. /**
  63506. * Creates a new BoneAxesViewer
  63507. * @param scene defines the hosting scene
  63508. * @param bone defines the target bone
  63509. * @param mesh defines the target mesh
  63510. * @param scaleLines defines a scaling factor for line length (1 by default)
  63511. */
  63512. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  63513. if (scaleLines === void 0) { scaleLines = 1; }
  63514. var _this = _super.call(this, scene, scaleLines) || this;
  63515. /** Gets current position */
  63516. _this.pos = BABYLON.Vector3.Zero();
  63517. /** Gets direction of X axis */
  63518. _this.xaxis = BABYLON.Vector3.Zero();
  63519. /** Gets direction of Y axis */
  63520. _this.yaxis = BABYLON.Vector3.Zero();
  63521. /** Gets direction of Z axis */
  63522. _this.zaxis = BABYLON.Vector3.Zero();
  63523. _this.mesh = mesh;
  63524. _this.bone = bone;
  63525. return _this;
  63526. }
  63527. /**
  63528. * Force the viewer to update
  63529. */
  63530. BoneAxesViewer.prototype.update = function () {
  63531. if (!this.mesh || !this.bone) {
  63532. return;
  63533. }
  63534. var bone = this.bone;
  63535. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  63536. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  63537. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  63538. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  63539. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  63540. };
  63541. /** Releases resources */
  63542. BoneAxesViewer.prototype.dispose = function () {
  63543. if (this.mesh) {
  63544. this.mesh = null;
  63545. this.bone = null;
  63546. _super.prototype.dispose.call(this);
  63547. }
  63548. };
  63549. return BoneAxesViewer;
  63550. }(Debug.AxesViewer));
  63551. Debug.BoneAxesViewer = BoneAxesViewer;
  63552. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63553. })(BABYLON || (BABYLON = {}));
  63554. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  63555. var BABYLON;
  63556. (function (BABYLON) {
  63557. /**
  63558. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  63559. * in order to better appreciate the issue one might have.
  63560. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  63561. */
  63562. var RayHelper = /** @class */ (function () {
  63563. /**
  63564. * Instantiate a new ray helper.
  63565. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  63566. * in order to better appreciate the issue one might have.
  63567. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  63568. * @param ray Defines the ray we are currently tryin to visualize
  63569. */
  63570. function RayHelper(ray) {
  63571. this.ray = ray;
  63572. }
  63573. /**
  63574. * Helper function to create a colored helper in a scene in one line.
  63575. * @param ray Defines the ray we are currently tryin to visualize
  63576. * @param scene Defines the scene the ray is used in
  63577. * @param color Defines the color we want to see the ray in
  63578. * @returns The newly created ray helper.
  63579. */
  63580. RayHelper.CreateAndShow = function (ray, scene, color) {
  63581. var helper = new RayHelper(ray);
  63582. helper.show(scene, color);
  63583. return helper;
  63584. };
  63585. /**
  63586. * Shows the ray we are willing to debug.
  63587. * @param scene Defines the scene the ray needs to be rendered in
  63588. * @param color Defines the color the ray needs to be rendered in
  63589. */
  63590. RayHelper.prototype.show = function (scene, color) {
  63591. if (!this._renderFunction && this.ray) {
  63592. var ray = this.ray;
  63593. this._renderFunction = this._render.bind(this);
  63594. this._scene = scene;
  63595. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  63596. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  63597. if (this._renderFunction) {
  63598. this._scene.registerBeforeRender(this._renderFunction);
  63599. }
  63600. }
  63601. if (color && this._renderLine) {
  63602. this._renderLine.color.copyFrom(color);
  63603. }
  63604. };
  63605. /**
  63606. * Hides the ray we are debugging.
  63607. */
  63608. RayHelper.prototype.hide = function () {
  63609. if (this._renderFunction && this._scene) {
  63610. this._scene.unregisterBeforeRender(this._renderFunction);
  63611. this._scene = null;
  63612. this._renderFunction = null;
  63613. if (this._renderLine) {
  63614. this._renderLine.dispose();
  63615. this._renderLine = null;
  63616. }
  63617. this._renderPoints = [];
  63618. }
  63619. };
  63620. RayHelper.prototype._render = function () {
  63621. var ray = this.ray;
  63622. if (!ray) {
  63623. return;
  63624. }
  63625. var point = this._renderPoints[1];
  63626. var len = Math.min(ray.length, 1000000);
  63627. point.copyFrom(ray.direction);
  63628. point.scaleInPlace(len);
  63629. point.addInPlace(ray.origin);
  63630. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  63631. };
  63632. /**
  63633. * Attach a ray helper to a mesh so that we can easily see its orientation for instance or information like its normals.
  63634. * @param mesh Defines the mesh we want the helper attached to
  63635. * @param meshSpaceDirection Defines the direction of the Ray in mesh space (local space of the mesh node)
  63636. * @param meshSpaceOrigin Defines the origin of the Ray in mesh space (local space of the mesh node)
  63637. * @param length Defines the length of the ray
  63638. */
  63639. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  63640. this._attachedToMesh = mesh;
  63641. var ray = this.ray;
  63642. if (!ray) {
  63643. return;
  63644. }
  63645. if (!ray.direction) {
  63646. ray.direction = BABYLON.Vector3.Zero();
  63647. }
  63648. if (!ray.origin) {
  63649. ray.origin = BABYLON.Vector3.Zero();
  63650. }
  63651. if (length) {
  63652. ray.length = length;
  63653. }
  63654. if (!meshSpaceOrigin) {
  63655. meshSpaceOrigin = BABYLON.Vector3.Zero();
  63656. }
  63657. if (!meshSpaceDirection) {
  63658. // -1 so that this will work with Mesh.lookAt
  63659. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  63660. }
  63661. if (!this._meshSpaceDirection) {
  63662. this._meshSpaceDirection = meshSpaceDirection.clone();
  63663. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  63664. }
  63665. else {
  63666. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  63667. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  63668. }
  63669. if (!this._updateToMeshFunction) {
  63670. this._updateToMeshFunction = this._updateToMesh.bind(this);
  63671. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  63672. }
  63673. this._updateToMesh();
  63674. };
  63675. /**
  63676. * Detach the ray helper from the mesh it has previously been attached to.
  63677. */
  63678. RayHelper.prototype.detachFromMesh = function () {
  63679. if (this._attachedToMesh) {
  63680. if (this._updateToMeshFunction) {
  63681. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  63682. }
  63683. this._attachedToMesh = null;
  63684. this._updateToMeshFunction = null;
  63685. }
  63686. };
  63687. RayHelper.prototype._updateToMesh = function () {
  63688. var ray = this.ray;
  63689. if (!this._attachedToMesh || !ray) {
  63690. return;
  63691. }
  63692. if (this._attachedToMesh._isDisposed) {
  63693. this.detachFromMesh();
  63694. return;
  63695. }
  63696. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  63697. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  63698. };
  63699. /**
  63700. * Dispose the helper and release its associated resources.
  63701. */
  63702. RayHelper.prototype.dispose = function () {
  63703. this.hide();
  63704. this.detachFromMesh();
  63705. this.ray = null;
  63706. };
  63707. return RayHelper;
  63708. }());
  63709. BABYLON.RayHelper = RayHelper;
  63710. })(BABYLON || (BABYLON = {}));
  63711. //# sourceMappingURL=babylon.rayHelper.js.map
  63712. var BABYLON;
  63713. (function (BABYLON) {
  63714. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  63715. get: function () {
  63716. if (!this._debugLayer) {
  63717. this._debugLayer = new DebugLayer(this);
  63718. }
  63719. return this._debugLayer;
  63720. },
  63721. enumerable: true,
  63722. configurable: true
  63723. });
  63724. /**
  63725. * The debug layer (aka Inspector) is the go to tool in order to better understand
  63726. * what is happening in your scene
  63727. * @see http://doc.babylonjs.com/features/playground_debuglayer
  63728. */
  63729. var DebugLayer = /** @class */ (function () {
  63730. /**
  63731. * Instantiates a new debug layer.
  63732. * The debug layer (aka Inspector) is the go to tool in order to better understand
  63733. * what is happening in your scene
  63734. * @see http://doc.babylonjs.com/features/playground_debuglayer
  63735. * @param scene Defines the scene to inspect
  63736. */
  63737. function DebugLayer(scene) {
  63738. var _this = this;
  63739. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  63740. /**
  63741. * Observable triggered when a property is changed through the inspector.
  63742. */
  63743. this.onPropertyChangedObservable = new BABYLON.Observable();
  63744. this._scene = scene;
  63745. this._scene.onDisposeObservable.add(function () {
  63746. // Debug layer
  63747. if (_this._scene._debugLayer) {
  63748. _this._scene._debugLayer.hide();
  63749. }
  63750. });
  63751. }
  63752. /** Creates the inspector window. */
  63753. DebugLayer.prototype._createInspector = function (config) {
  63754. if (config === void 0) { config = {}; }
  63755. var popup = config.popup || false;
  63756. var initialTab = config.initialTab || 0;
  63757. var parentElement = config.parentElement || null;
  63758. if (!this._inspector) {
  63759. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  63760. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  63761. } // else nothing to do as instance is already created
  63762. };
  63763. /**
  63764. * Get if the inspector is visible or not.
  63765. * @returns true if visible otherwise, false
  63766. */
  63767. DebugLayer.prototype.isVisible = function () {
  63768. if (!this._inspector) {
  63769. return false;
  63770. }
  63771. return true;
  63772. };
  63773. /**
  63774. * Hide the inspector and close its window.
  63775. */
  63776. DebugLayer.prototype.hide = function () {
  63777. if (this._inspector) {
  63778. try {
  63779. this._inspector.dispose();
  63780. }
  63781. catch (e) {
  63782. // If the inspector has been removed directly from the inspector tool
  63783. }
  63784. this.onPropertyChangedObservable.clear();
  63785. this._inspector = null;
  63786. }
  63787. };
  63788. /**
  63789. *
  63790. * Launch the debugLayer.
  63791. *
  63792. * initialTab:
  63793. * | Value | Tab Name |
  63794. * | --- | --- |
  63795. * | 0 | Scene |
  63796. * | 1 | Console |
  63797. * | 2 | Stats |
  63798. * | 3 | Textures |
  63799. * | 4 | Mesh |
  63800. * | 5 | Light |
  63801. * | 6 | Material |
  63802. * | 7 | GLTF |
  63803. * | 8 | GUI |
  63804. * | 9 | Physics |
  63805. * | 10 | Camera |
  63806. * | 11 | Audio |
  63807. *
  63808. * @param config Define the configuration of the inspector
  63809. */
  63810. DebugLayer.prototype.show = function (config) {
  63811. if (config === void 0) { config = {}; }
  63812. if (typeof this.BJSINSPECTOR == 'undefined') {
  63813. // Load inspector and add it to the DOM
  63814. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  63815. }
  63816. else {
  63817. // Otherwise creates the inspector
  63818. this._createInspector(config);
  63819. }
  63820. };
  63821. /**
  63822. * Gets the active tab
  63823. * @return the index of the active tab or -1 if the inspector is hidden
  63824. */
  63825. DebugLayer.prototype.getActiveTab = function () {
  63826. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  63827. };
  63828. /**
  63829. * Define the url to get the inspector script from.
  63830. * By default it uses the babylonjs CDN.
  63831. * @ignoreNaming
  63832. */
  63833. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  63834. return DebugLayer;
  63835. }());
  63836. BABYLON.DebugLayer = DebugLayer;
  63837. })(BABYLON || (BABYLON = {}));
  63838. //# sourceMappingURL=babylon.debugLayer.js.map
  63839. var BABYLON;
  63840. (function (BABYLON) {
  63841. var Debug;
  63842. (function (Debug) {
  63843. /**
  63844. * Used to show the physics impostor around the specific mesh
  63845. */
  63846. var PhysicsViewer = /** @class */ (function () {
  63847. /**
  63848. * Creates a new PhysicsViewer
  63849. * @param scene defines the hosting scene
  63850. */
  63851. function PhysicsViewer(scene) {
  63852. /** @hidden */
  63853. this._impostors = [];
  63854. /** @hidden */
  63855. this._meshes = [];
  63856. /** @hidden */
  63857. this._numMeshes = 0;
  63858. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  63859. var physicEngine = this._scene.getPhysicsEngine();
  63860. if (physicEngine) {
  63861. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  63862. }
  63863. }
  63864. /** @hidden */
  63865. PhysicsViewer.prototype._updateDebugMeshes = function () {
  63866. var plugin = this._physicsEnginePlugin;
  63867. for (var i = 0; i < this._numMeshes; i++) {
  63868. var impostor = this._impostors[i];
  63869. if (!impostor) {
  63870. continue;
  63871. }
  63872. if (impostor.isDisposed) {
  63873. this.hideImpostor(this._impostors[i--]);
  63874. }
  63875. else {
  63876. var mesh = this._meshes[i];
  63877. if (mesh && plugin) {
  63878. plugin.syncMeshWithImpostor(mesh, impostor);
  63879. }
  63880. }
  63881. }
  63882. };
  63883. /**
  63884. * Renders a specified physic impostor
  63885. * @param impostor defines the impostor to render
  63886. */
  63887. PhysicsViewer.prototype.showImpostor = function (impostor) {
  63888. if (!this._scene) {
  63889. return;
  63890. }
  63891. for (var i = 0; i < this._numMeshes; i++) {
  63892. if (this._impostors[i] == impostor) {
  63893. return;
  63894. }
  63895. }
  63896. var debugMesh = this._getDebugMesh(impostor, this._scene);
  63897. if (debugMesh) {
  63898. this._impostors[this._numMeshes] = impostor;
  63899. this._meshes[this._numMeshes] = debugMesh;
  63900. if (this._numMeshes === 0) {
  63901. this._renderFunction = this._updateDebugMeshes.bind(this);
  63902. this._scene.registerBeforeRender(this._renderFunction);
  63903. }
  63904. this._numMeshes++;
  63905. }
  63906. };
  63907. /**
  63908. * Hides a specified physic impostor
  63909. * @param impostor defines the impostor to hide
  63910. */
  63911. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  63912. if (!impostor || !this._scene) {
  63913. return;
  63914. }
  63915. var removed = false;
  63916. for (var i = 0; i < this._numMeshes; i++) {
  63917. if (this._impostors[i] == impostor) {
  63918. var mesh = this._meshes[i];
  63919. if (!mesh) {
  63920. continue;
  63921. }
  63922. this._scene.removeMesh(mesh);
  63923. mesh.dispose();
  63924. this._numMeshes--;
  63925. if (this._numMeshes > 0) {
  63926. this._meshes[i] = this._meshes[this._numMeshes];
  63927. this._impostors[i] = this._impostors[this._numMeshes];
  63928. this._meshes[this._numMeshes] = null;
  63929. this._impostors[this._numMeshes] = null;
  63930. }
  63931. else {
  63932. this._meshes[0] = null;
  63933. this._impostors[0] = null;
  63934. }
  63935. removed = true;
  63936. break;
  63937. }
  63938. }
  63939. if (removed && this._numMeshes === 0) {
  63940. this._scene.unregisterBeforeRender(this._renderFunction);
  63941. }
  63942. };
  63943. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  63944. if (!this._debugMaterial) {
  63945. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  63946. this._debugMaterial.wireframe = true;
  63947. }
  63948. return this._debugMaterial;
  63949. };
  63950. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  63951. if (!this._debugBoxMesh) {
  63952. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  63953. this._debugBoxMesh.renderingGroupId = 1;
  63954. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  63955. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  63956. scene.removeMesh(this._debugBoxMesh);
  63957. }
  63958. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  63959. };
  63960. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  63961. if (!this._debugSphereMesh) {
  63962. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  63963. this._debugSphereMesh.renderingGroupId = 1;
  63964. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  63965. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  63966. scene.removeMesh(this._debugSphereMesh);
  63967. }
  63968. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  63969. };
  63970. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  63971. var mesh = null;
  63972. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  63973. mesh = this._getDebugBoxMesh(scene);
  63974. impostor.getBoxSizeToRef(mesh.scaling);
  63975. }
  63976. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  63977. mesh = this._getDebugSphereMesh(scene);
  63978. var radius = impostor.getRadius();
  63979. mesh.scaling.x = radius * 2;
  63980. mesh.scaling.y = radius * 2;
  63981. mesh.scaling.z = radius * 2;
  63982. }
  63983. return mesh;
  63984. };
  63985. /** Releases all resources */
  63986. PhysicsViewer.prototype.dispose = function () {
  63987. for (var i = 0; i < this._numMeshes; i++) {
  63988. this.hideImpostor(this._impostors[i]);
  63989. }
  63990. if (this._debugBoxMesh) {
  63991. this._debugBoxMesh.dispose();
  63992. }
  63993. if (this._debugSphereMesh) {
  63994. this._debugSphereMesh.dispose();
  63995. }
  63996. if (this._debugMaterial) {
  63997. this._debugMaterial.dispose();
  63998. }
  63999. this._impostors.length = 0;
  64000. this._scene = null;
  64001. this._physicsEnginePlugin = null;
  64002. };
  64003. return PhysicsViewer;
  64004. }());
  64005. Debug.PhysicsViewer = PhysicsViewer;
  64006. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64007. })(BABYLON || (BABYLON = {}));
  64008. //# sourceMappingURL=babylon.physicsViewer.js.map
  64009. var BABYLON;
  64010. (function (BABYLON) {
  64011. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  64012. get: function () {
  64013. return this._forceShowBoundingBoxes || false;
  64014. },
  64015. set: function (value) {
  64016. this._forceShowBoundingBoxes = value;
  64017. // Lazyly creates a BB renderer if needed.
  64018. if (value) {
  64019. this.getBoundingBoxRenderer();
  64020. }
  64021. },
  64022. enumerable: true,
  64023. configurable: true
  64024. });
  64025. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  64026. if (!this._boundingBoxRenderer) {
  64027. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  64028. }
  64029. return this._boundingBoxRenderer;
  64030. };
  64031. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  64032. get: function () {
  64033. return this._showBoundingBox || false;
  64034. },
  64035. set: function (value) {
  64036. this._showBoundingBox = value;
  64037. // Lazyly creates a BB renderer if needed.
  64038. if (value) {
  64039. this.getScene().getBoundingBoxRenderer();
  64040. }
  64041. },
  64042. enumerable: true,
  64043. configurable: true
  64044. });
  64045. /**
  64046. * Component responsible of rendering the bounding box of the meshes in a scene.
  64047. * This is usually used through the mesh.showBoundingBox or the scene.forceShowBoundingBoxes properties
  64048. */
  64049. var BoundingBoxRenderer = /** @class */ (function () {
  64050. /**
  64051. * Instantiates a new bounding box renderer in a scene.
  64052. * @param scene the scene the renderer renders in
  64053. */
  64054. function BoundingBoxRenderer(scene) {
  64055. /**
  64056. * The component name helpfull to identify the component in the list of scene components.
  64057. */
  64058. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  64059. /**
  64060. * Color of the bounding box lines placed in front of an object
  64061. */
  64062. this.frontColor = new BABYLON.Color3(1, 1, 1);
  64063. /**
  64064. * Color of the bounding box lines placed behind an object
  64065. */
  64066. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  64067. /**
  64068. * Defines if the renderer should show the back lines or not
  64069. */
  64070. this.showBackLines = true;
  64071. /**
  64072. * @hidden
  64073. */
  64074. this.renderList = new BABYLON.SmartArray(32);
  64075. this._vertexBuffers = {};
  64076. this.scene = scene;
  64077. scene._addComponent(this);
  64078. }
  64079. /**
  64080. * Registers the component in a given scene
  64081. */
  64082. BoundingBoxRenderer.prototype.register = function () {
  64083. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  64084. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  64085. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  64086. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  64087. };
  64088. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  64089. if (mesh.showSubMeshesBoundingBox) {
  64090. var boundingInfo = subMesh.getBoundingInfo();
  64091. if (boundingInfo !== null && boundingInfo !== undefined) {
  64092. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  64093. this.renderList.push(boundingInfo.boundingBox);
  64094. }
  64095. }
  64096. };
  64097. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  64098. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  64099. var boundingInfo = sourceMesh.getBoundingInfo();
  64100. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  64101. this.renderList.push(boundingInfo.boundingBox);
  64102. }
  64103. };
  64104. BoundingBoxRenderer.prototype._prepareRessources = function () {
  64105. if (this._colorShader) {
  64106. return;
  64107. }
  64108. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  64109. attributes: [BABYLON.VertexBuffer.PositionKind],
  64110. uniforms: ["world", "viewProjection", "color"]
  64111. });
  64112. var engine = this.scene.getEngine();
  64113. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  64114. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  64115. this._createIndexBuffer();
  64116. };
  64117. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  64118. var engine = this.scene.getEngine();
  64119. 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]);
  64120. };
  64121. /**
  64122. * Rebuilds the elements related to this component in case of
  64123. * context lost for instance.
  64124. */
  64125. BoundingBoxRenderer.prototype.rebuild = function () {
  64126. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64127. if (vb) {
  64128. vb._rebuild();
  64129. }
  64130. this._createIndexBuffer();
  64131. };
  64132. /**
  64133. * @hidden
  64134. */
  64135. BoundingBoxRenderer.prototype.reset = function () {
  64136. this.renderList.reset();
  64137. };
  64138. /**
  64139. * Render the bounding boxes of a specific rendering group
  64140. * @param renderingGroupId defines the rendering group to render
  64141. */
  64142. BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
  64143. if (this.renderList.length === 0) {
  64144. return;
  64145. }
  64146. this._prepareRessources();
  64147. if (!this._colorShader.isReady()) {
  64148. return;
  64149. }
  64150. var engine = this.scene.getEngine();
  64151. engine.setDepthWrite(false);
  64152. this._colorShader._preBind();
  64153. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  64154. var boundingBox = this.renderList.data[boundingBoxIndex];
  64155. if (boundingBox._tag !== renderingGroupId) {
  64156. continue;
  64157. }
  64158. var min = boundingBox.minimum;
  64159. var max = boundingBox.maximum;
  64160. var diff = max.subtract(min);
  64161. var median = min.add(diff.scale(0.5));
  64162. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  64163. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  64164. .multiply(boundingBox.getWorldMatrix());
  64165. // VBOs
  64166. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  64167. if (this.showBackLines) {
  64168. // Back
  64169. engine.setDepthFunctionToGreaterOrEqual();
  64170. this.scene.resetCachedMaterial();
  64171. this._colorShader.setColor4("color", this.backColor.toColor4());
  64172. this._colorShader.bind(worldMatrix);
  64173. // Draw order
  64174. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  64175. }
  64176. // Front
  64177. engine.setDepthFunctionToLess();
  64178. this.scene.resetCachedMaterial();
  64179. this._colorShader.setColor4("color", this.frontColor.toColor4());
  64180. this._colorShader.bind(worldMatrix);
  64181. // Draw order
  64182. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  64183. }
  64184. this._colorShader.unbind();
  64185. engine.setDepthFunctionToLessOrEqual();
  64186. engine.setDepthWrite(true);
  64187. };
  64188. /**
  64189. * In case of occlusion queries, we can render the occlusion bounding box through this method
  64190. * @param mesh Define the mesh to render the occlusion bounding box for
  64191. */
  64192. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  64193. this._prepareRessources();
  64194. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  64195. return;
  64196. }
  64197. var engine = this.scene.getEngine();
  64198. engine.setDepthWrite(false);
  64199. engine.setColorWrite(false);
  64200. this._colorShader._preBind();
  64201. var boundingBox = mesh._boundingInfo.boundingBox;
  64202. var min = boundingBox.minimum;
  64203. var max = boundingBox.maximum;
  64204. var diff = max.subtract(min);
  64205. var median = min.add(diff.scale(0.5));
  64206. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  64207. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  64208. .multiply(boundingBox.getWorldMatrix());
  64209. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  64210. engine.setDepthFunctionToLess();
  64211. this.scene.resetCachedMaterial();
  64212. this._colorShader.bind(worldMatrix);
  64213. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  64214. this._colorShader.unbind();
  64215. engine.setDepthFunctionToLessOrEqual();
  64216. engine.setDepthWrite(true);
  64217. engine.setColorWrite(true);
  64218. };
  64219. /**
  64220. * Dispose and release the resources attached to this renderer.
  64221. */
  64222. BoundingBoxRenderer.prototype.dispose = function () {
  64223. if (!this._colorShader) {
  64224. return;
  64225. }
  64226. this.renderList.dispose();
  64227. this._colorShader.dispose();
  64228. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64229. if (buffer) {
  64230. buffer.dispose();
  64231. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64232. }
  64233. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  64234. };
  64235. return BoundingBoxRenderer;
  64236. }());
  64237. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  64238. })(BABYLON || (BABYLON = {}));
  64239. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  64240. var BABYLON;
  64241. (function (BABYLON) {
  64242. BABYLON.Engine.prototype.createTransformFeedback = function () {
  64243. return this._gl.createTransformFeedback();
  64244. };
  64245. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  64246. this._gl.deleteTransformFeedback(value);
  64247. };
  64248. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  64249. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  64250. };
  64251. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  64252. if (usePoints === void 0) { usePoints = true; }
  64253. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  64254. };
  64255. BABYLON.Engine.prototype.endTransformFeedback = function () {
  64256. this._gl.endTransformFeedback();
  64257. };
  64258. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  64259. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  64260. };
  64261. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  64262. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  64263. };
  64264. })(BABYLON || (BABYLON = {}));
  64265. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  64266. var BABYLON;
  64267. (function (BABYLON) {
  64268. /**
  64269. * This represents a GPU particle system in Babylon
  64270. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  64271. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  64272. */
  64273. var GPUParticleSystem = /** @class */ (function (_super) {
  64274. __extends(GPUParticleSystem, _super);
  64275. /**
  64276. * Instantiates a GPU particle system.
  64277. * 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.
  64278. * @param name The name of the particle system
  64279. * @param options The options used to create the system
  64280. * @param scene The scene the particle system belongs to
  64281. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  64282. */
  64283. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  64284. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  64285. var _this = _super.call(this, name) || this;
  64286. /**
  64287. * The layer mask we are rendering the particles through.
  64288. */
  64289. _this.layerMask = 0x0FFFFFFF;
  64290. _this._accumulatedCount = 0;
  64291. _this._targetIndex = 0;
  64292. _this._currentRenderId = -1;
  64293. _this._started = false;
  64294. _this._stopped = false;
  64295. _this._timeDelta = 0;
  64296. _this._attributesStrideSize = 21;
  64297. _this._actualFrame = 0;
  64298. _this._rawTextureWidth = 256;
  64299. /**
  64300. * An event triggered when the system is disposed.
  64301. */
  64302. _this.onDisposeObservable = new BABYLON.Observable();
  64303. /**
  64304. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  64305. * to override the particles.
  64306. */
  64307. _this.forceDepthWrite = false;
  64308. _this._preWarmDone = false;
  64309. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64310. // Setup the default processing configuration to the scene.
  64311. _this._attachImageProcessingConfiguration(null);
  64312. _this._engine = _this._scene.getEngine();
  64313. if (!options.randomTextureSize) {
  64314. delete options.randomTextureSize;
  64315. }
  64316. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  64317. var optionsAsNumber = options;
  64318. if (isFinite(optionsAsNumber)) {
  64319. fullOptions.capacity = optionsAsNumber;
  64320. }
  64321. _this._capacity = fullOptions.capacity;
  64322. _this._activeCount = fullOptions.capacity;
  64323. _this._currentActiveCount = 0;
  64324. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  64325. _this._scene.particleSystems.push(_this);
  64326. _this._updateEffectOptions = {
  64327. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  64328. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  64329. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  64330. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  64331. uniformBuffersNames: [],
  64332. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  64333. defines: "",
  64334. fallbacks: null,
  64335. onCompiled: null,
  64336. onError: null,
  64337. indexParameters: null,
  64338. maxSimultaneousLights: 0,
  64339. transformFeedbackVaryings: []
  64340. };
  64341. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  64342. // Random data
  64343. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  64344. var d = [];
  64345. for (var i = 0; i < maxTextureSize; ++i) {
  64346. d.push(Math.random());
  64347. d.push(Math.random());
  64348. d.push(Math.random());
  64349. d.push(Math.random());
  64350. }
  64351. _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);
  64352. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64353. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64354. d = [];
  64355. for (var i = 0; i < maxTextureSize; ++i) {
  64356. d.push(Math.random());
  64357. d.push(Math.random());
  64358. d.push(Math.random());
  64359. d.push(Math.random());
  64360. }
  64361. _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);
  64362. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64363. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64364. _this._randomTextureSize = maxTextureSize;
  64365. return _this;
  64366. }
  64367. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  64368. /**
  64369. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  64370. */
  64371. get: function () {
  64372. if (!BABYLON.Engine.LastCreatedEngine) {
  64373. return false;
  64374. }
  64375. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  64376. },
  64377. enumerable: true,
  64378. configurable: true
  64379. });
  64380. /**
  64381. * Gets the maximum number of particles active at the same time.
  64382. * @returns The max number of active particles.
  64383. */
  64384. GPUParticleSystem.prototype.getCapacity = function () {
  64385. return this._capacity;
  64386. };
  64387. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  64388. /**
  64389. * Gets or set the number of active particles
  64390. */
  64391. get: function () {
  64392. return this._activeCount;
  64393. },
  64394. set: function (value) {
  64395. this._activeCount = Math.min(value, this._capacity);
  64396. },
  64397. enumerable: true,
  64398. configurable: true
  64399. });
  64400. /**
  64401. * Is this system ready to be used/rendered
  64402. * @return true if the system is ready
  64403. */
  64404. GPUParticleSystem.prototype.isReady = function () {
  64405. if (!this._updateEffect) {
  64406. this._recreateUpdateEffect();
  64407. this._recreateRenderEffect();
  64408. return false;
  64409. }
  64410. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  64411. return false;
  64412. }
  64413. return true;
  64414. };
  64415. /**
  64416. * Gets if the system has been started. (Note: this will still be true after stop is called)
  64417. * @returns True if it has been started, otherwise false.
  64418. */
  64419. GPUParticleSystem.prototype.isStarted = function () {
  64420. return this._started;
  64421. };
  64422. /**
  64423. * Starts the particle system and begins to emit
  64424. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  64425. */
  64426. GPUParticleSystem.prototype.start = function (delay) {
  64427. var _this = this;
  64428. if (delay === void 0) { delay = this.startDelay; }
  64429. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  64430. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  64431. }
  64432. if (delay) {
  64433. setTimeout(function () {
  64434. _this.start(0);
  64435. }, delay);
  64436. return;
  64437. }
  64438. this._started = true;
  64439. this._stopped = false;
  64440. this._preWarmDone = false;
  64441. // Animations
  64442. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  64443. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  64444. }
  64445. };
  64446. /**
  64447. * Stops the particle system.
  64448. */
  64449. GPUParticleSystem.prototype.stop = function () {
  64450. this._stopped = true;
  64451. };
  64452. /**
  64453. * Remove all active particles
  64454. */
  64455. GPUParticleSystem.prototype.reset = function () {
  64456. this._releaseBuffers();
  64457. this._releaseVAOs();
  64458. this._currentActiveCount = 0;
  64459. this._targetIndex = 0;
  64460. };
  64461. /**
  64462. * Returns the string "GPUParticleSystem"
  64463. * @returns a string containing the class name
  64464. */
  64465. GPUParticleSystem.prototype.getClassName = function () {
  64466. return "GPUParticleSystem";
  64467. };
  64468. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  64469. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  64470. this._releaseBuffers();
  64471. return this;
  64472. };
  64473. /**
  64474. * Adds a new color gradient
  64475. * @param gradient defines the gradient to use (between 0 and 1)
  64476. * @param color1 defines the color to affect to the specified gradient
  64477. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  64478. * @returns the current particle system
  64479. */
  64480. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  64481. if (!this._colorGradients) {
  64482. this._colorGradients = [];
  64483. }
  64484. var colorGradient = new BABYLON.ColorGradient();
  64485. colorGradient.gradient = gradient;
  64486. colorGradient.color1 = color1;
  64487. this._colorGradients.push(colorGradient);
  64488. this._colorGradients.sort(function (a, b) {
  64489. if (a.gradient < b.gradient) {
  64490. return -1;
  64491. }
  64492. else if (a.gradient > b.gradient) {
  64493. return 1;
  64494. }
  64495. return 0;
  64496. });
  64497. if (this._colorGradientsTexture) {
  64498. this._colorGradientsTexture.dispose();
  64499. this._colorGradientsTexture = null;
  64500. }
  64501. this._releaseBuffers();
  64502. return this;
  64503. };
  64504. /**
  64505. * Remove a specific color gradient
  64506. * @param gradient defines the gradient to remove
  64507. * @returns the current particle system
  64508. */
  64509. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  64510. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  64511. this._colorGradientsTexture = null;
  64512. return this;
  64513. };
  64514. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  64515. var valueGradient = new BABYLON.FactorGradient();
  64516. valueGradient.gradient = gradient;
  64517. valueGradient.factor1 = factor;
  64518. factorGradients.push(valueGradient);
  64519. factorGradients.sort(function (a, b) {
  64520. if (a.gradient < b.gradient) {
  64521. return -1;
  64522. }
  64523. else if (a.gradient > b.gradient) {
  64524. return 1;
  64525. }
  64526. return 0;
  64527. });
  64528. this._releaseBuffers();
  64529. };
  64530. /**
  64531. * Adds a new size gradient
  64532. * @param gradient defines the gradient to use (between 0 and 1)
  64533. * @param factor defines the size factor to affect to the specified gradient
  64534. * @returns the current particle system
  64535. */
  64536. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  64537. if (!this._sizeGradients) {
  64538. this._sizeGradients = [];
  64539. }
  64540. this._addFactorGradient(this._sizeGradients, gradient, factor);
  64541. if (this._sizeGradientsTexture) {
  64542. this._sizeGradientsTexture.dispose();
  64543. this._sizeGradientsTexture = null;
  64544. }
  64545. this._releaseBuffers();
  64546. return this;
  64547. };
  64548. /**
  64549. * Remove a specific size gradient
  64550. * @param gradient defines the gradient to remove
  64551. * @returns the current particle system
  64552. */
  64553. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  64554. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  64555. this._sizeGradientsTexture = null;
  64556. return this;
  64557. };
  64558. /**
  64559. * Adds a new angular speed gradient
  64560. * @param gradient defines the gradient to use (between 0 and 1)
  64561. * @param factor defines the angular speed to affect to the specified gradient
  64562. * @returns the current particle system
  64563. */
  64564. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  64565. if (!this._angularSpeedGradients) {
  64566. this._angularSpeedGradients = [];
  64567. }
  64568. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  64569. if (this._angularSpeedGradientsTexture) {
  64570. this._angularSpeedGradientsTexture.dispose();
  64571. this._angularSpeedGradientsTexture = null;
  64572. }
  64573. this._releaseBuffers();
  64574. return this;
  64575. };
  64576. /**
  64577. * Remove a specific angular speed gradient
  64578. * @param gradient defines the gradient to remove
  64579. * @returns the current particle system
  64580. */
  64581. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  64582. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  64583. this._angularSpeedGradientsTexture = null;
  64584. return this;
  64585. };
  64586. /**
  64587. * Adds a new velocity gradient
  64588. * @param gradient defines the gradient to use (between 0 and 1)
  64589. * @param factor defines the velocity to affect to the specified gradient
  64590. * @returns the current particle system
  64591. */
  64592. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  64593. if (!this._velocityGradients) {
  64594. this._velocityGradients = [];
  64595. }
  64596. this._addFactorGradient(this._velocityGradients, gradient, factor);
  64597. if (this._velocityGradientsTexture) {
  64598. this._velocityGradientsTexture.dispose();
  64599. this._velocityGradientsTexture = null;
  64600. }
  64601. this._releaseBuffers();
  64602. return this;
  64603. };
  64604. /**
  64605. * Remove a specific velocity gradient
  64606. * @param gradient defines the gradient to remove
  64607. * @returns the current particle system
  64608. */
  64609. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  64610. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  64611. this._velocityGradientsTexture = null;
  64612. return this;
  64613. };
  64614. /**
  64615. * Adds a new limit velocity gradient
  64616. * @param gradient defines the gradient to use (between 0 and 1)
  64617. * @param factor defines the limit velocity value to affect to the specified gradient
  64618. * @returns the current particle system
  64619. */
  64620. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  64621. if (!this._limitVelocityGradients) {
  64622. this._limitVelocityGradients = [];
  64623. }
  64624. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  64625. if (this._limitVelocityGradientsTexture) {
  64626. this._limitVelocityGradientsTexture.dispose();
  64627. this._limitVelocityGradientsTexture = null;
  64628. }
  64629. this._releaseBuffers();
  64630. return this;
  64631. };
  64632. /**
  64633. * Remove a specific limit velocity gradient
  64634. * @param gradient defines the gradient to remove
  64635. * @returns the current particle system
  64636. */
  64637. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  64638. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  64639. this._limitVelocityGradientsTexture = null;
  64640. return this;
  64641. };
  64642. /**
  64643. * Adds a new drag gradient
  64644. * @param gradient defines the gradient to use (between 0 and 1)
  64645. * @param factor defines the drag value to affect to the specified gradient
  64646. * @returns the current particle system
  64647. */
  64648. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  64649. if (!this._dragGradients) {
  64650. this._dragGradients = [];
  64651. }
  64652. this._addFactorGradient(this._dragGradients, gradient, factor);
  64653. if (this._dragGradientsTexture) {
  64654. this._dragGradientsTexture.dispose();
  64655. this._dragGradientsTexture = null;
  64656. }
  64657. this._releaseBuffers();
  64658. return this;
  64659. };
  64660. /**
  64661. * Remove a specific drag gradient
  64662. * @param gradient defines the gradient to remove
  64663. * @returns the current particle system
  64664. */
  64665. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  64666. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  64667. this._dragGradientsTexture = null;
  64668. return this;
  64669. };
  64670. /**
  64671. * Not supported by GPUParticleSystem
  64672. * @param gradient defines the gradient to use (between 0 and 1)
  64673. * @param factor defines the emit rate value to affect to the specified gradient
  64674. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  64675. * @returns the current particle system
  64676. */
  64677. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  64678. // Do nothing as emit rate is not supported by GPUParticleSystem
  64679. return this;
  64680. };
  64681. /**
  64682. * Not supported by GPUParticleSystem
  64683. * @param gradient defines the gradient to remove
  64684. * @returns the current particle system
  64685. */
  64686. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  64687. // Do nothing as emit rate is not supported by GPUParticleSystem
  64688. return this;
  64689. };
  64690. /**
  64691. * Not supported by GPUParticleSystem
  64692. * @param gradient defines the gradient to use (between 0 and 1)
  64693. * @param factor defines the start size value to affect to the specified gradient
  64694. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  64695. * @returns the current particle system
  64696. */
  64697. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  64698. // Do nothing as start size is not supported by GPUParticleSystem
  64699. return this;
  64700. };
  64701. /**
  64702. * Not supported by GPUParticleSystem
  64703. * @param gradient defines the gradient to remove
  64704. * @returns the current particle system
  64705. */
  64706. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  64707. // Do nothing as start size is not supported by GPUParticleSystem
  64708. return this;
  64709. };
  64710. /**
  64711. * Not supported by GPUParticleSystem
  64712. * @param gradient defines the gradient to use (between 0 and 1)
  64713. * @param min defines the color remap minimal range
  64714. * @param max defines the color remap maximal range
  64715. * @returns the current particle system
  64716. */
  64717. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  64718. // Do nothing as start size is not supported by GPUParticleSystem
  64719. return this;
  64720. };
  64721. /**
  64722. * Not supported by GPUParticleSystem
  64723. * @param gradient defines the gradient to remove
  64724. * @returns the current particle system
  64725. */
  64726. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  64727. // Do nothing as start size is not supported by GPUParticleSystem
  64728. return this;
  64729. };
  64730. /**
  64731. * Not supported by GPUParticleSystem
  64732. * @param gradient defines the gradient to use (between 0 and 1)
  64733. * @param min defines the alpha remap minimal range
  64734. * @param max defines the alpha remap maximal range
  64735. * @returns the current particle system
  64736. */
  64737. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  64738. // Do nothing as start size is not supported by GPUParticleSystem
  64739. return this;
  64740. };
  64741. /**
  64742. * Not supported by GPUParticleSystem
  64743. * @param gradient defines the gradient to remove
  64744. * @returns the current particle system
  64745. */
  64746. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  64747. // Do nothing as start size is not supported by GPUParticleSystem
  64748. return this;
  64749. };
  64750. /**
  64751. * Not supported by GPUParticleSystem
  64752. * @param gradient defines the gradient to use (between 0 and 1)
  64753. * @param color defines the color to affect to the specified gradient
  64754. * @returns the current particle system
  64755. */
  64756. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  64757. //Not supported by GPUParticleSystem
  64758. return this;
  64759. };
  64760. /**
  64761. * Not supported by GPUParticleSystem
  64762. * @param gradient defines the gradient to remove
  64763. * @returns the current particle system
  64764. */
  64765. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  64766. //Not supported by GPUParticleSystem
  64767. return this;
  64768. };
  64769. /**
  64770. * Not supported by GPUParticleSystem
  64771. * @returns the list of ramp gradients
  64772. */
  64773. GPUParticleSystem.prototype.getRampGradients = function () {
  64774. return null;
  64775. };
  64776. Object.defineProperty(GPUParticleSystem.prototype, "useRampGradients", {
  64777. /**
  64778. * Not supported by GPUParticleSystem
  64779. * Gets or sets a boolean indicating that ramp gradients must be used
  64780. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  64781. */
  64782. get: function () {
  64783. //Not supported by GPUParticleSystem
  64784. return false;
  64785. },
  64786. set: function (value) {
  64787. //Not supported by GPUParticleSystem
  64788. },
  64789. enumerable: true,
  64790. configurable: true
  64791. });
  64792. /**
  64793. * Not supported by GPUParticleSystem
  64794. * @param gradient defines the gradient to use (between 0 and 1)
  64795. * @param factor defines the life time factor to affect to the specified gradient
  64796. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  64797. * @returns the current particle system
  64798. */
  64799. GPUParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  64800. //Not supported by GPUParticleSystem
  64801. return this;
  64802. };
  64803. /**
  64804. * Not supported by GPUParticleSystem
  64805. * @param gradient defines the gradient to remove
  64806. * @returns the current particle system
  64807. */
  64808. GPUParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  64809. //Not supported by GPUParticleSystem
  64810. return this;
  64811. };
  64812. GPUParticleSystem.prototype._reset = function () {
  64813. this._releaseBuffers();
  64814. };
  64815. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  64816. var updateVertexBuffers = {};
  64817. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  64818. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  64819. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  64820. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  64821. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  64822. var offset = 12;
  64823. if (!this._colorGradientsTexture) {
  64824. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  64825. offset += 4;
  64826. }
  64827. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  64828. offset += 3;
  64829. if (!this._isBillboardBased) {
  64830. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  64831. offset += 3;
  64832. }
  64833. if (this._angularSpeedGradientsTexture) {
  64834. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  64835. offset += 1;
  64836. }
  64837. else {
  64838. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  64839. offset += 2;
  64840. }
  64841. if (this._isAnimationSheetEnabled) {
  64842. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  64843. offset += 1;
  64844. if (this.spriteRandomStartCell) {
  64845. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  64846. offset += 1;
  64847. }
  64848. }
  64849. if (this.noiseTexture) {
  64850. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  64851. offset += 3;
  64852. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  64853. offset += 3;
  64854. }
  64855. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  64856. this._engine.bindArrayBuffer(null);
  64857. return vao;
  64858. };
  64859. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  64860. var renderVertexBuffers = {};
  64861. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  64862. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  64863. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  64864. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  64865. var offset = 12;
  64866. if (!this._colorGradientsTexture) {
  64867. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  64868. offset += 4;
  64869. }
  64870. if (this.billboardMode === BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED) {
  64871. renderVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
  64872. }
  64873. offset += 3; // Direction
  64874. if (!this._isBillboardBased) {
  64875. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  64876. offset += 3;
  64877. }
  64878. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  64879. if (this._angularSpeedGradientsTexture) {
  64880. offset++;
  64881. }
  64882. else {
  64883. offset += 2;
  64884. }
  64885. if (this._isAnimationSheetEnabled) {
  64886. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  64887. offset += 1;
  64888. if (this.spriteRandomStartCell) {
  64889. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  64890. offset += 1;
  64891. }
  64892. }
  64893. if (this.noiseTexture) {
  64894. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  64895. offset += 3;
  64896. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  64897. offset += 3;
  64898. }
  64899. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  64900. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  64901. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  64902. this._engine.bindArrayBuffer(null);
  64903. return vao;
  64904. };
  64905. GPUParticleSystem.prototype._initialize = function (force) {
  64906. if (force === void 0) { force = false; }
  64907. if (this._buffer0 && !force) {
  64908. return;
  64909. }
  64910. var engine = this._scene.getEngine();
  64911. var data = new Array();
  64912. if (!this.isBillboardBased) {
  64913. this._attributesStrideSize += 3;
  64914. }
  64915. if (this._colorGradientsTexture) {
  64916. this._attributesStrideSize -= 4;
  64917. }
  64918. if (this._angularSpeedGradientsTexture) {
  64919. this._attributesStrideSize -= 1;
  64920. }
  64921. if (this._isAnimationSheetEnabled) {
  64922. this._attributesStrideSize += 1;
  64923. if (this.spriteRandomStartCell) {
  64924. this._attributesStrideSize += 1;
  64925. }
  64926. }
  64927. if (this.noiseTexture) {
  64928. this._attributesStrideSize += 6;
  64929. }
  64930. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  64931. // position
  64932. data.push(0.0);
  64933. data.push(0.0);
  64934. data.push(0.0);
  64935. // Age and life
  64936. data.push(0.0); // create the particle as a dead one to create a new one at start
  64937. data.push(0.0);
  64938. // Seed
  64939. data.push(Math.random());
  64940. data.push(Math.random());
  64941. data.push(Math.random());
  64942. data.push(Math.random());
  64943. // Size
  64944. data.push(0.0);
  64945. data.push(0.0);
  64946. data.push(0.0);
  64947. if (!this._colorGradientsTexture) {
  64948. // color
  64949. data.push(0.0);
  64950. data.push(0.0);
  64951. data.push(0.0);
  64952. data.push(0.0);
  64953. }
  64954. // direction
  64955. data.push(0.0);
  64956. data.push(0.0);
  64957. data.push(0.0);
  64958. if (!this.isBillboardBased) {
  64959. // initialDirection
  64960. data.push(0.0);
  64961. data.push(0.0);
  64962. data.push(0.0);
  64963. }
  64964. // angle
  64965. data.push(0.0);
  64966. if (!this._angularSpeedGradientsTexture) {
  64967. data.push(0.0);
  64968. }
  64969. if (this._isAnimationSheetEnabled) {
  64970. data.push(0.0);
  64971. if (this.spriteRandomStartCell) {
  64972. data.push(0.0);
  64973. }
  64974. }
  64975. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  64976. data.push(Math.random());
  64977. data.push(Math.random());
  64978. data.push(Math.random());
  64979. data.push(Math.random());
  64980. data.push(Math.random());
  64981. data.push(Math.random());
  64982. }
  64983. }
  64984. // Sprite data
  64985. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  64986. -0.5, 0.5, 0, 1,
  64987. -0.5, -0.5, 0, 0,
  64988. 0.5, -0.5, 1, 0]);
  64989. // Buffers
  64990. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  64991. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  64992. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  64993. // Update VAO
  64994. this._updateVAO = [];
  64995. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  64996. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  64997. // Render VAO
  64998. this._renderVAO = [];
  64999. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  65000. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  65001. // Links
  65002. this._sourceBuffer = this._buffer0;
  65003. this._targetBuffer = this._buffer1;
  65004. };
  65005. /** @hidden */
  65006. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  65007. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  65008. if (this._isBillboardBased) {
  65009. defines += "\n#define BILLBOARD";
  65010. }
  65011. if (this._colorGradientsTexture) {
  65012. defines += "\n#define COLORGRADIENTS";
  65013. }
  65014. if (this._sizeGradientsTexture) {
  65015. defines += "\n#define SIZEGRADIENTS";
  65016. }
  65017. if (this._angularSpeedGradientsTexture) {
  65018. defines += "\n#define ANGULARSPEEDGRADIENTS";
  65019. }
  65020. if (this._velocityGradientsTexture) {
  65021. defines += "\n#define VELOCITYGRADIENTS";
  65022. }
  65023. if (this._limitVelocityGradientsTexture) {
  65024. defines += "\n#define LIMITVELOCITYGRADIENTS";
  65025. }
  65026. if (this._dragGradientsTexture) {
  65027. defines += "\n#define DRAGGRADIENTS";
  65028. }
  65029. if (this.isAnimationSheetEnabled) {
  65030. defines += "\n#define ANIMATESHEET";
  65031. if (this.spriteRandomStartCell) {
  65032. defines += "\n#define ANIMATESHEETRANDOMSTART";
  65033. }
  65034. }
  65035. if (this.noiseTexture) {
  65036. defines += "\n#define NOISE";
  65037. }
  65038. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  65039. return;
  65040. }
  65041. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  65042. if (!this._colorGradientsTexture) {
  65043. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  65044. }
  65045. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  65046. if (!this._isBillboardBased) {
  65047. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  65048. }
  65049. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  65050. if (this.isAnimationSheetEnabled) {
  65051. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  65052. if (this.spriteRandomStartCell) {
  65053. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  65054. }
  65055. }
  65056. if (this.noiseTexture) {
  65057. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  65058. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  65059. }
  65060. this._updateEffectOptions.defines = defines;
  65061. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  65062. };
  65063. /** @hidden */
  65064. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  65065. var defines = "";
  65066. if (this._scene.clipPlane) {
  65067. defines = "\n#define CLIPPLANE";
  65068. }
  65069. if (this._scene.clipPlane2) {
  65070. defines = "\n#define CLIPPLANE2";
  65071. }
  65072. if (this._scene.clipPlane3) {
  65073. defines = "\n#define CLIPPLANE3";
  65074. }
  65075. if (this._scene.clipPlane4) {
  65076. defines = "\n#define CLIPPLANE4";
  65077. }
  65078. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  65079. defines = "\n#define BLENDMULTIPLYMODE";
  65080. }
  65081. if (this._isBillboardBased) {
  65082. defines += "\n#define BILLBOARD";
  65083. switch (this.billboardMode) {
  65084. case BABYLON.ParticleSystem.BILLBOARDMODE_Y:
  65085. defines += "\n#define BILLBOARDY";
  65086. break;
  65087. case BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED:
  65088. defines += "\n#define BILLBOARDSTRETCHED";
  65089. break;
  65090. case BABYLON.ParticleSystem.BILLBOARDMODE_ALL:
  65091. default:
  65092. break;
  65093. }
  65094. }
  65095. if (this._colorGradientsTexture) {
  65096. defines += "\n#define COLORGRADIENTS";
  65097. }
  65098. if (this.isAnimationSheetEnabled) {
  65099. defines += "\n#define ANIMATESHEET";
  65100. }
  65101. if (this._imageProcessingConfiguration) {
  65102. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  65103. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  65104. }
  65105. if (this._renderEffect && this._renderEffect.defines === defines) {
  65106. return;
  65107. }
  65108. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  65109. var samplers = ["textureSampler", "colorGradientSampler"];
  65110. if (BABYLON.ImageProcessingConfiguration) {
  65111. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  65112. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  65113. }
  65114. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "direction", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  65115. };
  65116. /**
  65117. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  65118. * @param preWarm defines if we are in the pre-warmimg phase
  65119. */
  65120. GPUParticleSystem.prototype.animate = function (preWarm) {
  65121. if (preWarm === void 0) { preWarm = false; }
  65122. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  65123. this._actualFrame += this._timeDelta;
  65124. if (!this._stopped) {
  65125. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  65126. this.stop();
  65127. }
  65128. }
  65129. };
  65130. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  65131. var texture = this[textureName];
  65132. if (!factorGradients || !factorGradients.length || texture) {
  65133. return;
  65134. }
  65135. var data = new Float32Array(this._rawTextureWidth);
  65136. for (var x = 0; x < this._rawTextureWidth; x++) {
  65137. var ratio = x / this._rawTextureWidth;
  65138. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  65139. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  65140. });
  65141. }
  65142. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  65143. };
  65144. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  65145. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  65146. };
  65147. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  65148. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  65149. };
  65150. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  65151. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  65152. };
  65153. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  65154. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  65155. };
  65156. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  65157. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  65158. };
  65159. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  65160. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  65161. return;
  65162. }
  65163. var data = new Uint8Array(this._rawTextureWidth * 4);
  65164. var tmpColor = BABYLON.Tmp.Color4[0];
  65165. for (var x = 0; x < this._rawTextureWidth; x++) {
  65166. var ratio = x / this._rawTextureWidth;
  65167. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  65168. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  65169. data[x * 4] = tmpColor.r * 255;
  65170. data[x * 4 + 1] = tmpColor.g * 255;
  65171. data[x * 4 + 2] = tmpColor.b * 255;
  65172. data[x * 4 + 3] = tmpColor.a * 255;
  65173. });
  65174. }
  65175. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  65176. };
  65177. /**
  65178. * Renders the particle system in its current state
  65179. * @param preWarm defines if the system should only update the particles but not render them
  65180. * @returns the current number of particles
  65181. */
  65182. GPUParticleSystem.prototype.render = function (preWarm) {
  65183. if (preWarm === void 0) { preWarm = false; }
  65184. if (!this._started) {
  65185. return 0;
  65186. }
  65187. this._createColorGradientTexture();
  65188. this._createSizeGradientTexture();
  65189. this._createAngularSpeedGradientTexture();
  65190. this._createVelocityGradientTexture();
  65191. this._createLimitVelocityGradientTexture();
  65192. this._createDragGradientTexture();
  65193. this._recreateUpdateEffect();
  65194. this._recreateRenderEffect();
  65195. if (!this.isReady()) {
  65196. return 0;
  65197. }
  65198. if (!preWarm) {
  65199. if (!this._preWarmDone && this.preWarmCycles) {
  65200. for (var index = 0; index < this.preWarmCycles; index++) {
  65201. this.animate(true);
  65202. this.render(true);
  65203. }
  65204. this._preWarmDone = true;
  65205. }
  65206. if (this._currentRenderId === this._scene.getRenderId()) {
  65207. return 0;
  65208. }
  65209. this._currentRenderId = this._scene.getRenderId();
  65210. }
  65211. // Get everything ready to render
  65212. this._initialize();
  65213. this._accumulatedCount += this.emitRate * this._timeDelta;
  65214. if (this._accumulatedCount > 1) {
  65215. var intPart = this._accumulatedCount | 0;
  65216. this._accumulatedCount -= intPart;
  65217. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  65218. }
  65219. if (!this._currentActiveCount) {
  65220. return 0;
  65221. }
  65222. // Enable update effect
  65223. this._engine.enableEffect(this._updateEffect);
  65224. this._engine.setState(false);
  65225. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  65226. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  65227. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  65228. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  65229. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  65230. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  65231. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  65232. if (!this._colorGradientsTexture) {
  65233. this._updateEffect.setDirectColor4("color1", this.color1);
  65234. this._updateEffect.setDirectColor4("color2", this.color2);
  65235. }
  65236. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  65237. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  65238. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  65239. this._updateEffect.setVector3("gravity", this.gravity);
  65240. if (this._sizeGradientsTexture) {
  65241. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  65242. }
  65243. if (this._angularSpeedGradientsTexture) {
  65244. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  65245. }
  65246. if (this._velocityGradientsTexture) {
  65247. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  65248. }
  65249. if (this._limitVelocityGradientsTexture) {
  65250. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  65251. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  65252. }
  65253. if (this._dragGradientsTexture) {
  65254. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  65255. }
  65256. if (this.particleEmitterType) {
  65257. this.particleEmitterType.applyToShader(this._updateEffect);
  65258. }
  65259. if (this._isAnimationSheetEnabled) {
  65260. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  65261. }
  65262. if (this.noiseTexture) {
  65263. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  65264. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  65265. }
  65266. var emitterWM;
  65267. if (this.emitter.position) {
  65268. var emitterMesh = this.emitter;
  65269. emitterWM = emitterMesh.getWorldMatrix();
  65270. }
  65271. else {
  65272. var emitterPosition = this.emitter;
  65273. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  65274. }
  65275. this._updateEffect.setMatrix("emitterWM", emitterWM);
  65276. // Bind source VAO
  65277. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  65278. // Update
  65279. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  65280. this._engine.setRasterizerState(false);
  65281. this._engine.beginTransformFeedback(true);
  65282. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  65283. this._engine.endTransformFeedback();
  65284. this._engine.setRasterizerState(true);
  65285. this._engine.bindTransformFeedbackBuffer(null);
  65286. if (!preWarm) {
  65287. // Enable render effect
  65288. this._engine.enableEffect(this._renderEffect);
  65289. var viewMatrix = this._scene.getViewMatrix();
  65290. this._renderEffect.setMatrix("view", viewMatrix);
  65291. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  65292. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  65293. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  65294. if (this._colorGradientsTexture) {
  65295. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  65296. }
  65297. else {
  65298. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  65299. }
  65300. if (this._isAnimationSheetEnabled && this.particleTexture) {
  65301. var baseSize = this.particleTexture.getBaseSize();
  65302. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  65303. }
  65304. if (this._isBillboardBased) {
  65305. var camera = this._scene.activeCamera;
  65306. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  65307. }
  65308. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  65309. var invView = viewMatrix.clone();
  65310. invView.invert();
  65311. this._renderEffect.setMatrix("invView", invView);
  65312. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  65313. }
  65314. // image processing
  65315. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  65316. this._imageProcessingConfiguration.bind(this._renderEffect);
  65317. }
  65318. // Draw order
  65319. switch (this.blendMode) {
  65320. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  65321. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  65322. break;
  65323. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  65324. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  65325. break;
  65326. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  65327. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  65328. break;
  65329. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  65330. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  65331. break;
  65332. }
  65333. if (this.forceDepthWrite) {
  65334. this._engine.setDepthWrite(true);
  65335. }
  65336. // Bind source VAO
  65337. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  65338. // Render
  65339. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  65340. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65341. }
  65342. // Switch VAOs
  65343. this._targetIndex++;
  65344. if (this._targetIndex === 2) {
  65345. this._targetIndex = 0;
  65346. }
  65347. // Switch buffers
  65348. var tmpBuffer = this._sourceBuffer;
  65349. this._sourceBuffer = this._targetBuffer;
  65350. this._targetBuffer = tmpBuffer;
  65351. return this._currentActiveCount;
  65352. };
  65353. /**
  65354. * Rebuilds the particle system
  65355. */
  65356. GPUParticleSystem.prototype.rebuild = function () {
  65357. this._initialize(true);
  65358. };
  65359. GPUParticleSystem.prototype._releaseBuffers = function () {
  65360. if (this._buffer0) {
  65361. this._buffer0.dispose();
  65362. this._buffer0 = null;
  65363. }
  65364. if (this._buffer1) {
  65365. this._buffer1.dispose();
  65366. this._buffer1 = null;
  65367. }
  65368. if (this._spriteBuffer) {
  65369. this._spriteBuffer.dispose();
  65370. this._spriteBuffer = null;
  65371. }
  65372. };
  65373. GPUParticleSystem.prototype._releaseVAOs = function () {
  65374. if (!this._updateVAO) {
  65375. return;
  65376. }
  65377. for (var index = 0; index < this._updateVAO.length; index++) {
  65378. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  65379. }
  65380. this._updateVAO = [];
  65381. for (var index = 0; index < this._renderVAO.length; index++) {
  65382. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  65383. }
  65384. this._renderVAO = [];
  65385. };
  65386. /**
  65387. * Disposes the particle system and free the associated resources
  65388. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  65389. */
  65390. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  65391. if (disposeTexture === void 0) { disposeTexture = true; }
  65392. var index = this._scene.particleSystems.indexOf(this);
  65393. if (index > -1) {
  65394. this._scene.particleSystems.splice(index, 1);
  65395. }
  65396. this._releaseBuffers();
  65397. this._releaseVAOs();
  65398. if (this._colorGradientsTexture) {
  65399. this._colorGradientsTexture.dispose();
  65400. this._colorGradientsTexture = null;
  65401. }
  65402. if (this._sizeGradientsTexture) {
  65403. this._sizeGradientsTexture.dispose();
  65404. this._sizeGradientsTexture = null;
  65405. }
  65406. if (this._angularSpeedGradientsTexture) {
  65407. this._angularSpeedGradientsTexture.dispose();
  65408. this._angularSpeedGradientsTexture = null;
  65409. }
  65410. if (this._velocityGradientsTexture) {
  65411. this._velocityGradientsTexture.dispose();
  65412. this._velocityGradientsTexture = null;
  65413. }
  65414. if (this._limitVelocityGradientsTexture) {
  65415. this._limitVelocityGradientsTexture.dispose();
  65416. this._limitVelocityGradientsTexture = null;
  65417. }
  65418. if (this._dragGradientsTexture) {
  65419. this._dragGradientsTexture.dispose();
  65420. this._dragGradientsTexture = null;
  65421. }
  65422. if (this._randomTexture) {
  65423. this._randomTexture.dispose();
  65424. this._randomTexture = null;
  65425. }
  65426. if (this._randomTexture2) {
  65427. this._randomTexture2.dispose();
  65428. this._randomTexture2 = null;
  65429. }
  65430. if (disposeTexture && this.particleTexture) {
  65431. this.particleTexture.dispose();
  65432. this.particleTexture = null;
  65433. }
  65434. if (disposeTexture && this.noiseTexture) {
  65435. this.noiseTexture.dispose();
  65436. this.noiseTexture = null;
  65437. }
  65438. // Callback
  65439. this.onDisposeObservable.notifyObservers(this);
  65440. this.onDisposeObservable.clear();
  65441. };
  65442. /**
  65443. * Clones the particle system.
  65444. * @param name The name of the cloned object
  65445. * @param newEmitter The new emitter to use
  65446. * @returns the cloned particle system
  65447. */
  65448. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  65449. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  65450. BABYLON.Tools.DeepCopy(this, result);
  65451. if (newEmitter === undefined) {
  65452. newEmitter = this.emitter;
  65453. }
  65454. result.emitter = newEmitter;
  65455. if (this.particleTexture) {
  65456. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  65457. }
  65458. return result;
  65459. };
  65460. /**
  65461. * Serializes the particle system to a JSON object.
  65462. * @returns the JSON object
  65463. */
  65464. GPUParticleSystem.prototype.serialize = function () {
  65465. var serializationObject = {};
  65466. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  65467. serializationObject.activeParticleCount = this.activeParticleCount;
  65468. return serializationObject;
  65469. };
  65470. /**
  65471. * Parses a JSON object to create a GPU particle system.
  65472. * @param parsedParticleSystem The JSON object to parse
  65473. * @param scene The scene to create the particle system in
  65474. * @param rootUrl The root url to use to load external dependencies like texture
  65475. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  65476. * @returns the parsed GPU particle system
  65477. */
  65478. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  65479. if (doNotStart === void 0) { doNotStart = false; }
  65480. var name = parsedParticleSystem.name;
  65481. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  65482. if (parsedParticleSystem.activeParticleCount) {
  65483. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  65484. }
  65485. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  65486. // Auto start
  65487. if (parsedParticleSystem.preventAutoStart) {
  65488. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  65489. }
  65490. if (!doNotStart && !particleSystem.preventAutoStart) {
  65491. particleSystem.start();
  65492. }
  65493. return particleSystem;
  65494. };
  65495. return GPUParticleSystem;
  65496. }(BABYLON.BaseParticleSystem));
  65497. BABYLON.GPUParticleSystem = GPUParticleSystem;
  65498. })(BABYLON || (BABYLON = {}));
  65499. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  65500. var BABYLON;
  65501. (function (BABYLON) {
  65502. /**
  65503. * Represents one particle of a solid particle system.
  65504. */
  65505. var SolidParticle = /** @class */ (function () {
  65506. /**
  65507. * Creates a Solid Particle object.
  65508. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  65509. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  65510. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  65511. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  65512. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  65513. * @param shapeId (integer) is the model shape identifier in the SPS.
  65514. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  65515. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  65516. */
  65517. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  65518. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  65519. /**
  65520. * particle global index
  65521. */
  65522. this.idx = 0;
  65523. /**
  65524. * The color of the particle
  65525. */
  65526. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  65527. /**
  65528. * The world space position of the particle.
  65529. */
  65530. this.position = BABYLON.Vector3.Zero();
  65531. /**
  65532. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  65533. */
  65534. this.rotation = BABYLON.Vector3.Zero();
  65535. /**
  65536. * The scaling of the particle.
  65537. */
  65538. this.scaling = BABYLON.Vector3.One();
  65539. /**
  65540. * The uvs of the particle.
  65541. */
  65542. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  65543. /**
  65544. * The current speed of the particle.
  65545. */
  65546. this.velocity = BABYLON.Vector3.Zero();
  65547. /**
  65548. * The pivot point in the particle local space.
  65549. */
  65550. this.pivot = BABYLON.Vector3.Zero();
  65551. /**
  65552. * Must the particle be translated from its pivot point in its local space ?
  65553. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  65554. * Default : false
  65555. */
  65556. this.translateFromPivot = false;
  65557. /**
  65558. * Is the particle active or not ?
  65559. */
  65560. this.alive = true;
  65561. /**
  65562. * Is the particle visible or not ?
  65563. */
  65564. this.isVisible = true;
  65565. /**
  65566. * Index of this particle in the global "positions" array (Internal use)
  65567. * @hidden
  65568. */
  65569. this._pos = 0;
  65570. /**
  65571. * @hidden Index of this particle in the global "indices" array (Internal use)
  65572. */
  65573. this._ind = 0;
  65574. /**
  65575. * ModelShape id of this particle
  65576. */
  65577. this.shapeId = 0;
  65578. /**
  65579. * Index of the particle in its shape id (Internal use)
  65580. */
  65581. this.idxInShape = 0;
  65582. /**
  65583. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  65584. */
  65585. this._stillInvisible = false;
  65586. /**
  65587. * @hidden Last computed particle rotation matrix
  65588. */
  65589. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  65590. /**
  65591. * Parent particle Id, if any.
  65592. * Default null.
  65593. */
  65594. this.parentId = null;
  65595. /**
  65596. * @hidden Internal global position in the SPS.
  65597. */
  65598. this._globalPosition = BABYLON.Vector3.Zero();
  65599. this.idx = particleIndex;
  65600. this._pos = positionIndex;
  65601. this._ind = indiceIndex;
  65602. this._model = model;
  65603. this.shapeId = shapeId;
  65604. this.idxInShape = idxInShape;
  65605. this._sps = sps;
  65606. if (modelBoundingInfo) {
  65607. this._modelBoundingInfo = modelBoundingInfo;
  65608. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  65609. }
  65610. }
  65611. Object.defineProperty(SolidParticle.prototype, "scale", {
  65612. /**
  65613. * Legacy support, changed scale to scaling
  65614. */
  65615. get: function () {
  65616. return this.scaling;
  65617. },
  65618. /**
  65619. * Legacy support, changed scale to scaling
  65620. */
  65621. set: function (scale) {
  65622. this.scaling = scale;
  65623. },
  65624. enumerable: true,
  65625. configurable: true
  65626. });
  65627. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  65628. /**
  65629. * Legacy support, changed quaternion to rotationQuaternion
  65630. */
  65631. get: function () {
  65632. return this.rotationQuaternion;
  65633. },
  65634. /**
  65635. * Legacy support, changed quaternion to rotationQuaternion
  65636. */
  65637. set: function (q) {
  65638. this.rotationQuaternion = q;
  65639. },
  65640. enumerable: true,
  65641. configurable: true
  65642. });
  65643. /**
  65644. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  65645. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  65646. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  65647. * @returns true if it intersects
  65648. */
  65649. SolidParticle.prototype.intersectsMesh = function (target) {
  65650. if (!this._boundingInfo || !target._boundingInfo) {
  65651. return false;
  65652. }
  65653. if (this._sps._bSphereOnly) {
  65654. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  65655. }
  65656. return this._boundingInfo.intersects(target._boundingInfo, false);
  65657. };
  65658. return SolidParticle;
  65659. }());
  65660. BABYLON.SolidParticle = SolidParticle;
  65661. /**
  65662. * Represents the shape of the model used by one particle of a solid particle system.
  65663. * SPS internal tool, don't use it manually.
  65664. */
  65665. var ModelShape = /** @class */ (function () {
  65666. /**
  65667. * 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.
  65668. * SPS internal tool, don't use it manually.
  65669. * @hidden
  65670. */
  65671. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  65672. /**
  65673. * length of the shape in the model indices array (internal use)
  65674. * @hidden
  65675. */
  65676. this._indicesLength = 0;
  65677. this.shapeID = id;
  65678. this._shape = shape;
  65679. this._indicesLength = indicesLength;
  65680. this._shapeUV = shapeUV;
  65681. this._positionFunction = posFunction;
  65682. this._vertexFunction = vtxFunction;
  65683. }
  65684. return ModelShape;
  65685. }());
  65686. BABYLON.ModelShape = ModelShape;
  65687. /**
  65688. * Represents a Depth Sorted Particle in the solid particle system.
  65689. */
  65690. var DepthSortedParticle = /** @class */ (function () {
  65691. function DepthSortedParticle() {
  65692. /**
  65693. * Index of the particle in the "indices" array
  65694. */
  65695. this.ind = 0;
  65696. /**
  65697. * Length of the particle shape in the "indices" array
  65698. */
  65699. this.indicesLength = 0;
  65700. /**
  65701. * Squared distance from the particle to the camera
  65702. */
  65703. this.sqDistance = 0.0;
  65704. }
  65705. return DepthSortedParticle;
  65706. }());
  65707. BABYLON.DepthSortedParticle = DepthSortedParticle;
  65708. })(BABYLON || (BABYLON = {}));
  65709. //# sourceMappingURL=babylon.solidParticle.js.map
  65710. var BABYLON;
  65711. (function (BABYLON) {
  65712. /**
  65713. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  65714. *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.
  65715. * The SPS is also a particle system. It provides some methods to manage the particles.
  65716. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  65717. *
  65718. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  65719. */
  65720. var SolidParticleSystem = /** @class */ (function () {
  65721. /**
  65722. * Creates a SPS (Solid Particle System) object.
  65723. * @param name (String) is the SPS name, this will be the underlying mesh name.
  65724. * @param scene (Scene) is the scene in which the SPS is added.
  65725. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  65726. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  65727. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  65728. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  65729. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  65730. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  65731. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  65732. */
  65733. function SolidParticleSystem(name, scene, options) {
  65734. /**
  65735. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  65736. * Example : var p = SPS.particles[i];
  65737. */
  65738. this.particles = new Array();
  65739. /**
  65740. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  65741. */
  65742. this.nbParticles = 0;
  65743. /**
  65744. * If the particles must ever face the camera (default false). Useful for planar particles.
  65745. */
  65746. this.billboard = false;
  65747. /**
  65748. * Recompute normals when adding a shape
  65749. */
  65750. this.recomputeNormals = true;
  65751. /**
  65752. * This a counter ofr your own usage. It's not set by any SPS functions.
  65753. */
  65754. this.counter = 0;
  65755. /**
  65756. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  65757. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  65758. */
  65759. this.vars = {};
  65760. /**
  65761. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  65762. * @hidden
  65763. */
  65764. this._bSphereOnly = false;
  65765. /**
  65766. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  65767. * @hidden
  65768. */
  65769. this._bSphereRadiusFactor = 1.0;
  65770. this._positions = new Array();
  65771. this._indices = new Array();
  65772. this._normals = new Array();
  65773. this._colors = new Array();
  65774. this._uvs = new Array();
  65775. this._index = 0; // indices index
  65776. this._updatable = true;
  65777. this._pickable = false;
  65778. this._isVisibilityBoxLocked = false;
  65779. this._alwaysVisible = false;
  65780. this._depthSort = false;
  65781. this._shapeCounter = 0;
  65782. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  65783. this._color = new BABYLON.Color4(0, 0, 0, 0);
  65784. this._computeParticleColor = true;
  65785. this._computeParticleTexture = true;
  65786. this._computeParticleRotation = true;
  65787. this._computeParticleVertex = false;
  65788. this._computeBoundingBox = false;
  65789. this._depthSortParticles = true;
  65790. this._cam_axisZ = BABYLON.Vector3.Zero();
  65791. this._cam_axisY = BABYLON.Vector3.Zero();
  65792. this._cam_axisX = BABYLON.Vector3.Zero();
  65793. this._axisZ = BABYLON.Axis.Z;
  65794. this._camDir = BABYLON.Vector3.Zero();
  65795. this._camInvertedPosition = BABYLON.Vector3.Zero();
  65796. this._rotMatrix = new BABYLON.Matrix();
  65797. this._invertMatrix = new BABYLON.Matrix();
  65798. this._rotated = BABYLON.Vector3.Zero();
  65799. this._quaternion = new BABYLON.Quaternion();
  65800. this._vertex = BABYLON.Vector3.Zero();
  65801. this._normal = BABYLON.Vector3.Zero();
  65802. this._yaw = 0.0;
  65803. this._pitch = 0.0;
  65804. this._roll = 0.0;
  65805. this._halfroll = 0.0;
  65806. this._halfpitch = 0.0;
  65807. this._halfyaw = 0.0;
  65808. this._sinRoll = 0.0;
  65809. this._cosRoll = 0.0;
  65810. this._sinPitch = 0.0;
  65811. this._cosPitch = 0.0;
  65812. this._sinYaw = 0.0;
  65813. this._cosYaw = 0.0;
  65814. this._mustUnrotateFixedNormals = false;
  65815. this._minimum = BABYLON.Vector3.Zero();
  65816. this._maximum = BABYLON.Vector3.Zero();
  65817. this._minBbox = BABYLON.Vector3.Zero();
  65818. this._maxBbox = BABYLON.Vector3.Zero();
  65819. this._particlesIntersect = false;
  65820. this._depthSortFunction = function (p1, p2) {
  65821. return (p2.sqDistance - p1.sqDistance);
  65822. };
  65823. this._needs32Bits = false;
  65824. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  65825. this._scaledPivot = BABYLON.Vector3.Zero();
  65826. this._particleHasParent = false;
  65827. this.name = name;
  65828. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  65829. this._camera = scene.activeCamera;
  65830. this._pickable = options ? options.isPickable : false;
  65831. this._depthSort = options ? options.enableDepthSort : false;
  65832. this._particlesIntersect = options ? options.particleIntersection : false;
  65833. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  65834. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  65835. if (options && options.updatable !== undefined) {
  65836. this._updatable = options.updatable;
  65837. }
  65838. else {
  65839. this._updatable = true;
  65840. }
  65841. if (this._pickable) {
  65842. this.pickedParticles = [];
  65843. }
  65844. if (this._depthSort) {
  65845. this.depthSortedParticles = [];
  65846. }
  65847. }
  65848. /**
  65849. * Builds the SPS underlying mesh. Returns a standard Mesh.
  65850. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  65851. * @returns the created mesh
  65852. */
  65853. SolidParticleSystem.prototype.buildMesh = function () {
  65854. if (this.nbParticles === 0) {
  65855. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  65856. this.addShape(triangle, 1);
  65857. triangle.dispose();
  65858. }
  65859. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  65860. this._positions32 = new Float32Array(this._positions);
  65861. this._uvs32 = new Float32Array(this._uvs);
  65862. this._colors32 = new Float32Array(this._colors);
  65863. if (this.recomputeNormals) {
  65864. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  65865. }
  65866. this._normals32 = new Float32Array(this._normals);
  65867. this._fixedNormal32 = new Float32Array(this._normals);
  65868. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  65869. this._unrotateFixedNormals();
  65870. }
  65871. var vertexData = new BABYLON.VertexData();
  65872. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  65873. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  65874. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  65875. if (this._uvs32.length > 0) {
  65876. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  65877. }
  65878. if (this._colors32.length > 0) {
  65879. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  65880. }
  65881. var mesh = new BABYLON.Mesh(this.name, this._scene);
  65882. vertexData.applyToMesh(mesh, this._updatable);
  65883. this.mesh = mesh;
  65884. this.mesh.isPickable = this._pickable;
  65885. // free memory
  65886. if (!this._depthSort) {
  65887. this._indices = null;
  65888. }
  65889. this._positions = null;
  65890. this._normals = null;
  65891. this._uvs = null;
  65892. this._colors = null;
  65893. if (!this._updatable) {
  65894. this.particles.length = 0;
  65895. }
  65896. return mesh;
  65897. };
  65898. /**
  65899. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  65900. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  65901. * Thus the particles generated from `digest()` have their property `position` set yet.
  65902. * @param mesh ( Mesh ) is the mesh to be digested
  65903. * @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
  65904. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  65905. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  65906. * @returns the current SPS
  65907. */
  65908. SolidParticleSystem.prototype.digest = function (mesh, options) {
  65909. var size = (options && options.facetNb) || 1;
  65910. var number = (options && options.number) || 0;
  65911. var delta = (options && options.delta) || 0;
  65912. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65913. var meshInd = mesh.getIndices();
  65914. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  65915. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  65916. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  65917. var f = 0; // facet counter
  65918. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  65919. // compute size from number
  65920. if (number) {
  65921. number = (number > totalFacets) ? totalFacets : number;
  65922. size = Math.round(totalFacets / number);
  65923. delta = 0;
  65924. }
  65925. else {
  65926. size = (size > totalFacets) ? totalFacets : size;
  65927. }
  65928. var facetPos = []; // submesh positions
  65929. var facetInd = []; // submesh indices
  65930. var facetUV = []; // submesh UV
  65931. var facetCol = []; // submesh colors
  65932. var barycenter = BABYLON.Vector3.Zero();
  65933. var sizeO = size;
  65934. while (f < totalFacets) {
  65935. size = sizeO + Math.floor((1 + delta) * Math.random());
  65936. if (f > totalFacets - size) {
  65937. size = totalFacets - f;
  65938. }
  65939. // reset temp arrays
  65940. facetPos.length = 0;
  65941. facetInd.length = 0;
  65942. facetUV.length = 0;
  65943. facetCol.length = 0;
  65944. // iterate over "size" facets
  65945. var fi = 0;
  65946. for (var j = f * 3; j < (f + size) * 3; j++) {
  65947. facetInd.push(fi);
  65948. var i = meshInd[j];
  65949. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  65950. if (meshUV) {
  65951. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  65952. }
  65953. if (meshCol) {
  65954. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  65955. }
  65956. fi++;
  65957. }
  65958. // create a model shape for each single particle
  65959. var idx = this.nbParticles;
  65960. var shape = this._posToShape(facetPos);
  65961. var shapeUV = this._uvsToShapeUV(facetUV);
  65962. // compute the barycenter of the shape
  65963. var v;
  65964. for (v = 0; v < shape.length; v++) {
  65965. barycenter.addInPlace(shape[v]);
  65966. }
  65967. barycenter.scaleInPlace(1 / shape.length);
  65968. // shift the shape from its barycenter to the origin
  65969. for (v = 0; v < shape.length; v++) {
  65970. shape[v].subtractInPlace(barycenter);
  65971. }
  65972. var bInfo;
  65973. if (this._particlesIntersect) {
  65974. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  65975. }
  65976. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  65977. // add the particle in the SPS
  65978. var currentPos = this._positions.length;
  65979. var currentInd = this._indices.length;
  65980. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  65981. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  65982. // initialize the particle position
  65983. this.particles[this.nbParticles].position.addInPlace(barycenter);
  65984. this._index += shape.length;
  65985. idx++;
  65986. this.nbParticles++;
  65987. this._shapeCounter++;
  65988. f += size;
  65989. }
  65990. return this;
  65991. };
  65992. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  65993. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  65994. var index = 0;
  65995. var idx = 0;
  65996. for (var p = 0; p < this.particles.length; p++) {
  65997. this._particle = this.particles[p];
  65998. this._shape = this._particle._model._shape;
  65999. if (this._particle.rotationQuaternion) {
  66000. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  66001. }
  66002. else {
  66003. this._yaw = this._particle.rotation.y;
  66004. this._pitch = this._particle.rotation.x;
  66005. this._roll = this._particle.rotation.z;
  66006. this._quaternionRotationYPR();
  66007. }
  66008. this._quaternionToRotationMatrix();
  66009. this._rotMatrix.invertToRef(this._invertMatrix);
  66010. for (var pt = 0; pt < this._shape.length; pt++) {
  66011. idx = index + pt * 3;
  66012. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  66013. this._fixedNormal32[idx] = this._normal.x;
  66014. this._fixedNormal32[idx + 1] = this._normal.y;
  66015. this._fixedNormal32[idx + 2] = this._normal.z;
  66016. }
  66017. index = idx + 3;
  66018. }
  66019. };
  66020. //reset copy
  66021. SolidParticleSystem.prototype._resetCopy = function () {
  66022. this._copy.position.x = 0;
  66023. this._copy.position.y = 0;
  66024. this._copy.position.z = 0;
  66025. this._copy.rotation.x = 0;
  66026. this._copy.rotation.y = 0;
  66027. this._copy.rotation.z = 0;
  66028. this._copy.rotationQuaternion = null;
  66029. this._copy.scaling.x = 1.0;
  66030. this._copy.scaling.y = 1.0;
  66031. this._copy.scaling.z = 1.0;
  66032. this._copy.uvs.x = 0;
  66033. this._copy.uvs.y = 0;
  66034. this._copy.uvs.z = 1.0;
  66035. this._copy.uvs.w = 1.0;
  66036. this._copy.color = null;
  66037. this._copy.translateFromPivot = false;
  66038. };
  66039. // _meshBuilder : inserts the shape model in the global SPS mesh
  66040. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  66041. var i;
  66042. var u = 0;
  66043. var c = 0;
  66044. var n = 0;
  66045. this._resetCopy();
  66046. if (options && options.positionFunction) { // call to custom positionFunction
  66047. options.positionFunction(this._copy, idx, idxInShape);
  66048. this._mustUnrotateFixedNormals = true;
  66049. }
  66050. if (this._copy.rotationQuaternion) {
  66051. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  66052. }
  66053. else {
  66054. this._yaw = this._copy.rotation.y;
  66055. this._pitch = this._copy.rotation.x;
  66056. this._roll = this._copy.rotation.z;
  66057. this._quaternionRotationYPR();
  66058. }
  66059. this._quaternionToRotationMatrix();
  66060. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  66061. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  66062. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  66063. if (this._copy.translateFromPivot) {
  66064. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  66065. }
  66066. else {
  66067. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  66068. }
  66069. for (i = 0; i < shape.length; i++) {
  66070. this._vertex.x = shape[i].x;
  66071. this._vertex.y = shape[i].y;
  66072. this._vertex.z = shape[i].z;
  66073. if (options && options.vertexFunction) {
  66074. options.vertexFunction(this._copy, this._vertex, i);
  66075. }
  66076. this._vertex.x *= this._copy.scaling.x;
  66077. this._vertex.y *= this._copy.scaling.y;
  66078. this._vertex.z *= this._copy.scaling.z;
  66079. this._vertex.x -= this._scaledPivot.x;
  66080. this._vertex.y -= this._scaledPivot.y;
  66081. this._vertex.z -= this._scaledPivot.z;
  66082. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  66083. this._rotated.addInPlace(this._pivotBackTranslation);
  66084. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  66085. if (meshUV) {
  66086. 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);
  66087. u += 2;
  66088. }
  66089. if (this._copy.color) {
  66090. this._color = this._copy.color;
  66091. }
  66092. else if (meshCol && meshCol[c] !== undefined) {
  66093. this._color.r = meshCol[c];
  66094. this._color.g = meshCol[c + 1];
  66095. this._color.b = meshCol[c + 2];
  66096. this._color.a = meshCol[c + 3];
  66097. }
  66098. else {
  66099. this._color.r = 1.0;
  66100. this._color.g = 1.0;
  66101. this._color.b = 1.0;
  66102. this._color.a = 1.0;
  66103. }
  66104. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  66105. c += 4;
  66106. if (!this.recomputeNormals && meshNor) {
  66107. this._normal.x = meshNor[n];
  66108. this._normal.y = meshNor[n + 1];
  66109. this._normal.z = meshNor[n + 2];
  66110. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  66111. normals.push(this._normal.x, this._normal.y, this._normal.z);
  66112. n += 3;
  66113. }
  66114. }
  66115. for (i = 0; i < meshInd.length; i++) {
  66116. var current_ind = p + meshInd[i];
  66117. indices.push(current_ind);
  66118. if (current_ind > 65535) {
  66119. this._needs32Bits = true;
  66120. }
  66121. }
  66122. if (this._pickable) {
  66123. var nbfaces = meshInd.length / 3;
  66124. for (i = 0; i < nbfaces; i++) {
  66125. this.pickedParticles.push({ idx: idx, faceId: i });
  66126. }
  66127. }
  66128. if (this._depthSort) {
  66129. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  66130. }
  66131. return this._copy;
  66132. };
  66133. // returns a shape array from positions array
  66134. SolidParticleSystem.prototype._posToShape = function (positions) {
  66135. var shape = [];
  66136. for (var i = 0; i < positions.length; i += 3) {
  66137. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  66138. }
  66139. return shape;
  66140. };
  66141. // returns a shapeUV array from a Vector4 uvs
  66142. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  66143. var shapeUV = [];
  66144. if (uvs) {
  66145. for (var i = 0; i < uvs.length; i++)
  66146. shapeUV.push(uvs[i]);
  66147. }
  66148. return shapeUV;
  66149. };
  66150. // adds a new particle object in the particles array
  66151. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  66152. if (bInfo === void 0) { bInfo = null; }
  66153. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  66154. this.particles.push(sp);
  66155. return sp;
  66156. };
  66157. /**
  66158. * Adds some particles to the SPS from the model shape. Returns the shape id.
  66159. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  66160. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  66161. * @param nb (positive integer) the number of particles to be created from this model
  66162. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  66163. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  66164. * @returns the number of shapes in the system
  66165. */
  66166. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  66167. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66168. var meshInd = mesh.getIndices();
  66169. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  66170. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  66171. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  66172. var bbInfo;
  66173. if (this._particlesIntersect) {
  66174. bbInfo = mesh.getBoundingInfo();
  66175. }
  66176. var shape = this._posToShape(meshPos);
  66177. var shapeUV = this._uvsToShapeUV(meshUV);
  66178. var posfunc = options ? options.positionFunction : null;
  66179. var vtxfunc = options ? options.vertexFunction : null;
  66180. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  66181. // particles
  66182. var sp;
  66183. var currentCopy;
  66184. var idx = this.nbParticles;
  66185. for (var i = 0; i < nb; i++) {
  66186. var currentPos = this._positions.length;
  66187. var currentInd = this._indices.length;
  66188. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  66189. if (this._updatable) {
  66190. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  66191. sp.position.copyFrom(currentCopy.position);
  66192. sp.rotation.copyFrom(currentCopy.rotation);
  66193. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  66194. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  66195. }
  66196. if (currentCopy.color && sp.color) {
  66197. sp.color.copyFrom(currentCopy.color);
  66198. }
  66199. sp.scaling.copyFrom(currentCopy.scaling);
  66200. sp.uvs.copyFrom(currentCopy.uvs);
  66201. }
  66202. this._index += shape.length;
  66203. idx++;
  66204. }
  66205. this.nbParticles += nb;
  66206. this._shapeCounter++;
  66207. return this._shapeCounter - 1;
  66208. };
  66209. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  66210. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  66211. this._resetCopy();
  66212. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  66213. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  66214. }
  66215. if (this._copy.rotationQuaternion) {
  66216. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  66217. }
  66218. else {
  66219. this._yaw = this._copy.rotation.y;
  66220. this._pitch = this._copy.rotation.x;
  66221. this._roll = this._copy.rotation.z;
  66222. this._quaternionRotationYPR();
  66223. }
  66224. this._quaternionToRotationMatrix();
  66225. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  66226. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  66227. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  66228. if (this._copy.translateFromPivot) {
  66229. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  66230. }
  66231. else {
  66232. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  66233. }
  66234. this._shape = particle._model._shape;
  66235. for (var pt = 0; pt < this._shape.length; pt++) {
  66236. this._vertex.x = this._shape[pt].x;
  66237. this._vertex.y = this._shape[pt].y;
  66238. this._vertex.z = this._shape[pt].z;
  66239. if (particle._model._vertexFunction) {
  66240. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  66241. }
  66242. this._vertex.x *= this._copy.scaling.x;
  66243. this._vertex.y *= this._copy.scaling.y;
  66244. this._vertex.z *= this._copy.scaling.z;
  66245. this._vertex.x -= this._scaledPivot.x;
  66246. this._vertex.y -= this._scaledPivot.y;
  66247. this._vertex.z -= this._scaledPivot.z;
  66248. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  66249. this._rotated.addInPlace(this._pivotBackTranslation);
  66250. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  66251. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  66252. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  66253. }
  66254. particle.position.x = 0.0;
  66255. particle.position.y = 0.0;
  66256. particle.position.z = 0.0;
  66257. particle.rotation.x = 0.0;
  66258. particle.rotation.y = 0.0;
  66259. particle.rotation.z = 0.0;
  66260. particle.rotationQuaternion = null;
  66261. particle.scaling.x = 1.0;
  66262. particle.scaling.y = 1.0;
  66263. particle.scaling.z = 1.0;
  66264. particle.uvs.x = 0.0;
  66265. particle.uvs.y = 0.0;
  66266. particle.uvs.z = 1.0;
  66267. particle.uvs.w = 1.0;
  66268. particle.pivot.x = 0.0;
  66269. particle.pivot.y = 0.0;
  66270. particle.pivot.z = 0.0;
  66271. particle.translateFromPivot = false;
  66272. particle.parentId = null;
  66273. };
  66274. /**
  66275. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  66276. * @returns the SPS.
  66277. */
  66278. SolidParticleSystem.prototype.rebuildMesh = function () {
  66279. for (var p = 0; p < this.particles.length; p++) {
  66280. this._rebuildParticle(this.particles[p]);
  66281. }
  66282. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  66283. return this;
  66284. };
  66285. /**
  66286. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  66287. * This method calls `updateParticle()` for each particle of the SPS.
  66288. * For an animated SPS, it is usually called within the render loop.
  66289. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  66290. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  66291. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  66292. * @returns the SPS.
  66293. */
  66294. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  66295. if (start === void 0) { start = 0; }
  66296. if (end === void 0) { end = this.nbParticles - 1; }
  66297. if (update === void 0) { update = true; }
  66298. if (!this._updatable) {
  66299. return this;
  66300. }
  66301. // custom beforeUpdate
  66302. this.beforeUpdateParticles(start, end, update);
  66303. this._cam_axisX.x = 1.0;
  66304. this._cam_axisX.y = 0.0;
  66305. this._cam_axisX.z = 0.0;
  66306. this._cam_axisY.x = 0.0;
  66307. this._cam_axisY.y = 1.0;
  66308. this._cam_axisY.z = 0.0;
  66309. this._cam_axisZ.x = 0.0;
  66310. this._cam_axisZ.y = 0.0;
  66311. this._cam_axisZ.z = 1.0;
  66312. // cases when the World Matrix is to be computed first
  66313. if (this.billboard || this._depthSort) {
  66314. this.mesh.computeWorldMatrix(true);
  66315. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  66316. }
  66317. // if the particles will always face the camera
  66318. if (this.billboard) {
  66319. // compute the camera position and un-rotate it by the current mesh rotation
  66320. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  66321. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  66322. this._cam_axisZ.normalize();
  66323. // same for camera up vector extracted from the cam view matrix
  66324. var view = this._camera.getViewMatrix(true);
  66325. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  66326. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  66327. this._cam_axisY.normalize();
  66328. this._cam_axisX.normalize();
  66329. }
  66330. // if depthSort, compute the camera global position in the mesh local system
  66331. if (this._depthSort) {
  66332. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  66333. }
  66334. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  66335. var idx = 0; // current position index in the global array positions32
  66336. var index = 0; // position start index in the global array positions32 of the current particle
  66337. var colidx = 0; // current color index in the global array colors32
  66338. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  66339. var uvidx = 0; // current uv index in the global array uvs32
  66340. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  66341. var pt = 0; // current index in the particle model shape
  66342. if (this.mesh.isFacetDataEnabled) {
  66343. this._computeBoundingBox = true;
  66344. }
  66345. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  66346. if (this._computeBoundingBox) {
  66347. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  66348. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  66349. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  66350. }
  66351. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  66352. if (this.mesh._boundingInfo) {
  66353. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  66354. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  66355. }
  66356. }
  66357. }
  66358. // particle loop
  66359. index = this.particles[start]._pos;
  66360. var vpos = (index / 3) | 0;
  66361. colorIndex = vpos * 4;
  66362. uvIndex = vpos * 2;
  66363. for (var p = start; p <= end; p++) {
  66364. this._particle = this.particles[p];
  66365. this._shape = this._particle._model._shape;
  66366. this._shapeUV = this._particle._model._shapeUV;
  66367. // call to custom user function to update the particle properties
  66368. this.updateParticle(this._particle);
  66369. // camera-particle distance for depth sorting
  66370. if (this._depthSort && this._depthSortParticles) {
  66371. var dsp = this.depthSortedParticles[p];
  66372. dsp.ind = this._particle._ind;
  66373. dsp.indicesLength = this._particle._model._indicesLength;
  66374. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  66375. }
  66376. // skip the computations for inactive or already invisible particles
  66377. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  66378. // increment indexes for the next particle
  66379. pt = this._shape.length;
  66380. index += pt * 3;
  66381. colorIndex += pt * 4;
  66382. uvIndex += pt * 2;
  66383. continue;
  66384. }
  66385. if (this._particle.isVisible) {
  66386. this._particle._stillInvisible = false; // un-mark permanent invisibility
  66387. this._particleHasParent = (this._particle.parentId !== null);
  66388. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  66389. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  66390. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  66391. // particle rotation matrix
  66392. if (this.billboard) {
  66393. this._particle.rotation.x = 0.0;
  66394. this._particle.rotation.y = 0.0;
  66395. }
  66396. if (this._computeParticleRotation || this.billboard) {
  66397. if (this._particle.rotationQuaternion) {
  66398. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  66399. }
  66400. else {
  66401. this._yaw = this._particle.rotation.y;
  66402. this._pitch = this._particle.rotation.x;
  66403. this._roll = this._particle.rotation.z;
  66404. this._quaternionRotationYPR();
  66405. }
  66406. this._quaternionToRotationMatrix();
  66407. }
  66408. if (this._particleHasParent) {
  66409. this._parent = this.particles[this._particle.parentId];
  66410. 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];
  66411. 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];
  66412. 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];
  66413. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  66414. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  66415. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  66416. if (this._computeParticleRotation || this.billboard) {
  66417. 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];
  66418. 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];
  66419. 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];
  66420. 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];
  66421. 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];
  66422. 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];
  66423. 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];
  66424. 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];
  66425. 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];
  66426. }
  66427. }
  66428. else {
  66429. this._particle._globalPosition.x = this._particle.position.x;
  66430. this._particle._globalPosition.y = this._particle.position.y;
  66431. this._particle._globalPosition.z = this._particle.position.z;
  66432. if (this._computeParticleRotation || this.billboard) {
  66433. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  66434. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  66435. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  66436. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  66437. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  66438. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  66439. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  66440. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  66441. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  66442. }
  66443. }
  66444. if (this._particle.translateFromPivot) {
  66445. this._pivotBackTranslation.x = 0.0;
  66446. this._pivotBackTranslation.y = 0.0;
  66447. this._pivotBackTranslation.z = 0.0;
  66448. }
  66449. else {
  66450. this._pivotBackTranslation.x = this._scaledPivot.x;
  66451. this._pivotBackTranslation.y = this._scaledPivot.y;
  66452. this._pivotBackTranslation.z = this._scaledPivot.z;
  66453. }
  66454. // particle vertex loop
  66455. for (pt = 0; pt < this._shape.length; pt++) {
  66456. idx = index + pt * 3;
  66457. colidx = colorIndex + pt * 4;
  66458. uvidx = uvIndex + pt * 2;
  66459. this._vertex.x = this._shape[pt].x;
  66460. this._vertex.y = this._shape[pt].y;
  66461. this._vertex.z = this._shape[pt].z;
  66462. if (this._computeParticleVertex) {
  66463. this.updateParticleVertex(this._particle, this._vertex, pt);
  66464. }
  66465. // positions
  66466. this._vertex.x *= this._particle.scaling.x;
  66467. this._vertex.y *= this._particle.scaling.y;
  66468. this._vertex.z *= this._particle.scaling.z;
  66469. this._vertex.x -= this._scaledPivot.x;
  66470. this._vertex.y -= this._scaledPivot.y;
  66471. this._vertex.z -= this._scaledPivot.z;
  66472. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  66473. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  66474. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  66475. this._rotated.x += this._pivotBackTranslation.x;
  66476. this._rotated.y += this._pivotBackTranslation.y;
  66477. this._rotated.z += this._pivotBackTranslation.z;
  66478. 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;
  66479. 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;
  66480. 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;
  66481. if (this._computeBoundingBox) {
  66482. if (this._positions32[idx] < this._minimum.x) {
  66483. this._minimum.x = this._positions32[idx];
  66484. }
  66485. if (this._positions32[idx] > this._maximum.x) {
  66486. this._maximum.x = this._positions32[idx];
  66487. }
  66488. if (this._positions32[idx + 1] < this._minimum.y) {
  66489. this._minimum.y = this._positions32[idx + 1];
  66490. }
  66491. if (this._positions32[idx + 1] > this._maximum.y) {
  66492. this._maximum.y = this._positions32[idx + 1];
  66493. }
  66494. if (this._positions32[idx + 2] < this._minimum.z) {
  66495. this._minimum.z = this._positions32[idx + 2];
  66496. }
  66497. if (this._positions32[idx + 2] > this._maximum.z) {
  66498. this._maximum.z = this._positions32[idx + 2];
  66499. }
  66500. }
  66501. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  66502. if (!this._computeParticleVertex) {
  66503. this._normal.x = this._fixedNormal32[idx];
  66504. this._normal.y = this._fixedNormal32[idx + 1];
  66505. this._normal.z = this._fixedNormal32[idx + 2];
  66506. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  66507. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  66508. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  66509. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  66510. 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;
  66511. 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;
  66512. }
  66513. if (this._computeParticleColor && this._particle.color) {
  66514. this._colors32[colidx] = this._particle.color.r;
  66515. this._colors32[colidx + 1] = this._particle.color.g;
  66516. this._colors32[colidx + 2] = this._particle.color.b;
  66517. this._colors32[colidx + 3] = this._particle.color.a;
  66518. }
  66519. if (this._computeParticleTexture) {
  66520. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  66521. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  66522. }
  66523. }
  66524. }
  66525. // particle just set invisible : scaled to zero and positioned at the origin
  66526. else {
  66527. this._particle._stillInvisible = true; // mark the particle as invisible
  66528. for (pt = 0; pt < this._shape.length; pt++) {
  66529. idx = index + pt * 3;
  66530. colidx = colorIndex + pt * 4;
  66531. uvidx = uvIndex + pt * 2;
  66532. this._positions32[idx] = 0.0;
  66533. this._positions32[idx + 1] = 0.0;
  66534. this._positions32[idx + 2] = 0.0;
  66535. this._normals32[idx] = 0.0;
  66536. this._normals32[idx + 1] = 0.0;
  66537. this._normals32[idx + 2] = 0.0;
  66538. if (this._computeParticleColor && this._particle.color) {
  66539. this._colors32[colidx] = this._particle.color.r;
  66540. this._colors32[colidx + 1] = this._particle.color.g;
  66541. this._colors32[colidx + 2] = this._particle.color.b;
  66542. this._colors32[colidx + 3] = this._particle.color.a;
  66543. }
  66544. if (this._computeParticleTexture) {
  66545. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  66546. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  66547. }
  66548. }
  66549. }
  66550. // if the particle intersections must be computed : update the bbInfo
  66551. if (this._particlesIntersect) {
  66552. var bInfo = this._particle._boundingInfo;
  66553. var bBox = bInfo.boundingBox;
  66554. var bSphere = bInfo.boundingSphere;
  66555. if (!this._bSphereOnly) {
  66556. // place, scale and rotate the particle bbox within the SPS local system, then update it
  66557. for (var b = 0; b < bBox.vectors.length; b++) {
  66558. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  66559. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  66560. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  66561. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  66562. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  66563. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  66564. 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;
  66565. 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;
  66566. 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;
  66567. }
  66568. bBox._update(this.mesh._worldMatrix);
  66569. }
  66570. // place and scale the particle bouding sphere in the SPS local system, then update it
  66571. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  66572. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  66573. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  66574. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  66575. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  66576. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  66577. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  66578. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  66579. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  66580. 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));
  66581. bSphere._update(this.mesh._worldMatrix);
  66582. }
  66583. // increment indexes for the next particle
  66584. index = idx + 3;
  66585. colorIndex = colidx + 4;
  66586. uvIndex = uvidx + 2;
  66587. }
  66588. // if the VBO must be updated
  66589. if (update) {
  66590. if (this._computeParticleColor) {
  66591. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  66592. }
  66593. if (this._computeParticleTexture) {
  66594. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  66595. }
  66596. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  66597. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  66598. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  66599. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  66600. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  66601. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  66602. for (var i = 0; i < this._normals32.length; i++) {
  66603. this._fixedNormal32[i] = this._normals32[i];
  66604. }
  66605. }
  66606. if (!this.mesh.areNormalsFrozen) {
  66607. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  66608. }
  66609. }
  66610. if (this._depthSort && this._depthSortParticles) {
  66611. this.depthSortedParticles.sort(this._depthSortFunction);
  66612. var dspl = this.depthSortedParticles.length;
  66613. var sorted = 0;
  66614. var lind = 0;
  66615. var sind = 0;
  66616. var sid = 0;
  66617. for (sorted = 0; sorted < dspl; sorted++) {
  66618. lind = this.depthSortedParticles[sorted].indicesLength;
  66619. sind = this.depthSortedParticles[sorted].ind;
  66620. for (var i = 0; i < lind; i++) {
  66621. this._indices32[sid] = this._indices[sind + i];
  66622. sid++;
  66623. }
  66624. }
  66625. this.mesh.updateIndices(this._indices32);
  66626. }
  66627. }
  66628. if (this._computeBoundingBox) {
  66629. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  66630. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  66631. }
  66632. this.afterUpdateParticles(start, end, update);
  66633. return this;
  66634. };
  66635. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  66636. this._halfroll = this._roll * 0.5;
  66637. this._halfpitch = this._pitch * 0.5;
  66638. this._halfyaw = this._yaw * 0.5;
  66639. this._sinRoll = Math.sin(this._halfroll);
  66640. this._cosRoll = Math.cos(this._halfroll);
  66641. this._sinPitch = Math.sin(this._halfpitch);
  66642. this._cosPitch = Math.cos(this._halfpitch);
  66643. this._sinYaw = Math.sin(this._halfyaw);
  66644. this._cosYaw = Math.cos(this._halfyaw);
  66645. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  66646. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  66647. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  66648. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  66649. };
  66650. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  66651. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  66652. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  66653. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  66654. this._rotMatrix.m[3] = 0;
  66655. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  66656. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  66657. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  66658. this._rotMatrix.m[7] = 0;
  66659. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  66660. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  66661. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  66662. this._rotMatrix.m[11] = 0;
  66663. this._rotMatrix.m[12] = 0;
  66664. this._rotMatrix.m[13] = 0;
  66665. this._rotMatrix.m[14] = 0;
  66666. this._rotMatrix.m[15] = 1.0;
  66667. };
  66668. /**
  66669. * Disposes the SPS.
  66670. */
  66671. SolidParticleSystem.prototype.dispose = function () {
  66672. this.mesh.dispose();
  66673. this.vars = null;
  66674. // drop references to internal big arrays for the GC
  66675. this._positions = null;
  66676. this._indices = null;
  66677. this._normals = null;
  66678. this._uvs = null;
  66679. this._colors = null;
  66680. this._indices32 = null;
  66681. this._positions32 = null;
  66682. this._normals32 = null;
  66683. this._fixedNormal32 = null;
  66684. this._uvs32 = null;
  66685. this._colors32 = null;
  66686. this.pickedParticles = null;
  66687. };
  66688. /**
  66689. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  66690. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66691. * @returns the SPS.
  66692. */
  66693. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  66694. if (!this._isVisibilityBoxLocked) {
  66695. this.mesh.refreshBoundingInfo();
  66696. }
  66697. return this;
  66698. };
  66699. /**
  66700. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  66701. * @param size the size (float) of the visibility box
  66702. * note : this doesn't lock the SPS mesh bounding box.
  66703. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66704. */
  66705. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  66706. var vis = size / 2;
  66707. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  66708. };
  66709. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  66710. /**
  66711. * Gets whether the SPS as always visible or not
  66712. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66713. */
  66714. get: function () {
  66715. return this._alwaysVisible;
  66716. },
  66717. /**
  66718. * Sets the SPS as always visible or not
  66719. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66720. */
  66721. set: function (val) {
  66722. this._alwaysVisible = val;
  66723. this.mesh.alwaysSelectAsActiveMesh = val;
  66724. },
  66725. enumerable: true,
  66726. configurable: true
  66727. });
  66728. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  66729. /**
  66730. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  66731. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66732. */
  66733. get: function () {
  66734. return this._isVisibilityBoxLocked;
  66735. },
  66736. /**
  66737. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  66738. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66739. */
  66740. set: function (val) {
  66741. this._isVisibilityBoxLocked = val;
  66742. var boundingInfo = this.mesh.getBoundingInfo();
  66743. boundingInfo.isLocked = val;
  66744. },
  66745. enumerable: true,
  66746. configurable: true
  66747. });
  66748. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  66749. /**
  66750. * Gets if `setParticles()` computes the particle rotations or not.
  66751. * Default value : true. The SPS is faster when it's set to false.
  66752. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  66753. */
  66754. get: function () {
  66755. return this._computeParticleRotation;
  66756. },
  66757. /**
  66758. * Tells to `setParticles()` to compute the particle rotations or not.
  66759. * Default value : true. The SPS is faster when it's set to false.
  66760. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  66761. */
  66762. set: function (val) {
  66763. this._computeParticleRotation = val;
  66764. },
  66765. enumerable: true,
  66766. configurable: true
  66767. });
  66768. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  66769. /**
  66770. * Gets if `setParticles()` computes the particle colors or not.
  66771. * Default value : true. The SPS is faster when it's set to false.
  66772. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  66773. */
  66774. get: function () {
  66775. return this._computeParticleColor;
  66776. },
  66777. /**
  66778. * Tells to `setParticles()` to compute the particle colors or not.
  66779. * Default value : true. The SPS is faster when it's set to false.
  66780. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  66781. */
  66782. set: function (val) {
  66783. this._computeParticleColor = val;
  66784. },
  66785. enumerable: true,
  66786. configurable: true
  66787. });
  66788. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  66789. /**
  66790. * Gets if `setParticles()` computes the particle textures or not.
  66791. * Default value : true. The SPS is faster when it's set to false.
  66792. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  66793. */
  66794. get: function () {
  66795. return this._computeParticleTexture;
  66796. },
  66797. set: function (val) {
  66798. this._computeParticleTexture = val;
  66799. },
  66800. enumerable: true,
  66801. configurable: true
  66802. });
  66803. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  66804. /**
  66805. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  66806. * Default value : false. The SPS is faster when it's set to false.
  66807. * Note : the particle custom vertex positions aren't stored values.
  66808. */
  66809. get: function () {
  66810. return this._computeParticleVertex;
  66811. },
  66812. /**
  66813. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  66814. * Default value : false. The SPS is faster when it's set to false.
  66815. * Note : the particle custom vertex positions aren't stored values.
  66816. */
  66817. set: function (val) {
  66818. this._computeParticleVertex = val;
  66819. },
  66820. enumerable: true,
  66821. configurable: true
  66822. });
  66823. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  66824. /**
  66825. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  66826. */
  66827. get: function () {
  66828. return this._computeBoundingBox;
  66829. },
  66830. /**
  66831. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  66832. */
  66833. set: function (val) {
  66834. this._computeBoundingBox = val;
  66835. },
  66836. enumerable: true,
  66837. configurable: true
  66838. });
  66839. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  66840. /**
  66841. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  66842. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  66843. * Default : `true`
  66844. */
  66845. get: function () {
  66846. return this._depthSortParticles;
  66847. },
  66848. /**
  66849. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  66850. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  66851. * Default : `true`
  66852. */
  66853. set: function (val) {
  66854. this._depthSortParticles = val;
  66855. },
  66856. enumerable: true,
  66857. configurable: true
  66858. });
  66859. // =======================================================================
  66860. // Particle behavior logic
  66861. // these following methods may be overwritten by the user to fit his needs
  66862. /**
  66863. * This function does nothing. It may be overwritten to set all the particle first values.
  66864. * The SPS doesn't call this function, you may have to call it by your own.
  66865. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  66866. */
  66867. SolidParticleSystem.prototype.initParticles = function () {
  66868. };
  66869. /**
  66870. * This function does nothing. It may be overwritten to recycle a particle.
  66871. * The SPS doesn't call this function, you may have to call it by your own.
  66872. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  66873. * @param particle The particle to recycle
  66874. * @returns the recycled particle
  66875. */
  66876. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  66877. return particle;
  66878. };
  66879. /**
  66880. * Updates a particle : this function should be overwritten by the user.
  66881. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  66882. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  66883. * @example : just set a particle position or velocity and recycle conditions
  66884. * @param particle The particle to update
  66885. * @returns the updated particle
  66886. */
  66887. SolidParticleSystem.prototype.updateParticle = function (particle) {
  66888. return particle;
  66889. };
  66890. /**
  66891. * Updates a vertex of a particle : it can be overwritten by the user.
  66892. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  66893. * @param particle the current particle
  66894. * @param vertex the current index of the current particle
  66895. * @param pt the index of the current vertex in the particle shape
  66896. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  66897. * @example : just set a vertex particle position
  66898. * @returns the updated vertex
  66899. */
  66900. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  66901. return vertex;
  66902. };
  66903. /**
  66904. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  66905. * This does nothing and may be overwritten by the user.
  66906. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  66907. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  66908. * @param update the boolean update value actually passed to setParticles()
  66909. */
  66910. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  66911. };
  66912. /**
  66913. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  66914. * This will be passed three parameters.
  66915. * This does nothing and may be overwritten by the user.
  66916. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  66917. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  66918. * @param update the boolean update value actually passed to setParticles()
  66919. */
  66920. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  66921. };
  66922. return SolidParticleSystem;
  66923. }());
  66924. BABYLON.SolidParticleSystem = SolidParticleSystem;
  66925. })(BABYLON || (BABYLON = {}));
  66926. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  66927. var BABYLON;
  66928. (function (BABYLON) {
  66929. /**
  66930. * Class containing static functions to help procedurally build meshes
  66931. */
  66932. var MeshBuilder = /** @class */ (function () {
  66933. function MeshBuilder() {
  66934. }
  66935. MeshBuilder.updateSideOrientation = function (orientation) {
  66936. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  66937. return BABYLON.Mesh.DOUBLESIDE;
  66938. }
  66939. if (orientation === undefined || orientation === null) {
  66940. return BABYLON.Mesh.FRONTSIDE;
  66941. }
  66942. return orientation;
  66943. };
  66944. /**
  66945. * Creates a box mesh
  66946. * * The parameter `size` sets the size (float) of each box side (default 1)
  66947. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value of `size`)
  66948. * * 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)
  66949. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  66950. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66951. * * 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
  66952. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66953. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  66954. * @param name defines the name of the mesh
  66955. * @param options defines the options used to create the mesh
  66956. * @param scene defines the hosting scene
  66957. * @returns the box mesh
  66958. */
  66959. MeshBuilder.CreateBox = function (name, options, scene) {
  66960. if (scene === void 0) { scene = null; }
  66961. var box = new BABYLON.Mesh(name, scene);
  66962. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66963. box._originalBuilderSideOrientation = options.sideOrientation;
  66964. var vertexData = BABYLON.VertexData.CreateBox(options);
  66965. vertexData.applyToMesh(box, options.updatable);
  66966. return box;
  66967. };
  66968. /**
  66969. * Creates a sphere mesh
  66970. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  66971. * * 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 of `diameter`)
  66972. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  66973. * * 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
  66974. * * 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)
  66975. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66976. * * 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
  66977. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66978. * @param name defines the name of the mesh
  66979. * @param options defines the options used to create the mesh
  66980. * @param scene defines the hosting scene
  66981. * @returns the sphere mesh
  66982. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  66983. */
  66984. MeshBuilder.CreateSphere = function (name, options, scene) {
  66985. var sphere = new BABYLON.Mesh(name, scene);
  66986. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66987. sphere._originalBuilderSideOrientation = options.sideOrientation;
  66988. var vertexData = BABYLON.VertexData.CreateSphere(options);
  66989. vertexData.applyToMesh(sphere, options.updatable);
  66990. return sphere;
  66991. };
  66992. /**
  66993. * Creates a plane polygonal mesh. By default, this is a disc
  66994. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  66995. * * 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
  66996. * * 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
  66997. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66998. * * 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
  66999. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67000. * @param name defines the name of the mesh
  67001. * @param options defines the options used to create the mesh
  67002. * @param scene defines the hosting scene
  67003. * @returns the plane polygonal mesh
  67004. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  67005. */
  67006. MeshBuilder.CreateDisc = function (name, options, scene) {
  67007. if (scene === void 0) { scene = null; }
  67008. var disc = new BABYLON.Mesh(name, scene);
  67009. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67010. disc._originalBuilderSideOrientation = options.sideOrientation;
  67011. var vertexData = BABYLON.VertexData.CreateDisc(options);
  67012. vertexData.applyToMesh(disc, options.updatable);
  67013. return disc;
  67014. };
  67015. /**
  67016. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  67017. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  67018. * * 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 of `radius`)
  67019. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  67020. * * 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
  67021. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67022. * * 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
  67023. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67024. * @param name defines the name of the mesh
  67025. * @param options defines the options used to create the mesh
  67026. * @param scene defines the hosting scene
  67027. * @returns the icosahedron mesh
  67028. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  67029. */
  67030. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  67031. var sphere = new BABYLON.Mesh(name, scene);
  67032. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67033. sphere._originalBuilderSideOrientation = options.sideOrientation;
  67034. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  67035. vertexData.applyToMesh(sphere, options.updatable);
  67036. return sphere;
  67037. };
  67038. ;
  67039. /**
  67040. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  67041. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  67042. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  67043. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  67044. * * 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
  67045. * * 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
  67046. * * 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
  67047. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67048. * * 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
  67049. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  67050. * * 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
  67051. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  67052. * * 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
  67053. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  67054. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67055. * @param name defines the name of the mesh
  67056. * @param options defines the options used to create the mesh
  67057. * @param scene defines the hosting scene
  67058. * @returns the ribbon mesh
  67059. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  67060. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  67061. */
  67062. MeshBuilder.CreateRibbon = function (name, options, scene) {
  67063. if (scene === void 0) { scene = null; }
  67064. var pathArray = options.pathArray;
  67065. var closeArray = options.closeArray;
  67066. var closePath = options.closePath;
  67067. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67068. var instance = options.instance;
  67069. var updatable = options.updatable;
  67070. if (instance) { // existing ribbon instance update
  67071. // positionFunction : ribbon case
  67072. // only pathArray and sideOrientation parameters are taken into account for positions update
  67073. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  67074. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  67075. var positionFunction = function (positions) {
  67076. var minlg = pathArray[0].length;
  67077. var mesh = instance;
  67078. var i = 0;
  67079. var ns = (mesh._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  67080. for (var si = 1; si <= ns; si++) {
  67081. for (var p = 0; p < pathArray.length; p++) {
  67082. var path = pathArray[p];
  67083. var l = path.length;
  67084. minlg = (minlg < l) ? minlg : l;
  67085. var j = 0;
  67086. while (j < minlg) {
  67087. positions[i] = path[j].x;
  67088. positions[i + 1] = path[j].y;
  67089. positions[i + 2] = path[j].z;
  67090. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  67091. BABYLON.Tmp.Vector3[0].x = path[j].x;
  67092. }
  67093. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  67094. BABYLON.Tmp.Vector3[1].x = path[j].x;
  67095. }
  67096. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  67097. BABYLON.Tmp.Vector3[0].y = path[j].y;
  67098. }
  67099. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  67100. BABYLON.Tmp.Vector3[1].y = path[j].y;
  67101. }
  67102. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  67103. BABYLON.Tmp.Vector3[0].z = path[j].z;
  67104. }
  67105. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  67106. BABYLON.Tmp.Vector3[1].z = path[j].z;
  67107. }
  67108. j++;
  67109. i += 3;
  67110. }
  67111. if (mesh._creationDataStorage && mesh._creationDataStorage.closePath) {
  67112. positions[i] = path[0].x;
  67113. positions[i + 1] = path[0].y;
  67114. positions[i + 2] = path[0].z;
  67115. i += 3;
  67116. }
  67117. }
  67118. }
  67119. };
  67120. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67121. positionFunction(positions);
  67122. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[2], BABYLON.Tmp.Vector3[3]);
  67123. instance._boundingInfo.update(instance._worldMatrix);
  67124. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  67125. if (options.colors) {
  67126. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  67127. for (var c = 0; c < options.colors.length; c++) {
  67128. colors[c * 4] = options.colors[c].r;
  67129. colors[c * 4 + 1] = options.colors[c].g;
  67130. colors[c * 4 + 2] = options.colors[c].b;
  67131. colors[c * 4 + 3] = options.colors[c].a;
  67132. }
  67133. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  67134. }
  67135. if (options.uvs) {
  67136. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  67137. for (var i = 0; i < options.uvs.length; i++) {
  67138. uvs[i * 2] = options.uvs[i].x;
  67139. uvs[i * 2 + 1] = options.uvs[i].y;
  67140. }
  67141. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  67142. }
  67143. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  67144. var indices = instance.getIndices();
  67145. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  67146. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  67147. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  67148. if (instance._creationDataStorage && instance._creationDataStorage.closePath) {
  67149. var indexFirst = 0;
  67150. var indexLast = 0;
  67151. for (var p = 0; p < pathArray.length; p++) {
  67152. indexFirst = instance._creationDataStorage.idx[p] * 3;
  67153. if (p + 1 < pathArray.length) {
  67154. indexLast = (instance._creationDataStorage.idx[p + 1] - 1) * 3;
  67155. }
  67156. else {
  67157. indexLast = normals.length - 3;
  67158. }
  67159. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  67160. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  67161. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  67162. normals[indexLast] = normals[indexFirst];
  67163. normals[indexLast + 1] = normals[indexFirst + 1];
  67164. normals[indexLast + 2] = normals[indexFirst + 2];
  67165. }
  67166. }
  67167. if (!(instance.areNormalsFrozen)) {
  67168. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  67169. }
  67170. }
  67171. return instance;
  67172. }
  67173. else { // new ribbon creation
  67174. var ribbon = new BABYLON.Mesh(name, scene);
  67175. ribbon._originalBuilderSideOrientation = sideOrientation;
  67176. ribbon._creationDataStorage = new BABYLON._CreationDataStorage();
  67177. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  67178. if (closePath) {
  67179. ribbon._creationDataStorage.idx = vertexData._idx;
  67180. }
  67181. ribbon._creationDataStorage.closePath = closePath;
  67182. ribbon._creationDataStorage.closeArray = closeArray;
  67183. vertexData.applyToMesh(ribbon, updatable);
  67184. return ribbon;
  67185. }
  67186. };
  67187. /**
  67188. * Creates a cylinder or a cone mesh
  67189. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  67190. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  67191. * * 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.
  67192. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  67193. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  67194. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  67195. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  67196. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  67197. * * 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).
  67198. * * 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
  67199. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  67200. * * 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
  67201. * * 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.
  67202. * * If `enclose` is false, a ring surface is one element.
  67203. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  67204. * * 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
  67205. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67206. * * 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
  67207. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67208. * @param name defines the name of the mesh
  67209. * @param options defines the options used to create the mesh
  67210. * @param scene defines the hosting scene
  67211. * @returns the cylinder mesh
  67212. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  67213. */
  67214. MeshBuilder.CreateCylinder = function (name, options, scene) {
  67215. var cylinder = new BABYLON.Mesh(name, scene);
  67216. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67217. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  67218. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  67219. vertexData.applyToMesh(cylinder, options.updatable);
  67220. return cylinder;
  67221. };
  67222. /**
  67223. * Creates a torus mesh
  67224. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  67225. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  67226. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  67227. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67228. * * 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
  67229. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67230. * @param name defines the name of the mesh
  67231. * @param options defines the options used to create the mesh
  67232. * @param scene defines the hosting scene
  67233. * @returns the torus mesh
  67234. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  67235. */
  67236. MeshBuilder.CreateTorus = function (name, options, scene) {
  67237. var torus = new BABYLON.Mesh(name, scene);
  67238. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67239. torus._originalBuilderSideOrientation = options.sideOrientation;
  67240. var vertexData = BABYLON.VertexData.CreateTorus(options);
  67241. vertexData.applyToMesh(torus, options.updatable);
  67242. return torus;
  67243. };
  67244. /**
  67245. * Creates a torus knot mesh
  67246. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  67247. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  67248. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  67249. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  67250. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67251. * * 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
  67252. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67253. * @param name defines the name of the mesh
  67254. * @param options defines the options used to create the mesh
  67255. * @param scene defines the hosting scene
  67256. * @returns the torus knot mesh
  67257. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  67258. */
  67259. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  67260. var torusKnot = new BABYLON.Mesh(name, scene);
  67261. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67262. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  67263. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  67264. vertexData.applyToMesh(torusKnot, options.updatable);
  67265. return torusKnot;
  67266. };
  67267. /**
  67268. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  67269. * * 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
  67270. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  67271. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  67272. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  67273. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  67274. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  67275. * * 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
  67276. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  67277. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67278. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  67279. * @param name defines the name of the new line system
  67280. * @param options defines the options used to create the line system
  67281. * @param scene defines the hosting scene
  67282. * @returns a new line system mesh
  67283. */
  67284. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  67285. var instance = options.instance;
  67286. var lines = options.lines;
  67287. var colors = options.colors;
  67288. if (instance) { // lines update
  67289. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67290. var vertexColor;
  67291. var lineColors;
  67292. if (colors) {
  67293. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  67294. }
  67295. var i = 0;
  67296. var c = 0;
  67297. for (var l = 0; l < lines.length; l++) {
  67298. var points = lines[l];
  67299. for (var p = 0; p < points.length; p++) {
  67300. positions[i] = points[p].x;
  67301. positions[i + 1] = points[p].y;
  67302. positions[i + 2] = points[p].z;
  67303. if (colors && vertexColor) {
  67304. lineColors = colors[l];
  67305. vertexColor[c] = lineColors[p].r;
  67306. vertexColor[c + 1] = lineColors[p].g;
  67307. vertexColor[c + 2] = lineColors[p].b;
  67308. vertexColor[c + 3] = lineColors[p].a;
  67309. c += 4;
  67310. }
  67311. i += 3;
  67312. }
  67313. }
  67314. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  67315. if (colors && vertexColor) {
  67316. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  67317. }
  67318. return instance;
  67319. }
  67320. // line system creation
  67321. var useVertexColor = (colors) ? true : false;
  67322. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  67323. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  67324. vertexData.applyToMesh(lineSystem, options.updatable);
  67325. return lineSystem;
  67326. };
  67327. /**
  67328. * Creates a line mesh
  67329. * 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
  67330. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  67331. * * The parameter `points` is an array successive Vector3
  67332. * * 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
  67333. * * The optional parameter `colors` is an array of successive Color4, one per line point
  67334. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  67335. * * When updating an instance, remember that only point positions can change, not the number of points
  67336. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67337. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  67338. * @param name defines the name of the new line system
  67339. * @param options defines the options used to create the line system
  67340. * @param scene defines the hosting scene
  67341. * @returns a new line mesh
  67342. */
  67343. MeshBuilder.CreateLines = function (name, options, scene) {
  67344. if (scene === void 0) { scene = null; }
  67345. var colors = (options.colors) ? [options.colors] : null;
  67346. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  67347. return lines;
  67348. };
  67349. /**
  67350. * Creates a dashed line mesh
  67351. * * 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
  67352. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  67353. * * The parameter `points` is an array successive Vector3
  67354. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  67355. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  67356. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  67357. * * 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
  67358. * * When updating an instance, remember that only point positions can change, not the number of points
  67359. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67360. * @param name defines the name of the mesh
  67361. * @param options defines the options used to create the mesh
  67362. * @param scene defines the hosting scene
  67363. * @returns the dashed line mesh
  67364. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  67365. */
  67366. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  67367. if (scene === void 0) { scene = null; }
  67368. var points = options.points;
  67369. var instance = options.instance;
  67370. var gapSize = options.gapSize || 1;
  67371. var dashSize = options.dashSize || 3;
  67372. if (instance) { // dashed lines update
  67373. var positionFunction = function (positions) {
  67374. var curvect = BABYLON.Vector3.Zero();
  67375. var nbSeg = positions.length / 6;
  67376. var lg = 0;
  67377. var nb = 0;
  67378. var shft = 0;
  67379. var dashshft = 0;
  67380. var curshft = 0;
  67381. var p = 0;
  67382. var i = 0;
  67383. var j = 0;
  67384. for (i = 0; i < points.length - 1; i++) {
  67385. points[i + 1].subtractToRef(points[i], curvect);
  67386. lg += curvect.length();
  67387. }
  67388. shft = lg / nbSeg;
  67389. var dashSize = instance._creationDataStorage.dashSize;
  67390. var gapSize = instance._creationDataStorage.gapSize;
  67391. dashshft = dashSize * shft / (dashSize + gapSize);
  67392. for (i = 0; i < points.length - 1; i++) {
  67393. points[i + 1].subtractToRef(points[i], curvect);
  67394. nb = Math.floor(curvect.length() / shft);
  67395. curvect.normalize();
  67396. j = 0;
  67397. while (j < nb && p < positions.length) {
  67398. curshft = shft * j;
  67399. positions[p] = points[i].x + curshft * curvect.x;
  67400. positions[p + 1] = points[i].y + curshft * curvect.y;
  67401. positions[p + 2] = points[i].z + curshft * curvect.z;
  67402. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  67403. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  67404. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  67405. p += 6;
  67406. j++;
  67407. }
  67408. }
  67409. while (p < positions.length) {
  67410. positions[p] = points[i].x;
  67411. positions[p + 1] = points[i].y;
  67412. positions[p + 2] = points[i].z;
  67413. p += 3;
  67414. }
  67415. };
  67416. instance.updateMeshPositions(positionFunction, false);
  67417. return instance;
  67418. }
  67419. // dashed lines creation
  67420. var dashedLines = new BABYLON.LinesMesh(name, scene);
  67421. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  67422. vertexData.applyToMesh(dashedLines, options.updatable);
  67423. dashedLines._creationDataStorage = new BABYLON._CreationDataStorage();
  67424. dashedLines._creationDataStorage.dashSize = dashSize;
  67425. dashedLines._creationDataStorage.gapSize = gapSize;
  67426. return dashedLines;
  67427. };
  67428. /**
  67429. * 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.
  67430. * * 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.
  67431. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  67432. * * 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.
  67433. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  67434. * * 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
  67435. * * 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
  67436. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  67437. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67438. * * 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
  67439. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  67440. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67441. * @param name defines the name of the mesh
  67442. * @param options defines the options used to create the mesh
  67443. * @param scene defines the hosting scene
  67444. * @returns the extruded shape mesh
  67445. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  67446. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  67447. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  67448. */
  67449. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  67450. if (scene === void 0) { scene = null; }
  67451. var path = options.path;
  67452. var shape = options.shape;
  67453. var scale = options.scale || 1;
  67454. var rotation = options.rotation || 0;
  67455. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  67456. var updatable = options.updatable;
  67457. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67458. var instance = options.instance || null;
  67459. var invertUV = options.invertUV || false;
  67460. 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);
  67461. };
  67462. /**
  67463. * Creates an custom extruded shape mesh.
  67464. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  67465. * * 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.
  67466. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  67467. * * 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
  67468. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  67469. * * 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
  67470. * * It must returns a float value that will be the scale value applied to the shape on each path point
  67471. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  67472. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  67473. * * 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
  67474. * * 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
  67475. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  67476. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67477. * * 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
  67478. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  67479. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67480. * @param name defines the name of the mesh
  67481. * @param options defines the options used to create the mesh
  67482. * @param scene defines the hosting scene
  67483. * @returns the custom extruded shape mesh
  67484. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  67485. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  67486. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  67487. */
  67488. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  67489. var path = options.path;
  67490. var shape = options.shape;
  67491. var scaleFunction = options.scaleFunction || (function () { return 1; });
  67492. var rotationFunction = options.rotationFunction || (function () { return 0; });
  67493. var ribbonCloseArray = options.ribbonCloseArray || false;
  67494. var ribbonClosePath = options.ribbonClosePath || false;
  67495. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  67496. var updatable = options.updatable;
  67497. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67498. var instance = options.instance;
  67499. var invertUV = options.invertUV || false;
  67500. 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);
  67501. };
  67502. /**
  67503. * Creates lathe mesh.
  67504. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  67505. * * 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
  67506. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  67507. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  67508. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  67509. * * 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
  67510. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  67511. * * 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
  67512. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67513. * * 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
  67514. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  67515. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67516. * @param name defines the name of the mesh
  67517. * @param options defines the options used to create the mesh
  67518. * @param scene defines the hosting scene
  67519. * @returns the lathe mesh
  67520. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  67521. */
  67522. MeshBuilder.CreateLathe = function (name, options, scene) {
  67523. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  67524. var closed = (options.closed === undefined) ? true : options.closed;
  67525. var shape = options.shape;
  67526. var radius = options.radius || 1;
  67527. var tessellation = options.tessellation || 64;
  67528. var clip = options.clip || 0;
  67529. var updatable = options.updatable;
  67530. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67531. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  67532. var pi2 = Math.PI * 2;
  67533. var paths = new Array();
  67534. var invertUV = options.invertUV || false;
  67535. var i = 0;
  67536. var p = 0;
  67537. var step = pi2 / tessellation * arc;
  67538. var rotated;
  67539. var path = new Array();
  67540. for (i = 0; i <= tessellation - clip; i++) {
  67541. var path = [];
  67542. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  67543. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  67544. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  67545. }
  67546. for (p = 0; p < shape.length; p++) {
  67547. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  67548. path.push(rotated);
  67549. }
  67550. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  67551. 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));
  67552. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  67553. }
  67554. paths.push(path);
  67555. }
  67556. // lathe ribbon
  67557. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  67558. return lathe;
  67559. };
  67560. /**
  67561. * Creates a plane mesh
  67562. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  67563. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value of `size`)
  67564. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  67565. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67566. * * 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
  67567. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67568. * @param name defines the name of the mesh
  67569. * @param options defines the options used to create the mesh
  67570. * @param scene defines the hosting scene
  67571. * @returns the plane mesh
  67572. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  67573. */
  67574. MeshBuilder.CreatePlane = function (name, options, scene) {
  67575. var plane = new BABYLON.Mesh(name, scene);
  67576. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67577. plane._originalBuilderSideOrientation = options.sideOrientation;
  67578. var vertexData = BABYLON.VertexData.CreatePlane(options);
  67579. vertexData.applyToMesh(plane, options.updatable);
  67580. if (options.sourcePlane) {
  67581. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  67582. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  67583. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  67584. if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
  67585. plane.rotate(vectorProduct, product);
  67586. }
  67587. }
  67588. return plane;
  67589. };
  67590. /**
  67591. * Creates a ground mesh
  67592. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  67593. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  67594. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67595. * @param name defines the name of the mesh
  67596. * @param options defines the options used to create the mesh
  67597. * @param scene defines the hosting scene
  67598. * @returns the ground mesh
  67599. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  67600. */
  67601. MeshBuilder.CreateGround = function (name, options, scene) {
  67602. var ground = new BABYLON.GroundMesh(name, scene);
  67603. ground._setReady(false);
  67604. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  67605. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  67606. ground._width = options.width || 1;
  67607. ground._height = options.height || 1;
  67608. ground._maxX = ground._width / 2;
  67609. ground._maxZ = ground._height / 2;
  67610. ground._minX = -ground._maxX;
  67611. ground._minZ = -ground._maxZ;
  67612. var vertexData = BABYLON.VertexData.CreateGround(options);
  67613. vertexData.applyToMesh(ground, options.updatable);
  67614. ground._setReady(true);
  67615. return ground;
  67616. };
  67617. /**
  67618. * Creates a tiled ground mesh
  67619. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  67620. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  67621. * * 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
  67622. * * 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
  67623. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67624. * @param name defines the name of the mesh
  67625. * @param options defines the options used to create the mesh
  67626. * @param scene defines the hosting scene
  67627. * @returns the tiled ground mesh
  67628. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  67629. */
  67630. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  67631. var tiledGround = new BABYLON.Mesh(name, scene);
  67632. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  67633. vertexData.applyToMesh(tiledGround, options.updatable);
  67634. return tiledGround;
  67635. };
  67636. /**
  67637. * Creates a ground mesh from a height map
  67638. * * The parameter `url` sets the URL of the height map image resource.
  67639. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  67640. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  67641. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  67642. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  67643. * * 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.
  67644. * * 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).
  67645. * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  67646. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67647. * @param name defines the name of the mesh
  67648. * @param url defines the url to the height map
  67649. * @param options defines the options used to create the mesh
  67650. * @param scene defines the hosting scene
  67651. * @returns the ground mesh
  67652. * @see http://doc.babylonjs.com/babylon101/height_map
  67653. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  67654. */
  67655. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  67656. var width = options.width || 10.0;
  67657. var height = options.height || 10.0;
  67658. var subdivisions = options.subdivisions || 1 | 0;
  67659. var minHeight = options.minHeight || 0.0;
  67660. var maxHeight = options.maxHeight || 1.0;
  67661. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  67662. var alphaFilter = options.alphaFilter || 0.0;
  67663. var updatable = options.updatable;
  67664. var onReady = options.onReady;
  67665. var ground = new BABYLON.GroundMesh(name, scene);
  67666. ground._subdivisionsX = subdivisions;
  67667. ground._subdivisionsY = subdivisions;
  67668. ground._width = width;
  67669. ground._height = height;
  67670. ground._maxX = ground._width / 2.0;
  67671. ground._maxZ = ground._height / 2.0;
  67672. ground._minX = -ground._maxX;
  67673. ground._minZ = -ground._maxZ;
  67674. ground._setReady(false);
  67675. var onload = function (img) {
  67676. // Getting height map data
  67677. var canvas = document.createElement("canvas");
  67678. var context = canvas.getContext("2d");
  67679. if (!context) {
  67680. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  67681. }
  67682. if (scene.isDisposed) {
  67683. return;
  67684. }
  67685. var bufferWidth = img.width;
  67686. var bufferHeight = img.height;
  67687. canvas.width = bufferWidth;
  67688. canvas.height = bufferHeight;
  67689. context.drawImage(img, 0, 0);
  67690. // Create VertexData from map data
  67691. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  67692. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  67693. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  67694. width: width, height: height,
  67695. subdivisions: subdivisions,
  67696. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  67697. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
  67698. alphaFilter: alphaFilter
  67699. });
  67700. vertexData.applyToMesh(ground, updatable);
  67701. //execute ready callback, if set
  67702. if (onReady) {
  67703. onReady(ground);
  67704. }
  67705. ground._setReady(true);
  67706. };
  67707. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  67708. return ground;
  67709. };
  67710. /**
  67711. * Creates a polygon mesh
  67712. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  67713. * * 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
  67714. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67715. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67716. * * 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)
  67717. * * Remember you can only change the shape positions, not their number when updating a polygon
  67718. * @param name defines the name of the mesh
  67719. * @param options defines the options used to create the mesh
  67720. * @param scene defines the hosting scene
  67721. * @returns the polygon mesh
  67722. */
  67723. MeshBuilder.CreatePolygon = function (name, options, scene) {
  67724. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67725. var shape = options.shape;
  67726. var holes = options.holes || [];
  67727. var depth = options.depth || 0;
  67728. var contours = [];
  67729. var hole = [];
  67730. for (var i = 0; i < shape.length; i++) {
  67731. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  67732. }
  67733. var epsilon = 0.00000001;
  67734. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  67735. contours.pop();
  67736. }
  67737. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  67738. for (var hNb = 0; hNb < holes.length; hNb++) {
  67739. hole = [];
  67740. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  67741. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  67742. }
  67743. polygonTriangulation.addHole(hole);
  67744. }
  67745. var polygon = polygonTriangulation.build(options.updatable, depth);
  67746. polygon._originalBuilderSideOrientation = options.sideOrientation;
  67747. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  67748. vertexData.applyToMesh(polygon, options.updatable);
  67749. return polygon;
  67750. };
  67751. ;
  67752. /**
  67753. * Creates an extruded polygon mesh, with depth in the Y direction.
  67754. * * 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)
  67755. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  67756. * @param name defines the name of the mesh
  67757. * @param options defines the options used to create the mesh
  67758. * @param scene defines the hosting scene
  67759. * @returns the polygon mesh
  67760. */
  67761. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  67762. return MeshBuilder.CreatePolygon(name, options, scene);
  67763. };
  67764. ;
  67765. /**
  67766. * Creates a tube mesh.
  67767. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  67768. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  67769. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  67770. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  67771. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  67772. * * 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)
  67773. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  67774. * * 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
  67775. * * 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
  67776. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67777. * * 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
  67778. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  67779. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67780. * @param name defines the name of the mesh
  67781. * @param options defines the options used to create the mesh
  67782. * @param scene defines the hosting scene
  67783. * @returns the tube mesh
  67784. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  67785. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  67786. */
  67787. MeshBuilder.CreateTube = function (name, options, scene) {
  67788. var path = options.path;
  67789. var instance = options.instance;
  67790. var radius = 1.0;
  67791. if (options.radius !== undefined) {
  67792. radius = options.radius;
  67793. }
  67794. else if (instance) {
  67795. radius = instance._creationDataStorage.radius;
  67796. }
  67797. var tessellation = options.tessellation || 64 | 0;
  67798. var radiusFunction = options.radiusFunction || null;
  67799. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  67800. var invertUV = options.invertUV || false;
  67801. var updatable = options.updatable;
  67802. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67803. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  67804. // tube geometry
  67805. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  67806. var tangents = path3D.getTangents();
  67807. var normals = path3D.getNormals();
  67808. var distances = path3D.getDistances();
  67809. var pi2 = Math.PI * 2;
  67810. var step = pi2 / tessellation * arc;
  67811. var returnRadius = function () { return radius; };
  67812. var radiusFunctionFinal = radiusFunction || returnRadius;
  67813. var circlePath;
  67814. var rad;
  67815. var normal;
  67816. var rotated;
  67817. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  67818. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  67819. for (var i = 0; i < path.length; i++) {
  67820. rad = radiusFunctionFinal(i, distances[i]); // current radius
  67821. circlePath = Array(); // current circle array
  67822. normal = normals[i]; // current normal
  67823. for (var t = 0; t < tessellation; t++) {
  67824. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  67825. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  67826. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  67827. rotated.scaleInPlace(rad).addInPlace(path[i]);
  67828. circlePath[t] = rotated;
  67829. }
  67830. circlePaths[index] = circlePath;
  67831. index++;
  67832. }
  67833. // cap
  67834. var capPath = function (nbPoints, pathIndex) {
  67835. var pointCap = Array();
  67836. for (var i = 0; i < nbPoints; i++) {
  67837. pointCap.push(path[pathIndex]);
  67838. }
  67839. return pointCap;
  67840. };
  67841. switch (cap) {
  67842. case BABYLON.Mesh.NO_CAP:
  67843. break;
  67844. case BABYLON.Mesh.CAP_START:
  67845. circlePaths[0] = capPath(tessellation, 0);
  67846. circlePaths[1] = circlePaths[2].slice(0);
  67847. break;
  67848. case BABYLON.Mesh.CAP_END:
  67849. circlePaths[index] = circlePaths[index - 1].slice(0);
  67850. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  67851. break;
  67852. case BABYLON.Mesh.CAP_ALL:
  67853. circlePaths[0] = capPath(tessellation, 0);
  67854. circlePaths[1] = circlePaths[2].slice(0);
  67855. circlePaths[index] = circlePaths[index - 1].slice(0);
  67856. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  67857. break;
  67858. default:
  67859. break;
  67860. }
  67861. return circlePaths;
  67862. };
  67863. var path3D;
  67864. var pathArray;
  67865. if (instance) { // tube update
  67866. var storage = instance._creationDataStorage;
  67867. var arc = options.arc || storage.arc;
  67868. path3D = storage.path3D.update(path);
  67869. pathArray = tubePathArray(path, path3D, storage.pathArray, radius, storage.tessellation, radiusFunction, storage.cap, arc);
  67870. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  67871. // Update mode, no need to recreate the storage.
  67872. storage.path3D = path3D;
  67873. storage.pathArray = pathArray;
  67874. storage.arc = arc;
  67875. storage.radius = radius;
  67876. return instance;
  67877. }
  67878. // tube creation
  67879. path3D = new BABYLON.Path3D(path);
  67880. var newPathArray = new Array();
  67881. cap = (cap < 0 || cap > 3) ? 0 : cap;
  67882. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  67883. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  67884. tube._creationDataStorage.pathArray = pathArray;
  67885. tube._creationDataStorage.path3D = path3D;
  67886. tube._creationDataStorage.tessellation = tessellation;
  67887. tube._creationDataStorage.cap = cap;
  67888. tube._creationDataStorage.arc = options.arc;
  67889. tube._creationDataStorage.radius = radius;
  67890. return tube;
  67891. };
  67892. /**
  67893. * Creates a polyhedron mesh
  67894. * * 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
  67895. * * The parameter `size` (positive float, default 1) sets the polygon size
  67896. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  67897. * * 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`
  67898. * * 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
  67899. * * 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)`)
  67900. * * 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
  67901. * * 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
  67902. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67903. * * 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
  67904. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67905. * @param name defines the name of the mesh
  67906. * @param options defines the options used to create the mesh
  67907. * @param scene defines the hosting scene
  67908. * @returns the polyhedron mesh
  67909. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  67910. */
  67911. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  67912. var polyhedron = new BABYLON.Mesh(name, scene);
  67913. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67914. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  67915. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  67916. vertexData.applyToMesh(polyhedron, options.updatable);
  67917. return polyhedron;
  67918. };
  67919. /**
  67920. * Creates a decal mesh.
  67921. * 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
  67922. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  67923. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  67924. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  67925. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  67926. * @param name defines the name of the mesh
  67927. * @param sourceMesh defines the mesh where the decal must be applied
  67928. * @param options defines the options used to create the mesh
  67929. * @param scene defines the hosting scene
  67930. * @returns the decal mesh
  67931. * @see http://doc.babylonjs.com/how_to/decals
  67932. */
  67933. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  67934. var indices = sourceMesh.getIndices();
  67935. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67936. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  67937. var position = options.position || BABYLON.Vector3.Zero();
  67938. var normal = options.normal || BABYLON.Vector3.Up();
  67939. var size = options.size || BABYLON.Vector3.One();
  67940. var angle = options.angle || 0;
  67941. // Getting correct rotation
  67942. if (!normal) {
  67943. var target = new BABYLON.Vector3(0, 0, 1);
  67944. var camera = sourceMesh.getScene().activeCamera;
  67945. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  67946. normal = camera.globalPosition.subtract(cameraWorldTarget);
  67947. }
  67948. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  67949. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  67950. var pitch = Math.atan2(normal.y, len);
  67951. // Matrix
  67952. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  67953. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  67954. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  67955. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  67956. var vertexData = new BABYLON.VertexData();
  67957. vertexData.indices = [];
  67958. vertexData.positions = [];
  67959. vertexData.normals = [];
  67960. vertexData.uvs = [];
  67961. var currentVertexDataIndex = 0;
  67962. var extractDecalVector3 = function (indexId) {
  67963. var result = new BABYLON.PositionNormalVertex();
  67964. if (!indices || !positions || !normals) {
  67965. return result;
  67966. }
  67967. var vertexId = indices[indexId];
  67968. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  67969. // Send vector to decal local world
  67970. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  67971. // Get normal
  67972. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  67973. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  67974. return result;
  67975. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  67976. var clip = function (vertices, axis) {
  67977. if (vertices.length === 0) {
  67978. return vertices;
  67979. }
  67980. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  67981. var clipVertices = function (v0, v1) {
  67982. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  67983. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  67984. };
  67985. var result = new Array();
  67986. for (var index = 0; index < vertices.length; index += 3) {
  67987. var v1Out;
  67988. var v2Out;
  67989. var v3Out;
  67990. var total = 0;
  67991. var nV1 = null;
  67992. var nV2 = null;
  67993. var nV3 = null;
  67994. var nV4 = null;
  67995. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  67996. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  67997. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  67998. v1Out = d1 > 0;
  67999. v2Out = d2 > 0;
  68000. v3Out = d3 > 0;
  68001. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  68002. switch (total) {
  68003. case 0:
  68004. result.push(vertices[index]);
  68005. result.push(vertices[index + 1]);
  68006. result.push(vertices[index + 2]);
  68007. break;
  68008. case 1:
  68009. if (v1Out) {
  68010. nV1 = vertices[index + 1];
  68011. nV2 = vertices[index + 2];
  68012. nV3 = clipVertices(vertices[index], nV1);
  68013. nV4 = clipVertices(vertices[index], nV2);
  68014. }
  68015. if (v2Out) {
  68016. nV1 = vertices[index];
  68017. nV2 = vertices[index + 2];
  68018. nV3 = clipVertices(vertices[index + 1], nV1);
  68019. nV4 = clipVertices(vertices[index + 1], nV2);
  68020. result.push(nV3);
  68021. result.push(nV2.clone());
  68022. result.push(nV1.clone());
  68023. result.push(nV2.clone());
  68024. result.push(nV3.clone());
  68025. result.push(nV4);
  68026. break;
  68027. }
  68028. if (v3Out) {
  68029. nV1 = vertices[index];
  68030. nV2 = vertices[index + 1];
  68031. nV3 = clipVertices(vertices[index + 2], nV1);
  68032. nV4 = clipVertices(vertices[index + 2], nV2);
  68033. }
  68034. if (nV1 && nV2 && nV3 && nV4) {
  68035. result.push(nV1.clone());
  68036. result.push(nV2.clone());
  68037. result.push(nV3);
  68038. result.push(nV4);
  68039. result.push(nV3.clone());
  68040. result.push(nV2.clone());
  68041. }
  68042. break;
  68043. case 2:
  68044. if (!v1Out) {
  68045. nV1 = vertices[index].clone();
  68046. nV2 = clipVertices(nV1, vertices[index + 1]);
  68047. nV3 = clipVertices(nV1, vertices[index + 2]);
  68048. result.push(nV1);
  68049. result.push(nV2);
  68050. result.push(nV3);
  68051. }
  68052. if (!v2Out) {
  68053. nV1 = vertices[index + 1].clone();
  68054. nV2 = clipVertices(nV1, vertices[index + 2]);
  68055. nV3 = clipVertices(nV1, vertices[index]);
  68056. result.push(nV1);
  68057. result.push(nV2);
  68058. result.push(nV3);
  68059. }
  68060. if (!v3Out) {
  68061. nV1 = vertices[index + 2].clone();
  68062. nV2 = clipVertices(nV1, vertices[index]);
  68063. nV3 = clipVertices(nV1, vertices[index + 1]);
  68064. result.push(nV1);
  68065. result.push(nV2);
  68066. result.push(nV3);
  68067. }
  68068. break;
  68069. case 3:
  68070. break;
  68071. }
  68072. }
  68073. return result;
  68074. };
  68075. for (var index = 0; index < indices.length; index += 3) {
  68076. var faceVertices = new Array();
  68077. faceVertices.push(extractDecalVector3(index));
  68078. faceVertices.push(extractDecalVector3(index + 1));
  68079. faceVertices.push(extractDecalVector3(index + 2));
  68080. // Clip
  68081. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  68082. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  68083. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  68084. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  68085. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  68086. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  68087. if (faceVertices.length === 0) {
  68088. continue;
  68089. }
  68090. // Add UVs and get back to world
  68091. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  68092. var vertex = faceVertices[vIndex];
  68093. //TODO check for Int32Array | Uint32Array | Uint16Array
  68094. vertexData.indices.push(currentVertexDataIndex);
  68095. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  68096. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  68097. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  68098. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  68099. currentVertexDataIndex++;
  68100. }
  68101. }
  68102. // Return mesh
  68103. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  68104. vertexData.applyToMesh(decal);
  68105. decal.position = position.clone();
  68106. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  68107. return decal;
  68108. };
  68109. // Privates
  68110. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  68111. // extrusion geometry
  68112. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  68113. var tangents = path3D.getTangents();
  68114. var normals = path3D.getNormals();
  68115. var binormals = path3D.getBinormals();
  68116. var distances = path3D.getDistances();
  68117. var angle = 0;
  68118. var returnScale = function () { return scale !== null ? scale : 1; };
  68119. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  68120. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  68121. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  68122. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  68123. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  68124. for (var i = 0; i < curve.length; i++) {
  68125. var shapePath = new Array();
  68126. var angleStep = rotate(i, distances[i]);
  68127. var scaleRatio = scl(i, distances[i]);
  68128. for (var p = 0; p < shape.length; p++) {
  68129. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  68130. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  68131. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  68132. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  68133. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  68134. shapePath[p] = rotated;
  68135. }
  68136. shapePaths[index] = shapePath;
  68137. angle += angleStep;
  68138. index++;
  68139. }
  68140. // cap
  68141. var capPath = function (shapePath) {
  68142. var pointCap = Array();
  68143. var barycenter = BABYLON.Vector3.Zero();
  68144. var i;
  68145. for (i = 0; i < shapePath.length; i++) {
  68146. barycenter.addInPlace(shapePath[i]);
  68147. }
  68148. barycenter.scaleInPlace(1.0 / shapePath.length);
  68149. for (i = 0; i < shapePath.length; i++) {
  68150. pointCap.push(barycenter);
  68151. }
  68152. return pointCap;
  68153. };
  68154. switch (cap) {
  68155. case BABYLON.Mesh.NO_CAP:
  68156. break;
  68157. case BABYLON.Mesh.CAP_START:
  68158. shapePaths[0] = capPath(shapePaths[2]);
  68159. shapePaths[1] = shapePaths[2];
  68160. break;
  68161. case BABYLON.Mesh.CAP_END:
  68162. shapePaths[index] = shapePaths[index - 1];
  68163. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  68164. break;
  68165. case BABYLON.Mesh.CAP_ALL:
  68166. shapePaths[0] = capPath(shapePaths[2]);
  68167. shapePaths[1] = shapePaths[2];
  68168. shapePaths[index] = shapePaths[index - 1];
  68169. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  68170. break;
  68171. default:
  68172. break;
  68173. }
  68174. return shapePaths;
  68175. };
  68176. var path3D;
  68177. var pathArray;
  68178. if (instance) { // instance update
  68179. var storage = instance._creationDataStorage;
  68180. path3D = storage.path3D.update(curve);
  68181. pathArray = extrusionPathArray(shape, curve, storage.path3D, storage.pathArray, scale, rotation, scaleFunction, rotateFunction, storage.cap, custom);
  68182. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  68183. return instance;
  68184. }
  68185. // extruded shape creation
  68186. path3D = new BABYLON.Path3D(curve);
  68187. var newShapePaths = new Array();
  68188. cap = (cap < 0 || cap > 3) ? 0 : cap;
  68189. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  68190. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  68191. extrudedGeneric._creationDataStorage.pathArray = pathArray;
  68192. extrudedGeneric._creationDataStorage.path3D = path3D;
  68193. extrudedGeneric._creationDataStorage.cap = cap;
  68194. return extrudedGeneric;
  68195. };
  68196. return MeshBuilder;
  68197. }());
  68198. BABYLON.MeshBuilder = MeshBuilder;
  68199. })(BABYLON || (BABYLON = {}));
  68200. //# sourceMappingURL=babylon.meshBuilder.js.map
  68201. var BABYLON;
  68202. (function (BABYLON) {
  68203. /**
  68204. * Draco compression (https://google.github.io/draco/)
  68205. *
  68206. * This class wraps the Draco module.
  68207. *
  68208. * **Encoder**
  68209. *
  68210. * The encoder is not currently implemented.
  68211. *
  68212. * **Decoder**
  68213. *
  68214. * By default, the configuration points to a copy of the Draco decoder files for glTF from the babylon.js preview cdn https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js.
  68215. *
  68216. * To update the configuration, use the following code:
  68217. * ```javascript
  68218. * BABYLON.DracoCompression.Configuration = {
  68219. * decoder: {
  68220. * wasmUrl: "<url to the WebAssembly library>",
  68221. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  68222. * fallbackUrl: "<url to the fallback JavaScript library>",
  68223. * }
  68224. * };
  68225. * ```
  68226. *
  68227. * 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.
  68228. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  68229. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  68230. *
  68231. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  68232. * ```javascript
  68233. * var dracoCompression = new BABYLON.DracoCompression();
  68234. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  68235. * [BABYLON.VertexBuffer.PositionKind]: 0
  68236. * });
  68237. * ```
  68238. *
  68239. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  68240. */
  68241. var DracoCompression = /** @class */ (function () {
  68242. /**
  68243. * Constructor
  68244. */
  68245. function DracoCompression() {
  68246. }
  68247. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  68248. /**
  68249. * Returns true if the decoder is available.
  68250. */
  68251. get: function () {
  68252. if (typeof DracoDecoderModule !== "undefined") {
  68253. return true;
  68254. }
  68255. var decoder = DracoCompression.Configuration.decoder;
  68256. if (decoder) {
  68257. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  68258. return true;
  68259. }
  68260. if (decoder.fallbackUrl) {
  68261. return true;
  68262. }
  68263. }
  68264. return false;
  68265. },
  68266. enumerable: true,
  68267. configurable: true
  68268. });
  68269. /**
  68270. * Stop all async operations and release resources.
  68271. */
  68272. DracoCompression.prototype.dispose = function () {
  68273. };
  68274. /**
  68275. * Decode Draco compressed mesh data to vertex data.
  68276. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  68277. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  68278. * @returns A promise that resolves with the decoded vertex data
  68279. */
  68280. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  68281. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  68282. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  68283. var module = wrappedModule.module;
  68284. var vertexData = new BABYLON.VertexData();
  68285. var buffer = new module.DecoderBuffer();
  68286. buffer.Init(dataView, dataView.byteLength);
  68287. var decoder = new module.Decoder();
  68288. var geometry;
  68289. var status;
  68290. try {
  68291. var type = decoder.GetEncodedGeometryType(buffer);
  68292. switch (type) {
  68293. case module.TRIANGULAR_MESH:
  68294. geometry = new module.Mesh();
  68295. status = decoder.DecodeBufferToMesh(buffer, geometry);
  68296. break;
  68297. case module.POINT_CLOUD:
  68298. geometry = new module.PointCloud();
  68299. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  68300. break;
  68301. default:
  68302. throw new Error("Invalid geometry type " + type);
  68303. }
  68304. if (!status.ok() || !geometry.ptr) {
  68305. throw new Error(status.error_msg());
  68306. }
  68307. var numPoints = geometry.num_points();
  68308. if (type === module.TRIANGULAR_MESH) {
  68309. var numFaces = geometry.num_faces();
  68310. var faceIndices = new module.DracoInt32Array();
  68311. try {
  68312. var indices = new Uint32Array(numFaces * 3);
  68313. for (var i = 0; i < numFaces; i++) {
  68314. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  68315. var offset = i * 3;
  68316. indices[offset + 0] = faceIndices.GetValue(0);
  68317. indices[offset + 1] = faceIndices.GetValue(1);
  68318. indices[offset + 2] = faceIndices.GetValue(2);
  68319. }
  68320. vertexData.indices = indices;
  68321. }
  68322. finally {
  68323. module.destroy(faceIndices);
  68324. }
  68325. }
  68326. for (var kind in attributes) {
  68327. var uniqueId = attributes[kind];
  68328. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  68329. var dracoData = new module.DracoFloat32Array();
  68330. try {
  68331. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  68332. var babylonData = new Float32Array(numPoints * attribute.num_components());
  68333. for (var i = 0; i < babylonData.length; i++) {
  68334. babylonData[i] = dracoData.GetValue(i);
  68335. }
  68336. vertexData.set(babylonData, kind);
  68337. }
  68338. finally {
  68339. module.destroy(dracoData);
  68340. }
  68341. }
  68342. }
  68343. finally {
  68344. if (geometry) {
  68345. module.destroy(geometry);
  68346. }
  68347. module.destroy(decoder);
  68348. module.destroy(buffer);
  68349. }
  68350. return vertexData;
  68351. });
  68352. };
  68353. DracoCompression._GetDecoderModule = function () {
  68354. if (!DracoCompression._DecoderModulePromise) {
  68355. var promise = null;
  68356. var config_1 = {};
  68357. if (typeof DracoDecoderModule !== "undefined") {
  68358. promise = Promise.resolve();
  68359. }
  68360. else {
  68361. var decoder = DracoCompression.Configuration.decoder;
  68362. if (decoder) {
  68363. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  68364. promise = Promise.all([
  68365. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  68366. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  68367. config_1.wasmBinary = data;
  68368. })
  68369. ]);
  68370. }
  68371. else if (decoder.fallbackUrl) {
  68372. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  68373. }
  68374. }
  68375. }
  68376. if (!promise) {
  68377. throw new Error("Draco decoder module is not available");
  68378. }
  68379. DracoCompression._DecoderModulePromise = promise.then(function () {
  68380. return new Promise(function (resolve) {
  68381. config_1.onModuleLoaded = function (decoderModule) {
  68382. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  68383. resolve({ module: decoderModule });
  68384. };
  68385. DracoDecoderModule(config_1);
  68386. });
  68387. });
  68388. }
  68389. return DracoCompression._DecoderModulePromise;
  68390. };
  68391. DracoCompression._LoadScriptAsync = function (url) {
  68392. return new Promise(function (resolve, reject) {
  68393. BABYLON.Tools.LoadScript(url, function () {
  68394. resolve();
  68395. }, function (message) {
  68396. reject(new Error(message));
  68397. });
  68398. });
  68399. };
  68400. DracoCompression._LoadFileAsync = function (url) {
  68401. return new Promise(function (resolve, reject) {
  68402. BABYLON.Tools.LoadFile(url, function (data) {
  68403. resolve(data);
  68404. }, undefined, undefined, true, function (request, exception) {
  68405. reject(exception);
  68406. });
  68407. });
  68408. };
  68409. /**
  68410. * The configuration. Defaults to the following urls:
  68411. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  68412. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  68413. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  68414. */
  68415. DracoCompression.Configuration = {
  68416. decoder: {
  68417. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  68418. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  68419. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  68420. }
  68421. };
  68422. return DracoCompression;
  68423. }());
  68424. BABYLON.DracoCompression = DracoCompression;
  68425. })(BABYLON || (BABYLON = {}));
  68426. //# sourceMappingURL=babylon.dracoCompression.js.map
  68427. var BABYLON;
  68428. (function (BABYLON) {
  68429. // Sets the default audio engine to Babylon JS.
  68430. BABYLON.Engine.AudioEngineFactory = function (engine) { return new AudioEngine(engine); };
  68431. /**
  68432. * This represents the default audio engine used in babylon.
  68433. * It is responsible to play, synchronize and analyse sounds throughout the application.
  68434. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  68435. */
  68436. var AudioEngine = /** @class */ (function () {
  68437. /**
  68438. * Instantiates a new audio engine.
  68439. *
  68440. * There should be only one per page as some browsers restrict the number
  68441. * of audio contexts you can create.
  68442. * @param engine defines the hosting engine
  68443. */
  68444. function AudioEngine(engine) {
  68445. if (engine === void 0) { engine = BABYLON.Engine.LastCreatedEngine; }
  68446. var _this = this;
  68447. this._audioContext = null;
  68448. this._audioContextInitialized = false;
  68449. this._muteButton = null;
  68450. /**
  68451. * Gets whether the current host supports Web Audio and thus could create AudioContexts.
  68452. */
  68453. this.canUseWebAudio = false;
  68454. /**
  68455. * Defines if Babylon should emit a warning if WebAudio is not supported.
  68456. * @ignoreNaming
  68457. */
  68458. this.WarnedWebAudioUnsupported = false;
  68459. /**
  68460. * Gets whether or not mp3 are supported by your browser.
  68461. */
  68462. this.isMP3supported = false;
  68463. /**
  68464. * Gets whether or not ogg are supported by your browser.
  68465. */
  68466. this.isOGGsupported = false;
  68467. /**
  68468. * Gets whether audio has been unlocked on the device.
  68469. * Some Browsers have strong restrictions about Audio and won t autoplay unless
  68470. * a user interaction has happened.
  68471. */
  68472. this.unlocked = true;
  68473. /**
  68474. * Defines if the audio engine relies on a custom unlocked button.
  68475. * In this case, the embedded button will not be displayed.
  68476. */
  68477. this.useCustomUnlockedButton = false;
  68478. /**
  68479. * Event raised when audio has been unlocked on the browser.
  68480. */
  68481. this.onAudioUnlockedObservable = new BABYLON.Observable();
  68482. /**
  68483. * Event raised when audio has been locked on the browser.
  68484. */
  68485. this.onAudioLockedObservable = new BABYLON.Observable();
  68486. this._tryToRun = false;
  68487. this._onResize = function () {
  68488. _this._moveButtonToTopLeft();
  68489. };
  68490. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  68491. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  68492. this.canUseWebAudio = true;
  68493. }
  68494. var audioElem = document.createElement('audio');
  68495. this._engine = engine;
  68496. try {
  68497. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  68498. this.isMP3supported = true;
  68499. }
  68500. }
  68501. catch (e) {
  68502. // protect error during capability check.
  68503. }
  68504. try {
  68505. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  68506. this.isOGGsupported = true;
  68507. }
  68508. }
  68509. catch (e) {
  68510. // protect error during capability check.
  68511. }
  68512. }
  68513. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  68514. /**
  68515. * Gets the current AudioContext if available.
  68516. */
  68517. get: function () {
  68518. if (!this._audioContextInitialized) {
  68519. this._initializeAudioContext();
  68520. }
  68521. else {
  68522. if (!this.unlocked && !this._muteButton) {
  68523. this._displayMuteButton();
  68524. }
  68525. }
  68526. return this._audioContext;
  68527. },
  68528. enumerable: true,
  68529. configurable: true
  68530. });
  68531. /**
  68532. * Flags the audio engine in Locked state.
  68533. * This happens due to new browser policies preventing audio to autoplay.
  68534. */
  68535. AudioEngine.prototype.lock = function () {
  68536. this._triggerSuspendedState();
  68537. };
  68538. /**
  68539. * Unlocks the audio engine once a user action has been done on the dom.
  68540. * This is helpful to resume play once browser policies have been satisfied.
  68541. */
  68542. AudioEngine.prototype.unlock = function () {
  68543. this._triggerRunningState();
  68544. };
  68545. AudioEngine.prototype._resumeAudioContext = function () {
  68546. var result;
  68547. if (this._audioContext.resume) {
  68548. result = this._audioContext.resume();
  68549. }
  68550. return result || Promise.resolve();
  68551. };
  68552. AudioEngine.prototype._initializeAudioContext = function () {
  68553. var _this = this;
  68554. try {
  68555. if (this.canUseWebAudio) {
  68556. this._audioContext = new AudioContext();
  68557. // create a global volume gain node
  68558. this.masterGain = this._audioContext.createGain();
  68559. this.masterGain.gain.value = 1;
  68560. this.masterGain.connect(this._audioContext.destination);
  68561. this._audioContextInitialized = true;
  68562. if (this._audioContext.state === "running") {
  68563. // Do not wait for the promise to unlock.
  68564. this._triggerRunningState();
  68565. }
  68566. else {
  68567. if (this._audioContext && this._audioContext.resume) {
  68568. this._resumeAudioContext().then(function () {
  68569. _this._triggerRunningState();
  68570. }).catch(function () {
  68571. // Can not resume automatically
  68572. // Needs user action
  68573. _this.lock();
  68574. });
  68575. }
  68576. }
  68577. }
  68578. }
  68579. catch (e) {
  68580. this.canUseWebAudio = false;
  68581. BABYLON.Tools.Error("Web Audio: " + e.message);
  68582. }
  68583. };
  68584. AudioEngine.prototype._triggerRunningState = function () {
  68585. var _this = this;
  68586. if (this._tryToRun) {
  68587. return;
  68588. }
  68589. this._tryToRun = true;
  68590. this._resumeAudioContext()
  68591. .then(function () {
  68592. _this._tryToRun = false;
  68593. _this.unlocked = true;
  68594. if (_this._muteButton) {
  68595. _this._hideMuteButton();
  68596. }
  68597. // Notify users that the audio stack is unlocked/unmuted
  68598. _this.onAudioUnlockedObservable.notifyObservers(_this);
  68599. }).catch(function () {
  68600. _this._tryToRun = false;
  68601. _this.unlocked = false;
  68602. });
  68603. };
  68604. AudioEngine.prototype._triggerSuspendedState = function () {
  68605. this.unlocked = false;
  68606. this.onAudioLockedObservable.notifyObservers(this);
  68607. this._displayMuteButton();
  68608. };
  68609. AudioEngine.prototype._displayMuteButton = function () {
  68610. var _this = this;
  68611. if (this.useCustomUnlockedButton) {
  68612. return;
  68613. }
  68614. this._canvas = this._engine.getRenderingCanvas();
  68615. this._muteButton = document.createElement("BUTTON");
  68616. this._muteButton.className = "babylonUnmuteIcon";
  68617. this._muteButton.id = "babylonUnmuteIconBtn";
  68618. this._muteButton.title = "Unmute";
  68619. var css = ".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E); background-size: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }";
  68620. var style = document.createElement('style');
  68621. style.appendChild(document.createTextNode(css));
  68622. document.getElementsByTagName('head')[0].appendChild(style);
  68623. document.body.appendChild(this._muteButton);
  68624. this._moveButtonToTopLeft();
  68625. this._muteButton.addEventListener('mousedown', function () {
  68626. _this._triggerRunningState();
  68627. }, true);
  68628. this._muteButton.addEventListener('touchend', function () {
  68629. _this._triggerRunningState();
  68630. }, true);
  68631. this._muteButton.addEventListener('click', function () {
  68632. _this._triggerRunningState();
  68633. }, true);
  68634. window.addEventListener("resize", this._onResize);
  68635. };
  68636. AudioEngine.prototype._moveButtonToTopLeft = function () {
  68637. if (this._canvas && this._muteButton) {
  68638. this._muteButton.style.top = this._canvas.offsetTop + 20 + "px";
  68639. this._muteButton.style.left = this._canvas.offsetLeft + 20 + "px";
  68640. }
  68641. };
  68642. AudioEngine.prototype._hideMuteButton = function () {
  68643. if (this._muteButton) {
  68644. document.body.removeChild(this._muteButton);
  68645. this._muteButton = null;
  68646. }
  68647. };
  68648. /**
  68649. * Destroy and release the resources associated with the audio ccontext.
  68650. */
  68651. AudioEngine.prototype.dispose = function () {
  68652. if (this.canUseWebAudio && this._audioContextInitialized) {
  68653. if (this._connectedAnalyser && this._audioContext) {
  68654. this._connectedAnalyser.stopDebugCanvas();
  68655. this._connectedAnalyser.dispose();
  68656. this.masterGain.disconnect();
  68657. this.masterGain.connect(this._audioContext.destination);
  68658. this._connectedAnalyser = null;
  68659. }
  68660. this.masterGain.gain.value = 1;
  68661. }
  68662. this.WarnedWebAudioUnsupported = false;
  68663. this._hideMuteButton();
  68664. window.removeEventListener("resize", this._onResize);
  68665. this.onAudioUnlockedObservable.clear();
  68666. this.onAudioLockedObservable.clear();
  68667. };
  68668. /**
  68669. * Gets the global volume sets on the master gain.
  68670. * @returns the global volume if set or -1 otherwise
  68671. */
  68672. AudioEngine.prototype.getGlobalVolume = function () {
  68673. if (this.canUseWebAudio && this._audioContextInitialized) {
  68674. return this.masterGain.gain.value;
  68675. }
  68676. else {
  68677. return -1;
  68678. }
  68679. };
  68680. /**
  68681. * Sets the global volume of your experience (sets on the master gain).
  68682. * @param newVolume Defines the new global volume of the application
  68683. */
  68684. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  68685. if (this.canUseWebAudio && this._audioContextInitialized) {
  68686. this.masterGain.gain.value = newVolume;
  68687. }
  68688. };
  68689. /**
  68690. * Connect the audio engine to an audio analyser allowing some amazing
  68691. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  68692. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  68693. * @param analyser The analyser to connect to the engine
  68694. */
  68695. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  68696. if (this._connectedAnalyser) {
  68697. this._connectedAnalyser.stopDebugCanvas();
  68698. }
  68699. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  68700. this._connectedAnalyser = analyser;
  68701. this.masterGain.disconnect();
  68702. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  68703. }
  68704. };
  68705. return AudioEngine;
  68706. }());
  68707. BABYLON.AudioEngine = AudioEngine;
  68708. })(BABYLON || (BABYLON = {}));
  68709. //# sourceMappingURL=babylon.audioEngine.js.map
  68710. var BABYLON;
  68711. (function (BABYLON) {
  68712. /**
  68713. * Defines a sound that can be played in the application.
  68714. * The sound can either be an ambient track or a simple sound played in reaction to a user action.
  68715. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  68716. */
  68717. var Sound = /** @class */ (function () {
  68718. /**
  68719. * Create a sound and attach it to a scene
  68720. * @param name Name of your sound
  68721. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  68722. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  68723. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  68724. */
  68725. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  68726. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  68727. var _this = this;
  68728. /**
  68729. * Does the sound autoplay once loaded.
  68730. */
  68731. this.autoplay = false;
  68732. /**
  68733. * Does the sound loop after it finishes playing once.
  68734. */
  68735. this.loop = false;
  68736. /**
  68737. * Does the sound use a custom attenuation curve to simulate the falloff
  68738. * happening when the source gets further away from the camera.
  68739. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  68740. */
  68741. this.useCustomAttenuation = false;
  68742. /**
  68743. * Is this sound currently played.
  68744. */
  68745. this.isPlaying = false;
  68746. /**
  68747. * Is this sound currently paused.
  68748. */
  68749. this.isPaused = false;
  68750. /**
  68751. * Does this sound enables spatial sound.
  68752. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68753. */
  68754. this.spatialSound = false;
  68755. /**
  68756. * Define the reference distance the sound should be heard perfectly.
  68757. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68758. */
  68759. this.refDistance = 1;
  68760. /**
  68761. * Define the roll off factor of spatial sounds.
  68762. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68763. */
  68764. this.rolloffFactor = 1;
  68765. /**
  68766. * Define the max distance the sound should be heard (intensity just became 0 at this point).
  68767. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68768. */
  68769. this.maxDistance = 100;
  68770. /**
  68771. * Define the distance attenuation model the sound will follow.
  68772. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68773. */
  68774. this.distanceModel = "linear";
  68775. /**
  68776. * Observable event when the current playing sound finishes.
  68777. */
  68778. this.onEndedObservable = new BABYLON.Observable();
  68779. this._panningModel = "equalpower";
  68780. this._playbackRate = 1;
  68781. this._streaming = false;
  68782. this._startTime = 0;
  68783. this._startOffset = 0;
  68784. this._position = BABYLON.Vector3.Zero();
  68785. /** @hidden */
  68786. this._positionInEmitterSpace = false;
  68787. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  68788. this._volume = 1;
  68789. this._isReadyToPlay = false;
  68790. this._isDirectional = false;
  68791. // Used if you'd like to create a directional sound.
  68792. // If not set, the sound will be omnidirectional
  68793. this._coneInnerAngle = 360;
  68794. this._coneOuterAngle = 360;
  68795. this._coneOuterGain = 0;
  68796. this._isOutputConnected = false;
  68797. this._urlType = "Unknown";
  68798. this.name = name;
  68799. this._scene = scene;
  68800. var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  68801. if (!compo) {
  68802. compo = new BABYLON.AudioSceneComponent(scene);
  68803. scene._addComponent(compo);
  68804. }
  68805. this._readyToPlayCallback = readyToPlayCallback;
  68806. // Default custom attenuation function is a linear attenuation
  68807. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  68808. if (currentDistance < maxDistance) {
  68809. return currentVolume * (1 - currentDistance / maxDistance);
  68810. }
  68811. else {
  68812. return 0;
  68813. }
  68814. };
  68815. if (options) {
  68816. this.autoplay = options.autoplay || false;
  68817. this.loop = options.loop || false;
  68818. // if volume === 0, we need another way to check this option
  68819. if (options.volume !== undefined) {
  68820. this._volume = options.volume;
  68821. }
  68822. this.spatialSound = options.spatialSound || false;
  68823. this.maxDistance = options.maxDistance || 100;
  68824. this.useCustomAttenuation = options.useCustomAttenuation || false;
  68825. this.rolloffFactor = options.rolloffFactor || 1;
  68826. this.refDistance = options.refDistance || 1;
  68827. this.distanceModel = options.distanceModel || "linear";
  68828. this._playbackRate = options.playbackRate || 1;
  68829. this._streaming = options.streaming || false;
  68830. }
  68831. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  68832. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  68833. this._soundGain.gain.value = this._volume;
  68834. this._inputAudioNode = this._soundGain;
  68835. this._outputAudioNode = this._soundGain;
  68836. if (this.spatialSound) {
  68837. this._createSpatialParameters();
  68838. }
  68839. this._scene.mainSoundTrack.AddSound(this);
  68840. var validParameter = true;
  68841. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  68842. if (urlOrArrayBuffer) {
  68843. try {
  68844. if (typeof (urlOrArrayBuffer) === "string") {
  68845. this._urlType = "String";
  68846. }
  68847. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  68848. this._urlType = "ArrayBuffer";
  68849. }
  68850. else if (urlOrArrayBuffer instanceof MediaStream) {
  68851. this._urlType = "MediaStream";
  68852. }
  68853. else if (Array.isArray(urlOrArrayBuffer)) {
  68854. this._urlType = "Array";
  68855. }
  68856. var urls = [];
  68857. var codecSupportedFound = false;
  68858. switch (this._urlType) {
  68859. case "MediaStream":
  68860. this._streaming = true;
  68861. this._isReadyToPlay = true;
  68862. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  68863. if (this.autoplay) {
  68864. this.play();
  68865. }
  68866. if (this._readyToPlayCallback) {
  68867. this._readyToPlayCallback();
  68868. }
  68869. break;
  68870. case "ArrayBuffer":
  68871. if (urlOrArrayBuffer.byteLength > 0) {
  68872. codecSupportedFound = true;
  68873. this._soundLoaded(urlOrArrayBuffer);
  68874. }
  68875. break;
  68876. case "String":
  68877. urls.push(urlOrArrayBuffer);
  68878. case "Array":
  68879. if (urls.length === 0)
  68880. urls = urlOrArrayBuffer;
  68881. // If we found a supported format, we load it immediately and stop the loop
  68882. for (var i = 0; i < urls.length; i++) {
  68883. var url = urls[i];
  68884. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  68885. codecSupportedFound = true;
  68886. }
  68887. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  68888. codecSupportedFound = true;
  68889. }
  68890. if (url.indexOf(".wav", url.length - 4) !== -1) {
  68891. codecSupportedFound = true;
  68892. }
  68893. if (url.indexOf("blob:") !== -1) {
  68894. codecSupportedFound = true;
  68895. }
  68896. if (codecSupportedFound) {
  68897. // Loading sound using XHR2
  68898. if (!this._streaming) {
  68899. this._scene._loadFile(url, function (data) {
  68900. _this._soundLoaded(data);
  68901. }, undefined, true, true, function (exception) {
  68902. if (exception) {
  68903. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  68904. }
  68905. BABYLON.Tools.Error("Sound creation aborted.");
  68906. _this._scene.mainSoundTrack.RemoveSound(_this);
  68907. });
  68908. }
  68909. // Streaming sound using HTML5 Audio tag
  68910. else {
  68911. this._htmlAudioElement = new Audio(url);
  68912. this._htmlAudioElement.controls = false;
  68913. this._htmlAudioElement.loop = this.loop;
  68914. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  68915. this._htmlAudioElement.preload = "auto";
  68916. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  68917. _this._isReadyToPlay = true;
  68918. if (_this.autoplay) {
  68919. _this.play();
  68920. }
  68921. if (_this._readyToPlayCallback) {
  68922. _this._readyToPlayCallback();
  68923. }
  68924. });
  68925. document.body.appendChild(this._htmlAudioElement);
  68926. this._htmlAudioElement.load();
  68927. }
  68928. break;
  68929. }
  68930. }
  68931. break;
  68932. default:
  68933. validParameter = false;
  68934. break;
  68935. }
  68936. if (!validParameter) {
  68937. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  68938. }
  68939. else {
  68940. if (!codecSupportedFound) {
  68941. this._isReadyToPlay = true;
  68942. // Simulating a ready to play event to avoid breaking code path
  68943. if (this._readyToPlayCallback) {
  68944. window.setTimeout(function () {
  68945. if (_this._readyToPlayCallback) {
  68946. _this._readyToPlayCallback();
  68947. }
  68948. }, 1000);
  68949. }
  68950. }
  68951. }
  68952. }
  68953. catch (ex) {
  68954. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  68955. this._scene.mainSoundTrack.RemoveSound(this);
  68956. }
  68957. }
  68958. }
  68959. else {
  68960. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  68961. this._scene.mainSoundTrack.AddSound(this);
  68962. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  68963. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  68964. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  68965. }
  68966. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  68967. if (this._readyToPlayCallback) {
  68968. window.setTimeout(function () {
  68969. if (_this._readyToPlayCallback) {
  68970. _this._readyToPlayCallback();
  68971. }
  68972. }, 1000);
  68973. }
  68974. }
  68975. }
  68976. /**
  68977. * Release the sound and its associated resources
  68978. */
  68979. Sound.prototype.dispose = function () {
  68980. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68981. if (this.isPlaying) {
  68982. this.stop();
  68983. }
  68984. this._isReadyToPlay = false;
  68985. if (this.soundTrackId === -1) {
  68986. this._scene.mainSoundTrack.RemoveSound(this);
  68987. }
  68988. else if (this._scene.soundTracks) {
  68989. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  68990. }
  68991. if (this._soundGain) {
  68992. this._soundGain.disconnect();
  68993. this._soundGain = null;
  68994. }
  68995. if (this._soundPanner) {
  68996. this._soundPanner.disconnect();
  68997. this._soundPanner = null;
  68998. }
  68999. if (this._soundSource) {
  69000. this._soundSource.disconnect();
  69001. this._soundSource = null;
  69002. }
  69003. this._audioBuffer = null;
  69004. if (this._htmlAudioElement) {
  69005. this._htmlAudioElement.pause();
  69006. this._htmlAudioElement.src = "";
  69007. document.body.removeChild(this._htmlAudioElement);
  69008. }
  69009. if (this._streamingSource) {
  69010. this._streamingSource.disconnect();
  69011. }
  69012. if (this._connectedMesh && this._registerFunc) {
  69013. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  69014. this._connectedMesh = null;
  69015. }
  69016. }
  69017. };
  69018. /**
  69019. * Gets if the sounds is ready to be played or not.
  69020. * @returns true if ready, otherwise false
  69021. */
  69022. Sound.prototype.isReady = function () {
  69023. return this._isReadyToPlay;
  69024. };
  69025. Sound.prototype._soundLoaded = function (audioData) {
  69026. var _this = this;
  69027. if (!BABYLON.Engine.audioEngine.audioContext) {
  69028. return;
  69029. }
  69030. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  69031. _this._audioBuffer = buffer;
  69032. _this._isReadyToPlay = true;
  69033. if (_this.autoplay) {
  69034. _this.play();
  69035. }
  69036. if (_this._readyToPlayCallback) {
  69037. _this._readyToPlayCallback();
  69038. }
  69039. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  69040. };
  69041. /**
  69042. * Sets the data of the sound from an audiobuffer
  69043. * @param audioBuffer The audioBuffer containing the data
  69044. */
  69045. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  69046. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69047. this._audioBuffer = audioBuffer;
  69048. this._isReadyToPlay = true;
  69049. }
  69050. };
  69051. /**
  69052. * Updates the current sounds options such as maxdistance, loop...
  69053. * @param options A JSON object containing values named as the object properties
  69054. */
  69055. Sound.prototype.updateOptions = function (options) {
  69056. if (options) {
  69057. this.loop = options.loop || this.loop;
  69058. this.maxDistance = options.maxDistance || this.maxDistance;
  69059. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  69060. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  69061. this.refDistance = options.refDistance || this.refDistance;
  69062. this.distanceModel = options.distanceModel || this.distanceModel;
  69063. this._playbackRate = options.playbackRate || this._playbackRate;
  69064. this._updateSpatialParameters();
  69065. if (this.isPlaying) {
  69066. if (this._streaming && this._htmlAudioElement) {
  69067. this._htmlAudioElement.playbackRate = this._playbackRate;
  69068. }
  69069. else {
  69070. if (this._soundSource) {
  69071. this._soundSource.playbackRate.value = this._playbackRate;
  69072. }
  69073. }
  69074. }
  69075. }
  69076. };
  69077. Sound.prototype._createSpatialParameters = function () {
  69078. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  69079. if (this._scene.headphone) {
  69080. this._panningModel = "HRTF";
  69081. }
  69082. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  69083. this._updateSpatialParameters();
  69084. this._soundPanner.connect(this._outputAudioNode);
  69085. this._inputAudioNode = this._soundPanner;
  69086. }
  69087. };
  69088. Sound.prototype._updateSpatialParameters = function () {
  69089. if (this.spatialSound && this._soundPanner) {
  69090. if (this.useCustomAttenuation) {
  69091. // Tricks to disable in a way embedded Web Audio attenuation
  69092. this._soundPanner.distanceModel = "linear";
  69093. this._soundPanner.maxDistance = Number.MAX_VALUE;
  69094. this._soundPanner.refDistance = 1;
  69095. this._soundPanner.rolloffFactor = 1;
  69096. this._soundPanner.panningModel = this._panningModel;
  69097. }
  69098. else {
  69099. this._soundPanner.distanceModel = this.distanceModel;
  69100. this._soundPanner.maxDistance = this.maxDistance;
  69101. this._soundPanner.refDistance = this.refDistance;
  69102. this._soundPanner.rolloffFactor = this.rolloffFactor;
  69103. this._soundPanner.panningModel = this._panningModel;
  69104. }
  69105. }
  69106. };
  69107. /**
  69108. * Switch the panning model to HRTF:
  69109. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  69110. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69111. */
  69112. Sound.prototype.switchPanningModelToHRTF = function () {
  69113. this._panningModel = "HRTF";
  69114. this._switchPanningModel();
  69115. };
  69116. /**
  69117. * Switch the panning model to Equal Power:
  69118. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  69119. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69120. */
  69121. Sound.prototype.switchPanningModelToEqualPower = function () {
  69122. this._panningModel = "equalpower";
  69123. this._switchPanningModel();
  69124. };
  69125. Sound.prototype._switchPanningModel = function () {
  69126. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  69127. this._soundPanner.panningModel = this._panningModel;
  69128. }
  69129. };
  69130. /**
  69131. * Connect this sound to a sound track audio node like gain...
  69132. * @param soundTrackAudioNode the sound track audio node to connect to
  69133. */
  69134. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  69135. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69136. if (this._isOutputConnected) {
  69137. this._outputAudioNode.disconnect();
  69138. }
  69139. this._outputAudioNode.connect(soundTrackAudioNode);
  69140. this._isOutputConnected = true;
  69141. }
  69142. };
  69143. /**
  69144. * Transform this sound into a directional source
  69145. * @param coneInnerAngle Size of the inner cone in degree
  69146. * @param coneOuterAngle Size of the outer cone in degree
  69147. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  69148. */
  69149. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  69150. if (coneOuterAngle < coneInnerAngle) {
  69151. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  69152. return;
  69153. }
  69154. this._coneInnerAngle = coneInnerAngle;
  69155. this._coneOuterAngle = coneOuterAngle;
  69156. this._coneOuterGain = coneOuterGain;
  69157. this._isDirectional = true;
  69158. if (this.isPlaying && this.loop) {
  69159. this.stop();
  69160. this.play();
  69161. }
  69162. };
  69163. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  69164. /**
  69165. * Gets or sets the inner angle for the directional cone.
  69166. */
  69167. get: function () {
  69168. return this._coneInnerAngle;
  69169. },
  69170. /**
  69171. * Gets or sets the inner angle for the directional cone.
  69172. */
  69173. set: function (value) {
  69174. if (value != this._coneInnerAngle) {
  69175. if (this._coneOuterAngle < value) {
  69176. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  69177. return;
  69178. }
  69179. this._coneInnerAngle = value;
  69180. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  69181. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  69182. }
  69183. }
  69184. },
  69185. enumerable: true,
  69186. configurable: true
  69187. });
  69188. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  69189. /**
  69190. * Gets or sets the outer angle for the directional cone.
  69191. */
  69192. get: function () {
  69193. return this._coneOuterAngle;
  69194. },
  69195. /**
  69196. * Gets or sets the outer angle for the directional cone.
  69197. */
  69198. set: function (value) {
  69199. if (value != this._coneOuterAngle) {
  69200. if (value < this._coneInnerAngle) {
  69201. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  69202. return;
  69203. }
  69204. this._coneOuterAngle = value;
  69205. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  69206. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  69207. }
  69208. }
  69209. },
  69210. enumerable: true,
  69211. configurable: true
  69212. });
  69213. /**
  69214. * Sets the position of the emitter if spatial sound is enabled
  69215. * @param newPosition Defines the new posisiton
  69216. */
  69217. Sound.prototype.setPosition = function (newPosition) {
  69218. this._position = newPosition;
  69219. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  69220. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  69221. }
  69222. };
  69223. /**
  69224. * Sets the local direction of the emitter if spatial sound is enabled
  69225. * @param newLocalDirection Defines the new local direction
  69226. */
  69227. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  69228. this._localDirection = newLocalDirection;
  69229. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  69230. this._updateDirection();
  69231. }
  69232. };
  69233. Sound.prototype._updateDirection = function () {
  69234. if (!this._connectedMesh || !this._soundPanner) {
  69235. return;
  69236. }
  69237. var mat = this._connectedMesh.getWorldMatrix();
  69238. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  69239. direction.normalize();
  69240. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  69241. };
  69242. /** @hidden */
  69243. Sound.prototype.updateDistanceFromListener = function () {
  69244. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  69245. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  69246. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  69247. }
  69248. };
  69249. /**
  69250. * Sets a new custom attenuation function for the sound.
  69251. * @param callback Defines the function used for the attenuation
  69252. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  69253. */
  69254. Sound.prototype.setAttenuationFunction = function (callback) {
  69255. this._customAttenuationFunction = callback;
  69256. };
  69257. /**
  69258. * Play the sound
  69259. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  69260. * @param offset (optional) Start the sound setting it at a specific time
  69261. */
  69262. Sound.prototype.play = function (time, offset) {
  69263. var _this = this;
  69264. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  69265. try {
  69266. if (this._startOffset < 0) {
  69267. time = -this._startOffset;
  69268. this._startOffset = 0;
  69269. }
  69270. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  69271. if (!this._soundSource || !this._streamingSource) {
  69272. if (this.spatialSound && this._soundPanner) {
  69273. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  69274. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  69275. }
  69276. if (this._isDirectional) {
  69277. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  69278. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  69279. this._soundPanner.coneOuterGain = this._coneOuterGain;
  69280. if (this._connectedMesh) {
  69281. this._updateDirection();
  69282. }
  69283. else {
  69284. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  69285. }
  69286. }
  69287. }
  69288. }
  69289. if (this._streaming) {
  69290. if (!this._streamingSource) {
  69291. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  69292. this._htmlAudioElement.onended = function () { _this._onended(); };
  69293. this._htmlAudioElement.playbackRate = this._playbackRate;
  69294. }
  69295. this._streamingSource.disconnect();
  69296. this._streamingSource.connect(this._inputAudioNode);
  69297. if (this._htmlAudioElement) {
  69298. // required to manage properly the new suspended default state of Chrome
  69299. // When the option 'streaming: true' is used, we need first to wait for
  69300. // the audio engine to be unlocked by a user gesture before trying to play
  69301. // an HTML Audio elememt
  69302. var tryToPlay = function () {
  69303. if (BABYLON.Engine.audioEngine.unlocked) {
  69304. var playPromise = _this._htmlAudioElement.play();
  69305. // In browsers that don’t yet support this functionality,
  69306. // playPromise won’t be defined.
  69307. if (playPromise !== undefined) {
  69308. playPromise.catch(function (error) {
  69309. // Automatic playback failed.
  69310. // Waiting for the audio engine to be unlocked by user click on unmute
  69311. BABYLON.Engine.audioEngine.lock();
  69312. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  69313. });
  69314. }
  69315. }
  69316. else {
  69317. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  69318. }
  69319. };
  69320. tryToPlay();
  69321. }
  69322. }
  69323. else {
  69324. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  69325. this._soundSource.buffer = this._audioBuffer;
  69326. this._soundSource.connect(this._inputAudioNode);
  69327. this._soundSource.loop = this.loop;
  69328. this._soundSource.playbackRate.value = this._playbackRate;
  69329. this._soundSource.onended = function () { _this._onended(); };
  69330. if (this._soundSource.buffer) {
  69331. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  69332. }
  69333. }
  69334. this._startTime = startTime;
  69335. this.isPlaying = true;
  69336. this.isPaused = false;
  69337. }
  69338. catch (ex) {
  69339. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  69340. }
  69341. }
  69342. };
  69343. Sound.prototype._onended = function () {
  69344. this.isPlaying = false;
  69345. if (this.onended) {
  69346. this.onended();
  69347. }
  69348. this.onEndedObservable.notifyObservers(this);
  69349. };
  69350. /**
  69351. * Stop the sound
  69352. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  69353. */
  69354. Sound.prototype.stop = function (time) {
  69355. if (this.isPlaying) {
  69356. if (this._streaming) {
  69357. if (this._htmlAudioElement) {
  69358. this._htmlAudioElement.pause();
  69359. // Test needed for Firefox or it will generate an Invalid State Error
  69360. if (this._htmlAudioElement.currentTime > 0) {
  69361. this._htmlAudioElement.currentTime = 0;
  69362. }
  69363. }
  69364. else {
  69365. this._streamingSource.disconnect();
  69366. }
  69367. }
  69368. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  69369. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  69370. this._soundSource.stop(stopTime);
  69371. this._soundSource.onended = function () { };
  69372. if (!this.isPaused) {
  69373. this._startOffset = 0;
  69374. }
  69375. }
  69376. this.isPlaying = false;
  69377. }
  69378. };
  69379. /**
  69380. * Put the sound in pause
  69381. */
  69382. Sound.prototype.pause = function () {
  69383. if (this.isPlaying) {
  69384. this.isPaused = true;
  69385. if (this._streaming) {
  69386. if (this._htmlAudioElement) {
  69387. this._htmlAudioElement.pause();
  69388. }
  69389. else {
  69390. this._streamingSource.disconnect();
  69391. }
  69392. }
  69393. else if (BABYLON.Engine.audioEngine.audioContext) {
  69394. this.stop(0);
  69395. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  69396. }
  69397. }
  69398. };
  69399. /**
  69400. * Sets a dedicated volume for this sounds
  69401. * @param newVolume Define the new volume of the sound
  69402. * @param time Define in how long the sound should be at this value
  69403. */
  69404. Sound.prototype.setVolume = function (newVolume, time) {
  69405. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  69406. if (time && BABYLON.Engine.audioEngine.audioContext) {
  69407. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  69408. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  69409. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  69410. }
  69411. else {
  69412. this._soundGain.gain.value = newVolume;
  69413. }
  69414. }
  69415. this._volume = newVolume;
  69416. };
  69417. /**
  69418. * Set the sound play back rate
  69419. * @param newPlaybackRate Define the playback rate the sound should be played at
  69420. */
  69421. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  69422. this._playbackRate = newPlaybackRate;
  69423. if (this.isPlaying) {
  69424. if (this._streaming && this._htmlAudioElement) {
  69425. this._htmlAudioElement.playbackRate = this._playbackRate;
  69426. }
  69427. else if (this._soundSource) {
  69428. this._soundSource.playbackRate.value = this._playbackRate;
  69429. }
  69430. }
  69431. };
  69432. /**
  69433. * Gets the volume of the sound.
  69434. * @returns the volume of the sound
  69435. */
  69436. Sound.prototype.getVolume = function () {
  69437. return this._volume;
  69438. };
  69439. /**
  69440. * Attach the sound to a dedicated mesh
  69441. * @param meshToConnectTo The mesh to connect the sound with
  69442. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  69443. */
  69444. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  69445. var _this = this;
  69446. if (this._connectedMesh && this._registerFunc) {
  69447. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  69448. this._registerFunc = null;
  69449. }
  69450. this._connectedMesh = meshToConnectTo;
  69451. if (!this.spatialSound) {
  69452. this.spatialSound = true;
  69453. this._createSpatialParameters();
  69454. if (this.isPlaying && this.loop) {
  69455. this.stop();
  69456. this.play();
  69457. }
  69458. }
  69459. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  69460. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  69461. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  69462. };
  69463. /**
  69464. * Detach the sound from the previously attached mesh
  69465. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  69466. */
  69467. Sound.prototype.detachFromMesh = function () {
  69468. if (this._connectedMesh && this._registerFunc) {
  69469. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  69470. this._registerFunc = null;
  69471. this._connectedMesh = null;
  69472. }
  69473. };
  69474. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  69475. if (!node.getBoundingInfo) {
  69476. return;
  69477. }
  69478. var mesh = node;
  69479. if (this._positionInEmitterSpace) {
  69480. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  69481. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  69482. }
  69483. else {
  69484. var boundingInfo = mesh.getBoundingInfo();
  69485. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  69486. }
  69487. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  69488. this._updateDirection();
  69489. }
  69490. };
  69491. /**
  69492. * Clone the current sound in the scene.
  69493. * @returns the new sound clone
  69494. */
  69495. Sound.prototype.clone = function () {
  69496. var _this = this;
  69497. if (!this._streaming) {
  69498. var setBufferAndRun = function () {
  69499. if (_this._isReadyToPlay) {
  69500. clonedSound._audioBuffer = _this.getAudioBuffer();
  69501. clonedSound._isReadyToPlay = true;
  69502. if (clonedSound.autoplay) {
  69503. clonedSound.play();
  69504. }
  69505. }
  69506. else {
  69507. window.setTimeout(setBufferAndRun, 300);
  69508. }
  69509. };
  69510. var currentOptions = {
  69511. autoplay: this.autoplay, loop: this.loop,
  69512. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  69513. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  69514. refDistance: this.refDistance, distanceModel: this.distanceModel
  69515. };
  69516. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  69517. if (this.useCustomAttenuation) {
  69518. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  69519. }
  69520. clonedSound.setPosition(this._position);
  69521. clonedSound.setPlaybackRate(this._playbackRate);
  69522. setBufferAndRun();
  69523. return clonedSound;
  69524. }
  69525. // Can't clone a streaming sound
  69526. else {
  69527. return null;
  69528. }
  69529. };
  69530. /**
  69531. * Gets the current underlying audio buffer containing the data
  69532. * @returns the audio buffer
  69533. */
  69534. Sound.prototype.getAudioBuffer = function () {
  69535. return this._audioBuffer;
  69536. };
  69537. /**
  69538. * Serializes the Sound in a JSON representation
  69539. * @returns the JSON representation of the sound
  69540. */
  69541. Sound.prototype.serialize = function () {
  69542. var serializationObject = {
  69543. name: this.name,
  69544. url: this.name,
  69545. autoplay: this.autoplay,
  69546. loop: this.loop,
  69547. volume: this._volume,
  69548. spatialSound: this.spatialSound,
  69549. maxDistance: this.maxDistance,
  69550. rolloffFactor: this.rolloffFactor,
  69551. refDistance: this.refDistance,
  69552. distanceModel: this.distanceModel,
  69553. playbackRate: this._playbackRate,
  69554. panningModel: this._panningModel,
  69555. soundTrackId: this.soundTrackId
  69556. };
  69557. if (this.spatialSound) {
  69558. if (this._connectedMesh)
  69559. serializationObject.connectedMeshId = this._connectedMesh.id;
  69560. serializationObject.position = this._position.asArray();
  69561. serializationObject.refDistance = this.refDistance;
  69562. serializationObject.distanceModel = this.distanceModel;
  69563. serializationObject.isDirectional = this._isDirectional;
  69564. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  69565. serializationObject.coneInnerAngle = this._coneInnerAngle;
  69566. serializationObject.coneOuterAngle = this._coneOuterAngle;
  69567. serializationObject.coneOuterGain = this._coneOuterGain;
  69568. }
  69569. return serializationObject;
  69570. };
  69571. /**
  69572. * Parse a JSON representation of a sound to innstantiate in a given scene
  69573. * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method)
  69574. * @param scene Define the scene the new parsed sound should be created in
  69575. * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies
  69576. * @param sourceSound Define a cound place holder if do not need to instantiate a new one
  69577. * @returns the newly parsed sound
  69578. */
  69579. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  69580. var soundName = parsedSound.name;
  69581. var soundUrl;
  69582. if (parsedSound.url) {
  69583. soundUrl = rootUrl + parsedSound.url;
  69584. }
  69585. else {
  69586. soundUrl = rootUrl + soundName;
  69587. }
  69588. var options = {
  69589. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  69590. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  69591. rolloffFactor: parsedSound.rolloffFactor,
  69592. refDistance: parsedSound.refDistance,
  69593. distanceModel: parsedSound.distanceModel,
  69594. playbackRate: parsedSound.playbackRate
  69595. };
  69596. var newSound;
  69597. if (!sourceSound) {
  69598. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  69599. scene._addPendingData(newSound);
  69600. }
  69601. else {
  69602. var setBufferAndRun = function () {
  69603. if (sourceSound._isReadyToPlay) {
  69604. newSound._audioBuffer = sourceSound.getAudioBuffer();
  69605. newSound._isReadyToPlay = true;
  69606. if (newSound.autoplay) {
  69607. newSound.play();
  69608. }
  69609. }
  69610. else {
  69611. window.setTimeout(setBufferAndRun, 300);
  69612. }
  69613. };
  69614. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  69615. setBufferAndRun();
  69616. }
  69617. if (parsedSound.position) {
  69618. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  69619. newSound.setPosition(soundPosition);
  69620. }
  69621. if (parsedSound.isDirectional) {
  69622. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  69623. if (parsedSound.localDirectionToMesh) {
  69624. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  69625. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  69626. }
  69627. }
  69628. if (parsedSound.connectedMeshId) {
  69629. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  69630. if (connectedMesh) {
  69631. newSound.attachToMesh(connectedMesh);
  69632. }
  69633. }
  69634. return newSound;
  69635. };
  69636. return Sound;
  69637. }());
  69638. BABYLON.Sound = Sound;
  69639. })(BABYLON || (BABYLON = {}));
  69640. //# sourceMappingURL=babylon.sound.js.map
  69641. var BABYLON;
  69642. (function (BABYLON) {
  69643. /**
  69644. * It could be useful to isolate your music & sounds on several tracks to better manage volume on a grouped instance of sounds.
  69645. * It will be also used in a future release to apply effects on a specific track.
  69646. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  69647. */
  69648. var SoundTrack = /** @class */ (function () {
  69649. /**
  69650. * Creates a new sound track.
  69651. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  69652. * @param scene Define the scene the sound track belongs to
  69653. * @param options
  69654. */
  69655. function SoundTrack(scene, options) {
  69656. if (options === void 0) { options = {}; }
  69657. /**
  69658. * The unique identifier of the sound track in the scene.
  69659. */
  69660. this.id = -1;
  69661. this._isMainTrack = false;
  69662. this._isInitialized = false;
  69663. this._scene = scene;
  69664. this.soundCollection = new Array();
  69665. this._options = options;
  69666. if (!this._isMainTrack && this._scene.soundTracks) {
  69667. this._scene.soundTracks.push(this);
  69668. this.id = this._scene.soundTracks.length - 1;
  69669. }
  69670. }
  69671. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  69672. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  69673. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  69674. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  69675. if (this._options) {
  69676. if (this._options.volume) {
  69677. this._outputAudioNode.gain.value = this._options.volume;
  69678. }
  69679. if (this._options.mainTrack) {
  69680. this._isMainTrack = this._options.mainTrack;
  69681. }
  69682. }
  69683. this._isInitialized = true;
  69684. }
  69685. };
  69686. /**
  69687. * Release the sound track and its associated resources
  69688. */
  69689. SoundTrack.prototype.dispose = function () {
  69690. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  69691. if (this._connectedAnalyser) {
  69692. this._connectedAnalyser.stopDebugCanvas();
  69693. }
  69694. while (this.soundCollection.length) {
  69695. this.soundCollection[0].dispose();
  69696. }
  69697. if (this._outputAudioNode) {
  69698. this._outputAudioNode.disconnect();
  69699. }
  69700. this._outputAudioNode = null;
  69701. }
  69702. };
  69703. /**
  69704. * Adds a sound to this sound track
  69705. * @param sound define the cound to add
  69706. * @ignoreNaming
  69707. */
  69708. SoundTrack.prototype.AddSound = function (sound) {
  69709. if (!this._isInitialized) {
  69710. this._initializeSoundTrackAudioGraph();
  69711. }
  69712. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  69713. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  69714. }
  69715. if (sound.soundTrackId) {
  69716. if (sound.soundTrackId === -1) {
  69717. this._scene.mainSoundTrack.RemoveSound(sound);
  69718. }
  69719. else if (this._scene.soundTracks) {
  69720. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  69721. }
  69722. }
  69723. this.soundCollection.push(sound);
  69724. sound.soundTrackId = this.id;
  69725. };
  69726. /**
  69727. * Removes a sound to this sound track
  69728. * @param sound define the cound to remove
  69729. * @ignoreNaming
  69730. */
  69731. SoundTrack.prototype.RemoveSound = function (sound) {
  69732. var index = this.soundCollection.indexOf(sound);
  69733. if (index !== -1) {
  69734. this.soundCollection.splice(index, 1);
  69735. }
  69736. };
  69737. /**
  69738. * Set a global volume for the full sound track.
  69739. * @param newVolume Define the new volume of the sound track
  69740. */
  69741. SoundTrack.prototype.setVolume = function (newVolume) {
  69742. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  69743. this._outputAudioNode.gain.value = newVolume;
  69744. }
  69745. };
  69746. /**
  69747. * Switch the panning model to HRTF:
  69748. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  69749. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69750. */
  69751. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  69752. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69753. for (var i = 0; i < this.soundCollection.length; i++) {
  69754. this.soundCollection[i].switchPanningModelToHRTF();
  69755. }
  69756. }
  69757. };
  69758. /**
  69759. * Switch the panning model to Equal Power:
  69760. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  69761. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69762. */
  69763. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  69764. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69765. for (var i = 0; i < this.soundCollection.length; i++) {
  69766. this.soundCollection[i].switchPanningModelToEqualPower();
  69767. }
  69768. }
  69769. };
  69770. /**
  69771. * Connect the sound track to an audio analyser allowing some amazing
  69772. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  69773. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  69774. * @param analyser The analyser to connect to the engine
  69775. */
  69776. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  69777. if (this._connectedAnalyser) {
  69778. this._connectedAnalyser.stopDebugCanvas();
  69779. }
  69780. this._connectedAnalyser = analyser;
  69781. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  69782. this._outputAudioNode.disconnect();
  69783. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  69784. }
  69785. };
  69786. return SoundTrack;
  69787. }());
  69788. BABYLON.SoundTrack = SoundTrack;
  69789. })(BABYLON || (BABYLON = {}));
  69790. //# sourceMappingURL=babylon.soundtrack.js.map
  69791. var BABYLON;
  69792. (function (BABYLON) {
  69793. /**
  69794. * Class used to work with sound analyzer using fast fourier transform (FFT)
  69795. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  69796. */
  69797. var Analyser = /** @class */ (function () {
  69798. /**
  69799. * Creates a new analyser
  69800. * @param scene defines hosting scene
  69801. */
  69802. function Analyser(scene) {
  69803. /**
  69804. * Gets or sets the smoothing
  69805. * @ignorenaming
  69806. */
  69807. this.SMOOTHING = 0.75;
  69808. /**
  69809. * Gets or sets the FFT table size
  69810. * @ignorenaming
  69811. */
  69812. this.FFT_SIZE = 512;
  69813. /**
  69814. * Gets or sets the bar graph amplitude
  69815. * @ignorenaming
  69816. */
  69817. this.BARGRAPHAMPLITUDE = 256;
  69818. /**
  69819. * Gets or sets the position of the debug canvas
  69820. * @ignorenaming
  69821. */
  69822. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  69823. /**
  69824. * Gets or sets the debug canvas size
  69825. * @ignorenaming
  69826. */
  69827. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  69828. this._scene = scene;
  69829. this._audioEngine = BABYLON.Engine.audioEngine;
  69830. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  69831. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  69832. this._webAudioAnalyser.minDecibels = -140;
  69833. this._webAudioAnalyser.maxDecibels = 0;
  69834. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  69835. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  69836. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  69837. }
  69838. }
  69839. /**
  69840. * Get the number of data values you will have to play with for the visualization
  69841. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  69842. * @returns a number
  69843. */
  69844. Analyser.prototype.getFrequencyBinCount = function () {
  69845. if (this._audioEngine.canUseWebAudio) {
  69846. return this._webAudioAnalyser.frequencyBinCount;
  69847. }
  69848. else {
  69849. return 0;
  69850. }
  69851. };
  69852. /**
  69853. * Gets the current frequency data as a byte array
  69854. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  69855. * @returns a Uint8Array
  69856. */
  69857. Analyser.prototype.getByteFrequencyData = function () {
  69858. if (this._audioEngine.canUseWebAudio) {
  69859. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  69860. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  69861. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  69862. }
  69863. return this._byteFreqs;
  69864. };
  69865. /**
  69866. * Gets the current waveform as a byte array
  69867. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  69868. * @returns a Uint8Array
  69869. */
  69870. Analyser.prototype.getByteTimeDomainData = function () {
  69871. if (this._audioEngine.canUseWebAudio) {
  69872. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  69873. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  69874. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  69875. }
  69876. return this._byteTime;
  69877. };
  69878. /**
  69879. * Gets the current frequency data as a float array
  69880. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  69881. * @returns a Float32Array
  69882. */
  69883. Analyser.prototype.getFloatFrequencyData = function () {
  69884. if (this._audioEngine.canUseWebAudio) {
  69885. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  69886. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  69887. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  69888. }
  69889. return this._floatFreqs;
  69890. };
  69891. /**
  69892. * Renders the debug canvas
  69893. */
  69894. Analyser.prototype.drawDebugCanvas = function () {
  69895. var _this = this;
  69896. if (this._audioEngine.canUseWebAudio) {
  69897. if (!this._debugCanvas) {
  69898. this._debugCanvas = document.createElement("canvas");
  69899. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  69900. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  69901. this._debugCanvas.style.position = "absolute";
  69902. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  69903. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  69904. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  69905. document.body.appendChild(this._debugCanvas);
  69906. this._registerFunc = function () {
  69907. _this.drawDebugCanvas();
  69908. };
  69909. this._scene.registerBeforeRender(this._registerFunc);
  69910. }
  69911. if (this._registerFunc && this._debugCanvasContext) {
  69912. var workingArray = this.getByteFrequencyData();
  69913. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  69914. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  69915. // Draw the frequency domain chart.
  69916. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  69917. var value = workingArray[i];
  69918. var percent = value / this.BARGRAPHAMPLITUDE;
  69919. var height = this.DEBUGCANVASSIZE.height * percent;
  69920. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  69921. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  69922. var hue = i / this.getFrequencyBinCount() * 360;
  69923. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  69924. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  69925. }
  69926. }
  69927. }
  69928. };
  69929. /**
  69930. * Stops rendering the debug canvas and removes it
  69931. */
  69932. Analyser.prototype.stopDebugCanvas = function () {
  69933. if (this._debugCanvas) {
  69934. if (this._registerFunc) {
  69935. this._scene.unregisterBeforeRender(this._registerFunc);
  69936. this._registerFunc = null;
  69937. }
  69938. document.body.removeChild(this._debugCanvas);
  69939. this._debugCanvas = null;
  69940. this._debugCanvasContext = null;
  69941. }
  69942. };
  69943. /**
  69944. * Connects two audio nodes
  69945. * @param inputAudioNode defines first node to connect
  69946. * @param outputAudioNode defines second node to connect
  69947. */
  69948. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  69949. if (this._audioEngine.canUseWebAudio) {
  69950. inputAudioNode.connect(this._webAudioAnalyser);
  69951. this._webAudioAnalyser.connect(outputAudioNode);
  69952. }
  69953. };
  69954. /**
  69955. * Releases all associated resources
  69956. */
  69957. Analyser.prototype.dispose = function () {
  69958. if (this._audioEngine.canUseWebAudio) {
  69959. this._webAudioAnalyser.disconnect();
  69960. }
  69961. };
  69962. return Analyser;
  69963. }());
  69964. BABYLON.Analyser = Analyser;
  69965. })(BABYLON || (BABYLON = {}));
  69966. //# sourceMappingURL=babylon.analyser.js.map
  69967. var BABYLON;
  69968. (function (BABYLON) {
  69969. /**
  69970. * Wraps one or more Sound objects and selects one with random weight for playback.
  69971. */
  69972. var WeightedSound = /** @class */ (function () {
  69973. /**
  69974. * Creates a new WeightedSound from the list of sounds given.
  69975. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  69976. * @param sounds Array of Sounds that will be selected from.
  69977. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  69978. */
  69979. function WeightedSound(loop, sounds, weights) {
  69980. var _this = this;
  69981. /** When true a Sound will be selected and played when the current playing Sound completes. */
  69982. this.loop = false;
  69983. this._coneInnerAngle = 360;
  69984. this._coneOuterAngle = 360;
  69985. this._volume = 1;
  69986. /** A Sound is currently playing. */
  69987. this.isPlaying = false;
  69988. /** A Sound is currently paused. */
  69989. this.isPaused = false;
  69990. this._sounds = [];
  69991. this._weights = [];
  69992. if (sounds.length !== weights.length) {
  69993. throw new Error('Sounds length does not equal weights length');
  69994. }
  69995. this.loop = loop;
  69996. this._weights = weights;
  69997. // Normalize the weights
  69998. var weightSum = 0;
  69999. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  70000. var weight = weights_1[_i];
  70001. weightSum += weight;
  70002. }
  70003. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  70004. for (var i = 0; i < this._weights.length; i++) {
  70005. this._weights[i] *= invWeightSum;
  70006. }
  70007. this._sounds = sounds;
  70008. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  70009. var sound = _b[_a];
  70010. sound.onEndedObservable.add(function () { _this._onended(); });
  70011. }
  70012. }
  70013. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  70014. /**
  70015. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  70016. */
  70017. get: function () {
  70018. return this._coneInnerAngle;
  70019. },
  70020. /**
  70021. * The size of cone in degress for a directional sound in which there will be no attenuation.
  70022. */
  70023. set: function (value) {
  70024. if (value !== this._coneInnerAngle) {
  70025. if (this._coneOuterAngle < value) {
  70026. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  70027. return;
  70028. }
  70029. this._coneInnerAngle = value;
  70030. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  70031. var sound = _a[_i];
  70032. sound.directionalConeInnerAngle = value;
  70033. }
  70034. }
  70035. },
  70036. enumerable: true,
  70037. configurable: true
  70038. });
  70039. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  70040. /**
  70041. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  70042. * Listener angles between innerAngle and outerAngle will falloff linearly.
  70043. */
  70044. get: function () {
  70045. return this._coneOuterAngle;
  70046. },
  70047. /**
  70048. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  70049. * Listener angles between innerAngle and outerAngle will falloff linearly.
  70050. */
  70051. set: function (value) {
  70052. if (value !== this._coneOuterAngle) {
  70053. if (value < this._coneInnerAngle) {
  70054. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  70055. return;
  70056. }
  70057. this._coneOuterAngle = value;
  70058. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  70059. var sound = _a[_i];
  70060. sound.directionalConeOuterAngle = value;
  70061. }
  70062. }
  70063. },
  70064. enumerable: true,
  70065. configurable: true
  70066. });
  70067. Object.defineProperty(WeightedSound.prototype, "volume", {
  70068. /**
  70069. * Playback volume.
  70070. */
  70071. get: function () {
  70072. return this._volume;
  70073. },
  70074. /**
  70075. * Playback volume.
  70076. */
  70077. set: function (value) {
  70078. if (value !== this._volume) {
  70079. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  70080. var sound = _a[_i];
  70081. sound.setVolume(value);
  70082. }
  70083. }
  70084. },
  70085. enumerable: true,
  70086. configurable: true
  70087. });
  70088. WeightedSound.prototype._onended = function () {
  70089. if (this._currentIndex !== undefined) {
  70090. this._sounds[this._currentIndex].autoplay = false;
  70091. }
  70092. if (this.loop && this.isPlaying) {
  70093. this.play();
  70094. }
  70095. else {
  70096. this.isPlaying = false;
  70097. }
  70098. };
  70099. /**
  70100. * Suspend playback
  70101. */
  70102. WeightedSound.prototype.pause = function () {
  70103. this.isPaused = true;
  70104. if (this._currentIndex !== undefined) {
  70105. this._sounds[this._currentIndex].pause();
  70106. }
  70107. };
  70108. /**
  70109. * Stop playback
  70110. */
  70111. WeightedSound.prototype.stop = function () {
  70112. this.isPlaying = false;
  70113. if (this._currentIndex !== undefined) {
  70114. this._sounds[this._currentIndex].stop();
  70115. }
  70116. };
  70117. /**
  70118. * Start playback.
  70119. * @param startOffset Position the clip head at a specific time in seconds.
  70120. */
  70121. WeightedSound.prototype.play = function (startOffset) {
  70122. if (!this.isPaused) {
  70123. this.stop();
  70124. var randomValue = Math.random();
  70125. var total = 0;
  70126. for (var i = 0; i < this._weights.length; i++) {
  70127. total += this._weights[i];
  70128. if (randomValue <= total) {
  70129. this._currentIndex = i;
  70130. break;
  70131. }
  70132. }
  70133. }
  70134. var sound = this._sounds[this._currentIndex];
  70135. if (sound.isReady()) {
  70136. sound.play(0, this.isPaused ? undefined : startOffset);
  70137. }
  70138. else {
  70139. sound.autoplay = true;
  70140. }
  70141. this.isPlaying = true;
  70142. this.isPaused = false;
  70143. };
  70144. return WeightedSound;
  70145. }());
  70146. BABYLON.WeightedSound = WeightedSound;
  70147. })(BABYLON || (BABYLON = {}));
  70148. //# sourceMappingURL=babylon.weightedsound.js.map
  70149. var BABYLON;
  70150. (function (BABYLON) {
  70151. // Adds the parser to the scene parsers.
  70152. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
  70153. // TODO: add sound
  70154. var loadedSounds = [];
  70155. var loadedSound;
  70156. container.sounds = container.sounds || [];
  70157. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  70158. for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  70159. var parsedSound = parsedData.sounds[index];
  70160. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  70161. if (!parsedSound.url)
  70162. parsedSound.url = parsedSound.name;
  70163. if (!loadedSounds[parsedSound.url]) {
  70164. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  70165. loadedSounds[parsedSound.url] = loadedSound;
  70166. container.sounds.push(loadedSound);
  70167. }
  70168. else {
  70169. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  70170. }
  70171. }
  70172. else {
  70173. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  70174. }
  70175. }
  70176. }
  70177. loadedSounds = [];
  70178. });
  70179. Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
  70180. get: function () {
  70181. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70182. if (!compo) {
  70183. compo = new AudioSceneComponent(this);
  70184. this._addComponent(compo);
  70185. }
  70186. if (!this._mainSoundTrack) {
  70187. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  70188. }
  70189. return this._mainSoundTrack;
  70190. },
  70191. enumerable: true,
  70192. configurable: true
  70193. });
  70194. BABYLON.Scene.prototype.getSoundByName = function (name) {
  70195. var index;
  70196. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  70197. if (this.mainSoundTrack.soundCollection[index].name === name) {
  70198. return this.mainSoundTrack.soundCollection[index];
  70199. }
  70200. }
  70201. if (this.soundTracks) {
  70202. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  70203. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  70204. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  70205. return this.soundTracks[sdIndex].soundCollection[index];
  70206. }
  70207. }
  70208. }
  70209. }
  70210. return null;
  70211. };
  70212. Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
  70213. get: function () {
  70214. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70215. if (!compo) {
  70216. compo = new AudioSceneComponent(this);
  70217. this._addComponent(compo);
  70218. }
  70219. return compo.audioEnabled;
  70220. },
  70221. set: function (value) {
  70222. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70223. if (!compo) {
  70224. compo = new AudioSceneComponent(this);
  70225. this._addComponent(compo);
  70226. }
  70227. if (value) {
  70228. compo.enableAudio();
  70229. }
  70230. else {
  70231. compo.disableAudio();
  70232. }
  70233. },
  70234. enumerable: true,
  70235. configurable: true
  70236. });
  70237. Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
  70238. get: function () {
  70239. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70240. if (!compo) {
  70241. compo = new AudioSceneComponent(this);
  70242. this._addComponent(compo);
  70243. }
  70244. return compo.headphone;
  70245. },
  70246. set: function (value) {
  70247. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70248. if (!compo) {
  70249. compo = new AudioSceneComponent(this);
  70250. this._addComponent(compo);
  70251. }
  70252. if (value) {
  70253. compo.switchAudioModeForHeadphones();
  70254. }
  70255. else {
  70256. compo.switchAudioModeForNormalSpeakers();
  70257. }
  70258. },
  70259. enumerable: true,
  70260. configurable: true
  70261. });
  70262. /**
  70263. * Defines the sound scene component responsible to manage any sounds
  70264. * in a given scene.
  70265. */
  70266. var AudioSceneComponent = /** @class */ (function () {
  70267. /**
  70268. * Creates a new instance of the component for the given scene
  70269. * @param scene Defines the scene to register the component in
  70270. */
  70271. function AudioSceneComponent(scene) {
  70272. /**
  70273. * The component name helpfull to identify the component in the list of scene components.
  70274. */
  70275. this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
  70276. this._audioEnabled = true;
  70277. this._headphone = false;
  70278. this.scene = scene;
  70279. scene.soundTracks = new Array();
  70280. scene.sounds = new Array();
  70281. }
  70282. Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
  70283. /**
  70284. * Gets whether audio is enabled or not.
  70285. * Please use related enable/disable method to switch state.
  70286. */
  70287. get: function () {
  70288. return this._audioEnabled;
  70289. },
  70290. enumerable: true,
  70291. configurable: true
  70292. });
  70293. Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
  70294. /**
  70295. * Gets whether audio is outputing to headphone or not.
  70296. * Please use the according Switch methods to change output.
  70297. */
  70298. get: function () {
  70299. return this._headphone;
  70300. },
  70301. enumerable: true,
  70302. configurable: true
  70303. });
  70304. /**
  70305. * Registers the component in a given scene
  70306. */
  70307. AudioSceneComponent.prototype.register = function () {
  70308. this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  70309. };
  70310. /**
  70311. * Rebuilds the elements related to this component in case of
  70312. * context lost for instance.
  70313. */
  70314. AudioSceneComponent.prototype.rebuild = function () {
  70315. // Nothing to do here. (Not rendering related)
  70316. };
  70317. /**
  70318. * Serializes the component data to the specified json object
  70319. * @param serializationObject The object to serialize to
  70320. */
  70321. AudioSceneComponent.prototype.serialize = function (serializationObject) {
  70322. serializationObject.sounds = [];
  70323. if (this.scene.soundTracks) {
  70324. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  70325. var soundtrack = this.scene.soundTracks[index];
  70326. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  70327. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  70328. }
  70329. }
  70330. }
  70331. };
  70332. /**
  70333. * Adds all the element from the container to the scene
  70334. * @param container the container holding the elements
  70335. */
  70336. AudioSceneComponent.prototype.addFromContainer = function (container) {
  70337. var _this = this;
  70338. if (!container.sounds) {
  70339. return;
  70340. }
  70341. container.sounds.forEach(function (sound) {
  70342. sound.play();
  70343. sound.autoplay = true;
  70344. _this.scene.mainSoundTrack.AddSound(sound);
  70345. });
  70346. };
  70347. /**
  70348. * Removes all the elements in the container from the scene
  70349. * @param container contains the elements to remove
  70350. */
  70351. AudioSceneComponent.prototype.removeFromContainer = function (container) {
  70352. var _this = this;
  70353. if (!container.sounds) {
  70354. return;
  70355. }
  70356. container.sounds.forEach(function (sound) {
  70357. sound.stop();
  70358. sound.autoplay = false;
  70359. _this.scene.mainSoundTrack.RemoveSound(sound);
  70360. });
  70361. };
  70362. /**
  70363. * Disposes the component and the associated ressources.
  70364. */
  70365. AudioSceneComponent.prototype.dispose = function () {
  70366. var scene = this.scene;
  70367. if (scene._mainSoundTrack) {
  70368. scene.mainSoundTrack.dispose();
  70369. }
  70370. if (scene.soundTracks) {
  70371. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  70372. scene.soundTracks[scIndex].dispose();
  70373. }
  70374. }
  70375. };
  70376. /**
  70377. * Disables audio in the associated scene.
  70378. */
  70379. AudioSceneComponent.prototype.disableAudio = function () {
  70380. var scene = this.scene;
  70381. this._audioEnabled = false;
  70382. var i;
  70383. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  70384. scene.mainSoundTrack.soundCollection[i].pause();
  70385. }
  70386. if (scene.soundTracks) {
  70387. for (i = 0; i < scene.soundTracks.length; i++) {
  70388. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  70389. scene.soundTracks[i].soundCollection[j].pause();
  70390. }
  70391. }
  70392. }
  70393. };
  70394. /**
  70395. * Enables audio in the associated scene.
  70396. */
  70397. AudioSceneComponent.prototype.enableAudio = function () {
  70398. var scene = this.scene;
  70399. this._audioEnabled = true;
  70400. var i;
  70401. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  70402. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  70403. scene.mainSoundTrack.soundCollection[i].play();
  70404. }
  70405. }
  70406. if (scene.soundTracks) {
  70407. for (i = 0; i < scene.soundTracks.length; i++) {
  70408. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  70409. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  70410. scene.soundTracks[i].soundCollection[j].play();
  70411. }
  70412. }
  70413. }
  70414. }
  70415. };
  70416. /**
  70417. * Switch audio to headphone output.
  70418. */
  70419. AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
  70420. var scene = this.scene;
  70421. this._headphone = true;
  70422. scene.mainSoundTrack.switchPanningModelToHRTF();
  70423. if (scene.soundTracks) {
  70424. for (var i = 0; i < scene.soundTracks.length; i++) {
  70425. scene.soundTracks[i].switchPanningModelToHRTF();
  70426. }
  70427. }
  70428. };
  70429. /**
  70430. * Switch audio to normal speakers.
  70431. */
  70432. AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
  70433. var scene = this.scene;
  70434. this._headphone = false;
  70435. scene.mainSoundTrack.switchPanningModelToEqualPower();
  70436. if (scene.soundTracks) {
  70437. for (var i = 0; i < scene.soundTracks.length; i++) {
  70438. scene.soundTracks[i].switchPanningModelToEqualPower();
  70439. }
  70440. }
  70441. };
  70442. AudioSceneComponent.prototype._afterRender = function () {
  70443. var scene = this.scene;
  70444. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  70445. return;
  70446. }
  70447. var listeningCamera;
  70448. var audioEngine = BABYLON.Engine.audioEngine;
  70449. if (scene.activeCameras.length > 0) {
  70450. listeningCamera = scene.activeCameras[0];
  70451. }
  70452. else {
  70453. listeningCamera = scene.activeCamera;
  70454. }
  70455. if (listeningCamera && audioEngine.audioContext) {
  70456. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  70457. // for VR cameras
  70458. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  70459. listeningCamera = listeningCamera.rigCameras[0];
  70460. }
  70461. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  70462. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  70463. cameraDirection.normalize();
  70464. // To avoid some errors on GearVR
  70465. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  70466. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  70467. }
  70468. var i;
  70469. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  70470. var sound = scene.mainSoundTrack.soundCollection[i];
  70471. if (sound.useCustomAttenuation) {
  70472. sound.updateDistanceFromListener();
  70473. }
  70474. }
  70475. if (scene.soundTracks) {
  70476. for (i = 0; i < scene.soundTracks.length; i++) {
  70477. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  70478. sound = scene.soundTracks[i].soundCollection[j];
  70479. if (sound.useCustomAttenuation) {
  70480. sound.updateDistanceFromListener();
  70481. }
  70482. }
  70483. }
  70484. }
  70485. }
  70486. };
  70487. return AudioSceneComponent;
  70488. }());
  70489. BABYLON.AudioSceneComponent = AudioSceneComponent;
  70490. })(BABYLON || (BABYLON = {}));
  70491. //# sourceMappingURL=babylon.audioSceneComponent.js.map
  70492. var BABYLON;
  70493. (function (BABYLON) {
  70494. /**
  70495. * This defines an action helpful to play a defined sound on a triggered action.
  70496. */
  70497. var PlaySoundAction = /** @class */ (function (_super) {
  70498. __extends(PlaySoundAction, _super);
  70499. /**
  70500. * Instantiate the action
  70501. * @param triggerOptions defines the trigger options
  70502. * @param sound defines the sound to play
  70503. * @param condition defines the trigger related conditions
  70504. */
  70505. function PlaySoundAction(triggerOptions, sound, condition) {
  70506. var _this = _super.call(this, triggerOptions, condition) || this;
  70507. _this._sound = sound;
  70508. return _this;
  70509. }
  70510. /** @hidden */
  70511. PlaySoundAction.prototype._prepare = function () {
  70512. };
  70513. /**
  70514. * Execute the action and play the sound.
  70515. */
  70516. PlaySoundAction.prototype.execute = function () {
  70517. if (this._sound !== undefined)
  70518. this._sound.play();
  70519. };
  70520. /**
  70521. * Serializes the actions and its related information.
  70522. * @param parent defines the object to serialize in
  70523. * @returns the serialized object
  70524. */
  70525. PlaySoundAction.prototype.serialize = function (parent) {
  70526. return _super.prototype._serialize.call(this, {
  70527. name: "PlaySoundAction",
  70528. properties: [{ name: "sound", value: this._sound.name }]
  70529. }, parent);
  70530. };
  70531. return PlaySoundAction;
  70532. }(BABYLON.Action));
  70533. BABYLON.PlaySoundAction = PlaySoundAction;
  70534. /**
  70535. * This defines an action helpful to stop a defined sound on a triggered action.
  70536. */
  70537. var StopSoundAction = /** @class */ (function (_super) {
  70538. __extends(StopSoundAction, _super);
  70539. /**
  70540. * Instantiate the action
  70541. * @param triggerOptions defines the trigger options
  70542. * @param sound defines the sound to stop
  70543. * @param condition defines the trigger related conditions
  70544. */
  70545. function StopSoundAction(triggerOptions, sound, condition) {
  70546. var _this = _super.call(this, triggerOptions, condition) || this;
  70547. _this._sound = sound;
  70548. return _this;
  70549. }
  70550. /** @hidden */
  70551. StopSoundAction.prototype._prepare = function () {
  70552. };
  70553. /**
  70554. * Execute the action and stop the sound.
  70555. */
  70556. StopSoundAction.prototype.execute = function () {
  70557. if (this._sound !== undefined)
  70558. this._sound.stop();
  70559. };
  70560. /**
  70561. * Serializes the actions and its related information.
  70562. * @param parent defines the object to serialize in
  70563. * @returns the serialized object
  70564. */
  70565. StopSoundAction.prototype.serialize = function (parent) {
  70566. return _super.prototype._serialize.call(this, {
  70567. name: "StopSoundAction",
  70568. properties: [{ name: "sound", value: this._sound.name }]
  70569. }, parent);
  70570. };
  70571. return StopSoundAction;
  70572. }(BABYLON.Action));
  70573. BABYLON.StopSoundAction = StopSoundAction;
  70574. })(BABYLON || (BABYLON = {}));
  70575. //# sourceMappingURL=babylon.directAudioActions.js.map
  70576. var BABYLON;
  70577. (function (BABYLON) {
  70578. /**
  70579. * Class for creating a cube texture
  70580. */
  70581. var CubeTexture = /** @class */ (function (_super) {
  70582. __extends(CubeTexture, _super);
  70583. /**
  70584. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  70585. * as prefiltered data.
  70586. * @param rootUrl defines the url of the texture or the root name of the six images
  70587. * @param scene defines the scene the texture is attached to
  70588. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  70589. * @param noMipmap defines if mipmaps should be created or not
  70590. * @param files defines the six files to load for the different faces
  70591. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  70592. * @param onError defines a callback triggered in case of error during load
  70593. * @param format defines the internal format to use for the texture once loaded
  70594. * @param prefiltered defines whether or not the texture is created from prefiltered data
  70595. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  70596. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  70597. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  70598. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  70599. * @return the cube texture
  70600. */
  70601. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  70602. if (extensions === void 0) { extensions = null; }
  70603. if (noMipmap === void 0) { noMipmap = false; }
  70604. if (files === void 0) { files = null; }
  70605. if (onLoad === void 0) { onLoad = null; }
  70606. if (onError === void 0) { onError = null; }
  70607. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  70608. if (prefiltered === void 0) { prefiltered = false; }
  70609. if (forcedExtension === void 0) { forcedExtension = null; }
  70610. if (createPolynomials === void 0) { createPolynomials = false; }
  70611. if (lodScale === void 0) { lodScale = 0.8; }
  70612. if (lodOffset === void 0) { lodOffset = 0; }
  70613. var _this = _super.call(this, scene) || this;
  70614. /**
  70615. * Gets or sets the center of the bounding box associated with the cube texture.
  70616. * It must define where the camera used to render the texture was set
  70617. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  70618. */
  70619. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  70620. _this._rotationY = 0;
  70621. /** @hidden */
  70622. _this._prefiltered = false;
  70623. _this.name = rootUrl;
  70624. _this.url = rootUrl;
  70625. _this._noMipmap = noMipmap;
  70626. _this.hasAlpha = false;
  70627. _this._format = format;
  70628. _this.isCube = true;
  70629. _this._textureMatrix = BABYLON.Matrix.Identity();
  70630. _this._createPolynomials = createPolynomials;
  70631. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  70632. if (!rootUrl && !files) {
  70633. return _this;
  70634. }
  70635. var lastDot = rootUrl.lastIndexOf(".");
  70636. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  70637. var isDDS = (extension === ".dds");
  70638. var isEnv = (extension === ".env");
  70639. if (isEnv) {
  70640. _this.gammaSpace = false;
  70641. _this._prefiltered = false;
  70642. }
  70643. else {
  70644. _this._prefiltered = prefiltered;
  70645. if (prefiltered) {
  70646. _this.gammaSpace = false;
  70647. }
  70648. }
  70649. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  70650. if (!files) {
  70651. if (!isEnv && !isDDS && !extensions) {
  70652. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  70653. }
  70654. files = [];
  70655. if (extensions) {
  70656. for (var index = 0; index < extensions.length; index++) {
  70657. files.push(rootUrl + extensions[index]);
  70658. }
  70659. }
  70660. }
  70661. _this._files = files;
  70662. if (!_this._texture) {
  70663. if (!scene.useDelayedTextureLoading) {
  70664. if (prefiltered) {
  70665. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  70666. }
  70667. else {
  70668. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  70669. }
  70670. }
  70671. else {
  70672. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  70673. }
  70674. }
  70675. else if (onLoad) {
  70676. if (_this._texture.isReady) {
  70677. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  70678. }
  70679. else {
  70680. _this._texture.onLoadedObservable.add(onLoad);
  70681. }
  70682. }
  70683. return _this;
  70684. }
  70685. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  70686. /**
  70687. * Returns the bounding box size
  70688. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  70689. */
  70690. get: function () {
  70691. return this._boundingBoxSize;
  70692. },
  70693. /**
  70694. * Gets or sets the size of the bounding box associated with the cube texture
  70695. * When defined, the cubemap will switch to local mode
  70696. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  70697. * @example https://www.babylonjs-playground.com/#RNASML
  70698. */
  70699. set: function (value) {
  70700. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  70701. return;
  70702. }
  70703. this._boundingBoxSize = value;
  70704. var scene = this.getScene();
  70705. if (scene) {
  70706. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  70707. }
  70708. },
  70709. enumerable: true,
  70710. configurable: true
  70711. });
  70712. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  70713. /**
  70714. * Gets texture matrix rotation angle around Y axis radians.
  70715. */
  70716. get: function () {
  70717. return this._rotationY;
  70718. },
  70719. /**
  70720. * Sets texture matrix rotation angle around Y axis in radians.
  70721. */
  70722. set: function (value) {
  70723. this._rotationY = value;
  70724. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  70725. },
  70726. enumerable: true,
  70727. configurable: true
  70728. });
  70729. /**
  70730. * Creates a cube texture from an array of image urls
  70731. * @param files defines an array of image urls
  70732. * @param scene defines the hosting scene
  70733. * @param noMipmap specifies if mip maps are not used
  70734. * @returns a cube texture
  70735. */
  70736. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  70737. var rootUrlKey = "";
  70738. files.forEach(function (url) { return rootUrlKey += url; });
  70739. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  70740. };
  70741. /**
  70742. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  70743. * @param url defines the url of the prefiltered texture
  70744. * @param scene defines the scene the texture is attached to
  70745. * @param forcedExtension defines the extension of the file if different from the url
  70746. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  70747. * @return the prefiltered texture
  70748. */
  70749. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  70750. if (forcedExtension === void 0) { forcedExtension = null; }
  70751. if (createPolynomials === void 0) { createPolynomials = true; }
  70752. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  70753. };
  70754. /**
  70755. * Delays loading of the cube texture
  70756. */
  70757. CubeTexture.prototype.delayLoad = function () {
  70758. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  70759. return;
  70760. }
  70761. var scene = this.getScene();
  70762. if (!scene) {
  70763. return;
  70764. }
  70765. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  70766. this._texture = this._getFromCache(this.url, this._noMipmap);
  70767. if (!this._texture) {
  70768. if (this._prefiltered) {
  70769. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  70770. }
  70771. else {
  70772. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  70773. }
  70774. }
  70775. };
  70776. /**
  70777. * Returns the reflection texture matrix
  70778. * @returns the reflection texture matrix
  70779. */
  70780. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  70781. return this._textureMatrix;
  70782. };
  70783. /**
  70784. * Sets the reflection texture matrix
  70785. * @param value Reflection texture matrix
  70786. */
  70787. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  70788. this._textureMatrix = value;
  70789. };
  70790. /**
  70791. * Parses text to create a cube texture
  70792. * @param parsedTexture define the serialized text to read from
  70793. * @param scene defines the hosting scene
  70794. * @param rootUrl defines the root url of the cube texture
  70795. * @returns a cube texture
  70796. */
  70797. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  70798. var texture = BABYLON.SerializationHelper.Parse(function () {
  70799. var prefiltered = false;
  70800. if (parsedTexture.prefiltered) {
  70801. prefiltered = parsedTexture.prefiltered;
  70802. }
  70803. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  70804. }, parsedTexture, scene);
  70805. // Local Cubemaps
  70806. if (parsedTexture.boundingBoxPosition) {
  70807. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  70808. }
  70809. if (parsedTexture.boundingBoxSize) {
  70810. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  70811. }
  70812. // Animations
  70813. if (parsedTexture.animations) {
  70814. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  70815. var parsedAnimation = parsedTexture.animations[animationIndex];
  70816. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  70817. }
  70818. }
  70819. return texture;
  70820. };
  70821. /**
  70822. * Makes a clone, or deep copy, of the cube texture
  70823. * @returns a new cube texture
  70824. */
  70825. CubeTexture.prototype.clone = function () {
  70826. var _this = this;
  70827. return BABYLON.SerializationHelper.Clone(function () {
  70828. var scene = _this.getScene();
  70829. if (!scene) {
  70830. return _this;
  70831. }
  70832. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  70833. }, this);
  70834. };
  70835. __decorate([
  70836. BABYLON.serialize("rotationY")
  70837. ], CubeTexture.prototype, "rotationY", null);
  70838. return CubeTexture;
  70839. }(BABYLON.BaseTexture));
  70840. BABYLON.CubeTexture = CubeTexture;
  70841. })(BABYLON || (BABYLON = {}));
  70842. //# sourceMappingURL=babylon.cubeTexture.js.map
  70843. var BABYLON;
  70844. (function (BABYLON) {
  70845. /**
  70846. * Raw cube texture where the raw buffers are passed in
  70847. */
  70848. var RawCubeTexture = /** @class */ (function (_super) {
  70849. __extends(RawCubeTexture, _super);
  70850. /**
  70851. * Creates a cube texture where the raw buffers are passed in.
  70852. * @param scene defines the scene the texture is attached to
  70853. * @param data defines the array of data to use to create each face
  70854. * @param size defines the size of the textures
  70855. * @param format defines the format of the data
  70856. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  70857. * @param generateMipMaps defines if the engine should generate the mip levels
  70858. * @param invertY defines if data must be stored with Y axis inverted
  70859. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  70860. * @param compression defines the compression used (null by default)
  70861. */
  70862. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  70863. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  70864. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70865. if (generateMipMaps === void 0) { generateMipMaps = false; }
  70866. if (invertY === void 0) { invertY = false; }
  70867. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70868. if (compression === void 0) { compression = null; }
  70869. var _this = _super.call(this, "", scene) || this;
  70870. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  70871. return _this;
  70872. }
  70873. /**
  70874. * Updates the raw cube texture.
  70875. * @param data defines the data to store
  70876. * @param format defines the data format
  70877. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  70878. * @param invertY defines if data must be stored with Y axis inverted
  70879. * @param compression defines the compression used (null by default)
  70880. * @param level defines which level of the texture to update
  70881. */
  70882. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  70883. if (compression === void 0) { compression = null; }
  70884. if (level === void 0) { level = 0; }
  70885. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  70886. };
  70887. /**
  70888. * Updates a raw cube texture with RGBD encoded data.
  70889. * @param data defines the array of data [mipmap][face] to use to create each face
  70890. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  70891. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  70892. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  70893. * @returns a promsie that resolves when the operation is complete
  70894. */
  70895. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  70896. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  70897. if (lodScale === void 0) { lodScale = 0.8; }
  70898. if (lodOffset === void 0) { lodOffset = 0; }
  70899. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  70900. };
  70901. /**
  70902. * Clones the raw cube texture.
  70903. * @return a new cube texture
  70904. */
  70905. RawCubeTexture.prototype.clone = function () {
  70906. var _this = this;
  70907. return BABYLON.SerializationHelper.Clone(function () {
  70908. var scene = _this.getScene();
  70909. var internalTexture = _this._texture;
  70910. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  70911. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  70912. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  70913. }
  70914. return texture;
  70915. }, this);
  70916. };
  70917. /** @hidden */
  70918. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  70919. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  70920. internalTexture._bufferViewArrayArray = data;
  70921. internalTexture._lodGenerationScale = lodScale;
  70922. internalTexture._lodGenerationOffset = lodOffset;
  70923. internalTexture._sphericalPolynomial = sphericalPolynomial;
  70924. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  70925. internalTexture.isReady = true;
  70926. });
  70927. };
  70928. return RawCubeTexture;
  70929. }(BABYLON.CubeTexture));
  70930. BABYLON.RawCubeTexture = RawCubeTexture;
  70931. })(BABYLON || (BABYLON = {}));
  70932. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  70933. var BABYLON;
  70934. (function (BABYLON) {
  70935. var RenderTargetTexture = /** @class */ (function (_super) {
  70936. __extends(RenderTargetTexture, _super);
  70937. /**
  70938. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  70939. * or used a shadow, depth texture...
  70940. * @param name The friendly name of the texture
  70941. * @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)
  70942. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  70943. * @param generateMipMaps True if mip maps need to be generated after render.
  70944. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  70945. * @param type The type of the buffer in the RTT (int, half float, float...)
  70946. * @param isCube True if a cube texture needs to be created
  70947. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  70948. * @param generateDepthBuffer True to generate a depth buffer
  70949. * @param generateStencilBuffer True to generate a stencil buffer
  70950. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  70951. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  70952. */
  70953. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  70954. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  70955. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70956. if (isCube === void 0) { isCube = false; }
  70957. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70958. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  70959. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  70960. if (isMulti === void 0) { isMulti = false; }
  70961. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  70962. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  70963. _this.isCube = isCube;
  70964. _this.renderParticles = true;
  70965. _this.renderSprites = false;
  70966. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  70967. _this.ignoreCameraViewport = false;
  70968. // Events
  70969. /**
  70970. * An event triggered when the texture is unbind.
  70971. */
  70972. _this.onBeforeBindObservable = new BABYLON.Observable();
  70973. /**
  70974. * An event triggered when the texture is unbind.
  70975. */
  70976. _this.onAfterUnbindObservable = new BABYLON.Observable();
  70977. /**
  70978. * An event triggered before rendering the texture
  70979. */
  70980. _this.onBeforeRenderObservable = new BABYLON.Observable();
  70981. /**
  70982. * An event triggered after rendering the texture
  70983. */
  70984. _this.onAfterRenderObservable = new BABYLON.Observable();
  70985. /**
  70986. * An event triggered after the texture clear
  70987. */
  70988. _this.onClearObservable = new BABYLON.Observable();
  70989. _this._currentRefreshId = -1;
  70990. _this._refreshRate = 1;
  70991. _this._samples = 1;
  70992. /**
  70993. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  70994. * It must define where the camera used to render the texture is set
  70995. */
  70996. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  70997. scene = _this.getScene();
  70998. if (!scene) {
  70999. return _this;
  71000. }
  71001. _this.renderList = new Array();
  71002. _this._engine = scene.getEngine();
  71003. _this.name = name;
  71004. _this.isRenderTarget = true;
  71005. _this._initialSizeParameter = size;
  71006. _this._processSizeParameter(size);
  71007. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  71008. });
  71009. _this._generateMipMaps = generateMipMaps ? true : false;
  71010. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  71011. // Rendering groups
  71012. _this._renderingManager = new BABYLON.RenderingManager(scene);
  71013. _this._renderingManager._useSceneAutoClearSetup = true;
  71014. if (isMulti) {
  71015. return _this;
  71016. }
  71017. _this._renderTargetOptions = {
  71018. generateMipMaps: generateMipMaps,
  71019. type: type,
  71020. format: format,
  71021. samplingMode: samplingMode,
  71022. generateDepthBuffer: generateDepthBuffer,
  71023. generateStencilBuffer: generateStencilBuffer
  71024. };
  71025. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  71026. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71027. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71028. }
  71029. if (isCube) {
  71030. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  71031. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  71032. _this._textureMatrix = BABYLON.Matrix.Identity();
  71033. }
  71034. else {
  71035. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  71036. }
  71037. return _this;
  71038. }
  71039. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  71040. get: function () {
  71041. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  71042. },
  71043. enumerable: true,
  71044. configurable: true
  71045. });
  71046. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  71047. get: function () {
  71048. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  71049. },
  71050. enumerable: true,
  71051. configurable: true
  71052. });
  71053. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  71054. get: function () {
  71055. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  71056. },
  71057. enumerable: true,
  71058. configurable: true
  71059. });
  71060. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  71061. /**
  71062. * Use this list to define the list of mesh you want to render.
  71063. */
  71064. get: function () {
  71065. return this._renderList;
  71066. },
  71067. set: function (value) {
  71068. this._renderList = value;
  71069. if (this._renderList) {
  71070. this._hookArray(this._renderList);
  71071. }
  71072. },
  71073. enumerable: true,
  71074. configurable: true
  71075. });
  71076. RenderTargetTexture.prototype._hookArray = function (array) {
  71077. var _this = this;
  71078. var oldPush = array.push;
  71079. array.push = function () {
  71080. var items = [];
  71081. for (var _i = 0; _i < arguments.length; _i++) {
  71082. items[_i] = arguments[_i];
  71083. }
  71084. var wasEmpty = array.length === 0;
  71085. var result = oldPush.apply(array, items);
  71086. if (wasEmpty) {
  71087. _this.getScene().meshes.forEach(function (mesh) {
  71088. mesh._markSubMeshesAsLightDirty();
  71089. });
  71090. }
  71091. return result;
  71092. };
  71093. var oldSplice = array.splice;
  71094. array.splice = function (index, deleteCount) {
  71095. var deleted = oldSplice.apply(array, [index, deleteCount]);
  71096. if (array.length === 0) {
  71097. _this.getScene().meshes.forEach(function (mesh) {
  71098. mesh._markSubMeshesAsLightDirty();
  71099. });
  71100. }
  71101. return deleted;
  71102. };
  71103. };
  71104. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  71105. set: function (callback) {
  71106. if (this._onAfterUnbindObserver) {
  71107. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  71108. }
  71109. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  71110. },
  71111. enumerable: true,
  71112. configurable: true
  71113. });
  71114. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  71115. set: function (callback) {
  71116. if (this._onBeforeRenderObserver) {
  71117. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  71118. }
  71119. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  71120. },
  71121. enumerable: true,
  71122. configurable: true
  71123. });
  71124. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  71125. set: function (callback) {
  71126. if (this._onAfterRenderObserver) {
  71127. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  71128. }
  71129. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  71130. },
  71131. enumerable: true,
  71132. configurable: true
  71133. });
  71134. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  71135. set: function (callback) {
  71136. if (this._onClearObserver) {
  71137. this.onClearObservable.remove(this._onClearObserver);
  71138. }
  71139. this._onClearObserver = this.onClearObservable.add(callback);
  71140. },
  71141. enumerable: true,
  71142. configurable: true
  71143. });
  71144. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  71145. get: function () {
  71146. return this._renderTargetOptions;
  71147. },
  71148. enumerable: true,
  71149. configurable: true
  71150. });
  71151. RenderTargetTexture.prototype._onRatioRescale = function () {
  71152. if (this._sizeRatio) {
  71153. this.resize(this._initialSizeParameter);
  71154. }
  71155. };
  71156. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  71157. get: function () {
  71158. return this._boundingBoxSize;
  71159. },
  71160. /**
  71161. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  71162. * When defined, the cubemap will switch to local mode
  71163. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  71164. * @example https://www.babylonjs-playground.com/#RNASML
  71165. */
  71166. set: function (value) {
  71167. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  71168. return;
  71169. }
  71170. this._boundingBoxSize = value;
  71171. var scene = this.getScene();
  71172. if (scene) {
  71173. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  71174. }
  71175. },
  71176. enumerable: true,
  71177. configurable: true
  71178. });
  71179. /**
  71180. * Creates a depth stencil texture.
  71181. * This is only available in WebGL 2 or with the depth texture extension available.
  71182. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  71183. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  71184. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  71185. */
  71186. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  71187. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  71188. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  71189. if (generateStencil === void 0) { generateStencil = false; }
  71190. if (!this.getScene()) {
  71191. return;
  71192. }
  71193. var engine = this.getScene().getEngine();
  71194. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  71195. bilinearFiltering: bilinearFiltering,
  71196. comparisonFunction: comparisonFunction,
  71197. generateStencil: generateStencil,
  71198. isCube: this.isCube
  71199. });
  71200. engine.setFrameBufferDepthStencilTexture(this);
  71201. };
  71202. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  71203. if (size.ratio) {
  71204. this._sizeRatio = size.ratio;
  71205. this._size = {
  71206. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  71207. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  71208. };
  71209. }
  71210. else {
  71211. this._size = size;
  71212. }
  71213. };
  71214. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  71215. get: function () {
  71216. return this._samples;
  71217. },
  71218. set: function (value) {
  71219. if (this._samples === value) {
  71220. return;
  71221. }
  71222. var scene = this.getScene();
  71223. if (!scene) {
  71224. return;
  71225. }
  71226. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  71227. },
  71228. enumerable: true,
  71229. configurable: true
  71230. });
  71231. /**
  71232. * Resets the refresh counter of the texture and start bak from scratch.
  71233. * Could be usefull to regenerate the texture if it is setup to render only once.
  71234. */
  71235. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  71236. this._currentRefreshId = -1;
  71237. };
  71238. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  71239. /**
  71240. * Define the refresh rate of the texture or the rendering frequency.
  71241. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  71242. */
  71243. get: function () {
  71244. return this._refreshRate;
  71245. },
  71246. set: function (value) {
  71247. this._refreshRate = value;
  71248. this.resetRefreshCounter();
  71249. },
  71250. enumerable: true,
  71251. configurable: true
  71252. });
  71253. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  71254. if (!this._postProcessManager) {
  71255. var scene = this.getScene();
  71256. if (!scene) {
  71257. return;
  71258. }
  71259. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  71260. this._postProcesses = new Array();
  71261. }
  71262. this._postProcesses.push(postProcess);
  71263. this._postProcesses[0].autoClear = false;
  71264. };
  71265. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  71266. if (!this._postProcesses) {
  71267. return;
  71268. }
  71269. if (dispose) {
  71270. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  71271. var postProcess = _a[_i];
  71272. postProcess.dispose();
  71273. }
  71274. }
  71275. this._postProcesses = [];
  71276. };
  71277. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  71278. if (!this._postProcesses) {
  71279. return;
  71280. }
  71281. var index = this._postProcesses.indexOf(postProcess);
  71282. if (index === -1) {
  71283. return;
  71284. }
  71285. this._postProcesses.splice(index, 1);
  71286. if (this._postProcesses.length > 0) {
  71287. this._postProcesses[0].autoClear = false;
  71288. }
  71289. };
  71290. /** @hidden */
  71291. RenderTargetTexture.prototype._shouldRender = function () {
  71292. if (this._currentRefreshId === -1) { // At least render once
  71293. this._currentRefreshId = 1;
  71294. return true;
  71295. }
  71296. if (this.refreshRate === this._currentRefreshId) {
  71297. this._currentRefreshId = 1;
  71298. return true;
  71299. }
  71300. this._currentRefreshId++;
  71301. return false;
  71302. };
  71303. RenderTargetTexture.prototype.getRenderSize = function () {
  71304. if (this._size.width) {
  71305. return this._size.width;
  71306. }
  71307. return this._size;
  71308. };
  71309. RenderTargetTexture.prototype.getRenderWidth = function () {
  71310. if (this._size.width) {
  71311. return this._size.width;
  71312. }
  71313. return this._size;
  71314. };
  71315. RenderTargetTexture.prototype.getRenderHeight = function () {
  71316. if (this._size.width) {
  71317. return this._size.height;
  71318. }
  71319. return this._size;
  71320. };
  71321. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  71322. get: function () {
  71323. return true;
  71324. },
  71325. enumerable: true,
  71326. configurable: true
  71327. });
  71328. RenderTargetTexture.prototype.scale = function (ratio) {
  71329. var newSize = this.getRenderSize() * ratio;
  71330. this.resize(newSize);
  71331. };
  71332. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  71333. if (this.isCube) {
  71334. return this._textureMatrix;
  71335. }
  71336. return _super.prototype.getReflectionTextureMatrix.call(this);
  71337. };
  71338. RenderTargetTexture.prototype.resize = function (size) {
  71339. this.releaseInternalTexture();
  71340. var scene = this.getScene();
  71341. if (!scene) {
  71342. return;
  71343. }
  71344. this._processSizeParameter(size);
  71345. if (this.isCube) {
  71346. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  71347. }
  71348. else {
  71349. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  71350. }
  71351. };
  71352. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  71353. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  71354. if (dumpForDebug === void 0) { dumpForDebug = false; }
  71355. var scene = this.getScene();
  71356. if (!scene) {
  71357. return;
  71358. }
  71359. var engine = scene.getEngine();
  71360. if (this.useCameraPostProcesses !== undefined) {
  71361. useCameraPostProcess = this.useCameraPostProcesses;
  71362. }
  71363. if (this._waitingRenderList) {
  71364. this.renderList = [];
  71365. for (var index = 0; index < this._waitingRenderList.length; index++) {
  71366. var id = this._waitingRenderList[index];
  71367. var mesh_1 = scene.getMeshByID(id);
  71368. if (mesh_1) {
  71369. this.renderList.push(mesh_1);
  71370. }
  71371. }
  71372. delete this._waitingRenderList;
  71373. }
  71374. // Is predicate defined?
  71375. if (this.renderListPredicate) {
  71376. if (this.renderList) {
  71377. this.renderList.splice(0); // Clear previous renderList
  71378. }
  71379. else {
  71380. this.renderList = [];
  71381. }
  71382. var scene = this.getScene();
  71383. if (!scene) {
  71384. return;
  71385. }
  71386. var sceneMeshes = scene.meshes;
  71387. for (var index = 0; index < sceneMeshes.length; index++) {
  71388. var mesh = sceneMeshes[index];
  71389. if (this.renderListPredicate(mesh)) {
  71390. this.renderList.push(mesh);
  71391. }
  71392. }
  71393. }
  71394. this.onBeforeBindObservable.notifyObservers(this);
  71395. // Set custom projection.
  71396. // Needs to be before binding to prevent changing the aspect ratio.
  71397. var camera;
  71398. if (this.activeCamera) {
  71399. camera = this.activeCamera;
  71400. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  71401. if (this.activeCamera !== scene.activeCamera) {
  71402. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  71403. }
  71404. }
  71405. else {
  71406. camera = scene.activeCamera;
  71407. if (camera) {
  71408. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  71409. }
  71410. }
  71411. // Prepare renderingManager
  71412. this._renderingManager.reset();
  71413. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  71414. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  71415. var sceneRenderId = scene.getRenderId();
  71416. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  71417. var mesh = currentRenderList[meshIndex];
  71418. if (mesh) {
  71419. if (!mesh.isReady(this.refreshRate === 0)) {
  71420. this.resetRefreshCounter();
  71421. continue;
  71422. }
  71423. mesh._preActivateForIntermediateRendering(sceneRenderId);
  71424. var isMasked = void 0;
  71425. if (!this.renderList && camera) {
  71426. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  71427. }
  71428. else {
  71429. isMasked = false;
  71430. }
  71431. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  71432. mesh._activate(sceneRenderId);
  71433. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  71434. var subMesh = mesh.subMeshes[subIndex];
  71435. scene._activeIndices.addCount(subMesh.indexCount, false);
  71436. this._renderingManager.dispatch(subMesh, mesh);
  71437. }
  71438. }
  71439. }
  71440. }
  71441. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  71442. var particleSystem = scene.particleSystems[particleIndex];
  71443. var emitter = particleSystem.emitter;
  71444. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  71445. continue;
  71446. }
  71447. if (currentRenderList.indexOf(emitter) >= 0) {
  71448. this._renderingManager.dispatchParticles(particleSystem);
  71449. }
  71450. }
  71451. if (this.isCube) {
  71452. for (var face = 0; face < 6; face++) {
  71453. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  71454. scene.incrementRenderId();
  71455. scene.resetCachedMaterial();
  71456. }
  71457. }
  71458. else {
  71459. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  71460. }
  71461. this.onAfterUnbindObservable.notifyObservers(this);
  71462. if (scene.activeCamera) {
  71463. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  71464. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  71465. }
  71466. engine.setViewport(scene.activeCamera.viewport);
  71467. }
  71468. scene.resetCachedMaterial();
  71469. };
  71470. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  71471. var minimum = 128;
  71472. var x = renderDimension * scale;
  71473. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  71474. // Ensure we don't exceed the render dimension (while staying POT)
  71475. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  71476. };
  71477. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  71478. var _this = this;
  71479. if (!this._texture) {
  71480. return;
  71481. }
  71482. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  71483. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  71484. });
  71485. };
  71486. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  71487. var scene = this.getScene();
  71488. if (!scene) {
  71489. return;
  71490. }
  71491. var engine = scene.getEngine();
  71492. if (!this._texture) {
  71493. return;
  71494. }
  71495. // Bind
  71496. if (this._postProcessManager) {
  71497. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  71498. }
  71499. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  71500. if (this._texture) {
  71501. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  71502. }
  71503. }
  71504. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  71505. // Clear
  71506. if (this.onClearObservable.hasObservers()) {
  71507. this.onClearObservable.notifyObservers(engine);
  71508. }
  71509. else {
  71510. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  71511. }
  71512. if (!this._doNotChangeAspectRatio) {
  71513. scene.updateTransformMatrix(true);
  71514. }
  71515. // Render
  71516. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  71517. if (this._postProcessManager) {
  71518. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  71519. }
  71520. else if (useCameraPostProcess) {
  71521. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  71522. }
  71523. if (!this._doNotChangeAspectRatio) {
  71524. scene.updateTransformMatrix(true);
  71525. }
  71526. // Dump ?
  71527. if (dumpForDebug) {
  71528. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  71529. }
  71530. // Unbind
  71531. if (!this.isCube || faceIndex === 5) {
  71532. if (this.isCube) {
  71533. if (faceIndex === 5) {
  71534. engine.generateMipMapsForCubemap(this._texture);
  71535. }
  71536. }
  71537. this.unbindFrameBuffer(engine, faceIndex);
  71538. }
  71539. else {
  71540. this.onAfterRenderObservable.notifyObservers(faceIndex);
  71541. }
  71542. };
  71543. /**
  71544. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  71545. * This allowed control for front to back rendering or reversly depending of the special needs.
  71546. *
  71547. * @param renderingGroupId The rendering group id corresponding to its index
  71548. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  71549. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  71550. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  71551. */
  71552. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  71553. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  71554. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  71555. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  71556. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  71557. };
  71558. /**
  71559. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  71560. *
  71561. * @param renderingGroupId The rendering group id corresponding to its index
  71562. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  71563. */
  71564. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  71565. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  71566. this._renderingManager._useSceneAutoClearSetup = false;
  71567. };
  71568. RenderTargetTexture.prototype.clone = function () {
  71569. var textureSize = this.getSize();
  71570. 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);
  71571. // Base texture
  71572. newTexture.hasAlpha = this.hasAlpha;
  71573. newTexture.level = this.level;
  71574. // RenderTarget Texture
  71575. newTexture.coordinatesMode = this.coordinatesMode;
  71576. if (this.renderList) {
  71577. newTexture.renderList = this.renderList.slice(0);
  71578. }
  71579. return newTexture;
  71580. };
  71581. RenderTargetTexture.prototype.serialize = function () {
  71582. if (!this.name) {
  71583. return null;
  71584. }
  71585. var serializationObject = _super.prototype.serialize.call(this);
  71586. serializationObject.renderTargetSize = this.getRenderSize();
  71587. serializationObject.renderList = [];
  71588. if (this.renderList) {
  71589. for (var index = 0; index < this.renderList.length; index++) {
  71590. serializationObject.renderList.push(this.renderList[index].id);
  71591. }
  71592. }
  71593. return serializationObject;
  71594. };
  71595. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  71596. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  71597. var objBuffer = this.getInternalTexture();
  71598. var scene = this.getScene();
  71599. if (objBuffer && scene) {
  71600. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  71601. }
  71602. };
  71603. RenderTargetTexture.prototype.dispose = function () {
  71604. if (this._postProcessManager) {
  71605. this._postProcessManager.dispose();
  71606. this._postProcessManager = null;
  71607. }
  71608. this.clearPostProcesses(true);
  71609. if (this._resizeObserver) {
  71610. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  71611. this._resizeObserver = null;
  71612. }
  71613. this.renderList = null;
  71614. // Remove from custom render targets
  71615. var scene = this.getScene();
  71616. if (!scene) {
  71617. return;
  71618. }
  71619. var index = scene.customRenderTargets.indexOf(this);
  71620. if (index >= 0) {
  71621. scene.customRenderTargets.splice(index, 1);
  71622. }
  71623. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  71624. var camera = _a[_i];
  71625. index = camera.customRenderTargets.indexOf(this);
  71626. if (index >= 0) {
  71627. camera.customRenderTargets.splice(index, 1);
  71628. }
  71629. }
  71630. _super.prototype.dispose.call(this);
  71631. };
  71632. /** @hidden */
  71633. RenderTargetTexture.prototype._rebuild = function () {
  71634. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  71635. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  71636. }
  71637. if (this._postProcessManager) {
  71638. this._postProcessManager._rebuild();
  71639. }
  71640. };
  71641. /**
  71642. * Clear the info related to rendering groups preventing retention point in material dispose.
  71643. */
  71644. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  71645. if (this._renderingManager) {
  71646. this._renderingManager.freeRenderingGroups();
  71647. }
  71648. };
  71649. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  71650. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  71651. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  71652. return RenderTargetTexture;
  71653. }(BABYLON.Texture));
  71654. BABYLON.RenderTargetTexture = RenderTargetTexture;
  71655. })(BABYLON || (BABYLON = {}));
  71656. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  71657. var BABYLON;
  71658. (function (BABYLON) {
  71659. ;
  71660. /**
  71661. * A multi render target, like a render target provides the ability to render to a texture.
  71662. * Unlike the render target, it can render to several draw buffers in one draw.
  71663. * This is specially interesting in deferred rendering or for any effects requiring more than
  71664. * just one color from a single pass.
  71665. */
  71666. var MultiRenderTarget = /** @class */ (function (_super) {
  71667. __extends(MultiRenderTarget, _super);
  71668. /**
  71669. * Instantiate a new multi render target texture.
  71670. * A multi render target, like a render target provides the ability to render to a texture.
  71671. * Unlike the render target, it can render to several draw buffers in one draw.
  71672. * This is specially interesting in deferred rendering or for any effects requiring more than
  71673. * just one color from a single pass.
  71674. * @param name Define the name of the texture
  71675. * @param size Define the size of the buffers to render to
  71676. * @param count Define the number of target we are rendering into
  71677. * @param scene Define the scene the texture belongs to
  71678. * @param options Define the options used to create the multi render target
  71679. */
  71680. function MultiRenderTarget(name, size, count, scene, options) {
  71681. var _this = this;
  71682. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  71683. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  71684. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  71685. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  71686. _this._engine = scene.getEngine();
  71687. if (!_this.isSupported) {
  71688. _this.dispose();
  71689. return;
  71690. }
  71691. var types = [];
  71692. var samplingModes = [];
  71693. for (var i = 0; i < count; i++) {
  71694. if (options && options.types && options.types[i] !== undefined) {
  71695. types.push(options.types[i]);
  71696. }
  71697. else {
  71698. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71699. }
  71700. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  71701. samplingModes.push(options.samplingModes[i]);
  71702. }
  71703. else {
  71704. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  71705. }
  71706. }
  71707. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  71708. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  71709. _this._size = size;
  71710. _this._multiRenderTargetOptions = {
  71711. samplingModes: samplingModes,
  71712. generateMipMaps: generateMipMaps,
  71713. generateDepthBuffer: generateDepthBuffer,
  71714. generateStencilBuffer: generateStencilBuffer,
  71715. generateDepthTexture: generateDepthTexture,
  71716. types: types,
  71717. textureCount: count
  71718. };
  71719. _this._createInternalTextures();
  71720. _this._createTextures();
  71721. return _this;
  71722. }
  71723. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  71724. /**
  71725. * Get if draw buffers are currently supported by the used hardware and browser.
  71726. */
  71727. get: function () {
  71728. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  71729. },
  71730. enumerable: true,
  71731. configurable: true
  71732. });
  71733. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  71734. /**
  71735. * Get the list of textures generated by the multi render target.
  71736. */
  71737. get: function () {
  71738. return this._textures;
  71739. },
  71740. enumerable: true,
  71741. configurable: true
  71742. });
  71743. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  71744. /**
  71745. * Get the depth texture generated by the multi render target if options.generateDepthTexture has been set
  71746. */
  71747. get: function () {
  71748. return this._textures[this._textures.length - 1];
  71749. },
  71750. enumerable: true,
  71751. configurable: true
  71752. });
  71753. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  71754. /**
  71755. * Set the wrapping mode on U of all the textures we are rendering to.
  71756. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  71757. */
  71758. set: function (wrap) {
  71759. if (this._textures) {
  71760. for (var i = 0; i < this._textures.length; i++) {
  71761. this._textures[i].wrapU = wrap;
  71762. }
  71763. }
  71764. },
  71765. enumerable: true,
  71766. configurable: true
  71767. });
  71768. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  71769. /**
  71770. * Set the wrapping mode on V of all the textures we are rendering to.
  71771. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  71772. */
  71773. set: function (wrap) {
  71774. if (this._textures) {
  71775. for (var i = 0; i < this._textures.length; i++) {
  71776. this._textures[i].wrapV = wrap;
  71777. }
  71778. }
  71779. },
  71780. enumerable: true,
  71781. configurable: true
  71782. });
  71783. /** @hidden */
  71784. MultiRenderTarget.prototype._rebuild = function () {
  71785. this.releaseInternalTextures();
  71786. this._createInternalTextures();
  71787. for (var i = 0; i < this._internalTextures.length; i++) {
  71788. var texture = this._textures[i];
  71789. texture._texture = this._internalTextures[i];
  71790. }
  71791. // Keeps references to frame buffer and stencil/depth buffer
  71792. this._texture = this._internalTextures[0];
  71793. };
  71794. MultiRenderTarget.prototype._createInternalTextures = function () {
  71795. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  71796. };
  71797. MultiRenderTarget.prototype._createTextures = function () {
  71798. this._textures = [];
  71799. for (var i = 0; i < this._internalTextures.length; i++) {
  71800. var texture = new BABYLON.Texture(null, this.getScene());
  71801. texture._texture = this._internalTextures[i];
  71802. this._textures.push(texture);
  71803. }
  71804. // Keeps references to frame buffer and stencil/depth buffer
  71805. this._texture = this._internalTextures[0];
  71806. };
  71807. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  71808. /**
  71809. * Define the number of samples used if MSAA is enabled.
  71810. */
  71811. get: function () {
  71812. return this._samples;
  71813. },
  71814. set: function (value) {
  71815. if (this._samples === value) {
  71816. return;
  71817. }
  71818. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  71819. },
  71820. enumerable: true,
  71821. configurable: true
  71822. });
  71823. /**
  71824. * Resize all the textures in the multi render target.
  71825. * Be carrefull as it will recreate all the data in the new texture.
  71826. * @param size Define the new size
  71827. */
  71828. MultiRenderTarget.prototype.resize = function (size) {
  71829. this.releaseInternalTextures();
  71830. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  71831. this._createInternalTextures();
  71832. };
  71833. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  71834. var _this = this;
  71835. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  71836. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  71837. });
  71838. };
  71839. /**
  71840. * Dispose the render targets and their associated resources
  71841. */
  71842. MultiRenderTarget.prototype.dispose = function () {
  71843. this.releaseInternalTextures();
  71844. _super.prototype.dispose.call(this);
  71845. };
  71846. /**
  71847. * Release all the underlying texture used as draw buffers.
  71848. */
  71849. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  71850. if (!this._internalTextures) {
  71851. return;
  71852. }
  71853. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  71854. if (this._internalTextures[i] !== undefined) {
  71855. this._internalTextures[i].dispose();
  71856. this._internalTextures.splice(i, 1);
  71857. }
  71858. }
  71859. };
  71860. return MultiRenderTarget;
  71861. }(BABYLON.RenderTargetTexture));
  71862. BABYLON.MultiRenderTarget = MultiRenderTarget;
  71863. })(BABYLON || (BABYLON = {}));
  71864. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  71865. var BABYLON;
  71866. (function (BABYLON) {
  71867. /**
  71868. * Mirror texture can be used to simulate the view from a mirror in a scene.
  71869. * It will dynamically be rendered every frame to adapt to the camera point of view.
  71870. * You can then easily use it as a reflectionTexture on a flat surface.
  71871. * In case the surface is not a plane, please consider relying on reflection probes.
  71872. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  71873. */
  71874. var MirrorTexture = /** @class */ (function (_super) {
  71875. __extends(MirrorTexture, _super);
  71876. /**
  71877. * Instantiates a Mirror Texture.
  71878. * Mirror texture can be used to simulate the view from a mirror in a scene.
  71879. * It will dynamically be rendered every frame to adapt to the camera point of view.
  71880. * You can then easily use it as a reflectionTexture on a flat surface.
  71881. * In case the surface is not a plane, please consider relying on reflection probes.
  71882. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  71883. * @param name
  71884. * @param size
  71885. * @param scene
  71886. * @param generateMipMaps
  71887. * @param type
  71888. * @param samplingMode
  71889. * @param generateDepthBuffer
  71890. */
  71891. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  71892. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71893. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71894. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  71895. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  71896. _this.scene = scene;
  71897. /**
  71898. * Define the reflection plane we want to use. The mirrorPlane is usually set to the constructed reflector.
  71899. * It is possible to directly set the mirrorPlane by directly using a BABYLON.Plane(a, b, c, d) where a, b and c give the plane normal vector (a, b, c) and d is a scalar displacement from the mirrorPlane to the origin. However in all but the very simplest of situations it is more straight forward to set it to the reflector as stated in the doc.
  71900. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  71901. */
  71902. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  71903. _this._transformMatrix = BABYLON.Matrix.Zero();
  71904. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  71905. _this._adaptiveBlurKernel = 0;
  71906. _this._blurKernelX = 0;
  71907. _this._blurKernelY = 0;
  71908. _this._blurRatio = 1.0;
  71909. _this.ignoreCameraViewport = true;
  71910. _this._updateGammaSpace();
  71911. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  71912. _this._updateGammaSpace;
  71913. });
  71914. _this.onBeforeRenderObservable.add(function () {
  71915. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  71916. _this._savedViewMatrix = scene.getViewMatrix();
  71917. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  71918. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  71919. scene.clipPlane = _this.mirrorPlane;
  71920. scene.getEngine().cullBackFaces = false;
  71921. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  71922. });
  71923. _this.onAfterRenderObservable.add(function () {
  71924. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  71925. scene.getEngine().cullBackFaces = true;
  71926. scene._mirroredCameraPosition = null;
  71927. delete scene.clipPlane;
  71928. });
  71929. return _this;
  71930. }
  71931. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  71932. get: function () {
  71933. return this._blurRatio;
  71934. },
  71935. /**
  71936. * Define the blur ratio used to blur the reflection if needed.
  71937. */
  71938. set: function (value) {
  71939. if (this._blurRatio === value) {
  71940. return;
  71941. }
  71942. this._blurRatio = value;
  71943. this._preparePostProcesses();
  71944. },
  71945. enumerable: true,
  71946. configurable: true
  71947. });
  71948. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  71949. /**
  71950. * Define the adaptive blur kernel used to blur the reflection if needed.
  71951. * This will autocompute the closest best match for the `blurKernel`
  71952. */
  71953. set: function (value) {
  71954. this._adaptiveBlurKernel = value;
  71955. this._autoComputeBlurKernel();
  71956. },
  71957. enumerable: true,
  71958. configurable: true
  71959. });
  71960. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  71961. /**
  71962. * Define the blur kernel used to blur the reflection if needed.
  71963. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  71964. */
  71965. set: function (value) {
  71966. this.blurKernelX = value;
  71967. this.blurKernelY = value;
  71968. },
  71969. enumerable: true,
  71970. configurable: true
  71971. });
  71972. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  71973. get: function () {
  71974. return this._blurKernelX;
  71975. },
  71976. /**
  71977. * Define the blur kernel on the X Axis used to blur the reflection if needed.
  71978. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  71979. */
  71980. set: function (value) {
  71981. if (this._blurKernelX === value) {
  71982. return;
  71983. }
  71984. this._blurKernelX = value;
  71985. this._preparePostProcesses();
  71986. },
  71987. enumerable: true,
  71988. configurable: true
  71989. });
  71990. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  71991. get: function () {
  71992. return this._blurKernelY;
  71993. },
  71994. /**
  71995. * Define the blur kernel on the Y Axis used to blur the reflection if needed.
  71996. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  71997. */
  71998. set: function (value) {
  71999. if (this._blurKernelY === value) {
  72000. return;
  72001. }
  72002. this._blurKernelY = value;
  72003. this._preparePostProcesses();
  72004. },
  72005. enumerable: true,
  72006. configurable: true
  72007. });
  72008. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  72009. var engine = this.getScene().getEngine();
  72010. var dw = this.getRenderWidth() / engine.getRenderWidth();
  72011. var dh = this.getRenderHeight() / engine.getRenderHeight();
  72012. this.blurKernelX = this._adaptiveBlurKernel * dw;
  72013. this.blurKernelY = this._adaptiveBlurKernel * dh;
  72014. };
  72015. MirrorTexture.prototype._onRatioRescale = function () {
  72016. if (this._sizeRatio) {
  72017. this.resize(this._initialSizeParameter);
  72018. if (!this._adaptiveBlurKernel) {
  72019. this._preparePostProcesses();
  72020. }
  72021. }
  72022. if (this._adaptiveBlurKernel) {
  72023. this._autoComputeBlurKernel();
  72024. }
  72025. };
  72026. MirrorTexture.prototype._updateGammaSpace = function () {
  72027. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  72028. };
  72029. MirrorTexture.prototype._preparePostProcesses = function () {
  72030. this.clearPostProcesses(true);
  72031. if (this._blurKernelX && this._blurKernelY) {
  72032. var engine = this.getScene().getEngine();
  72033. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72034. 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);
  72035. this._blurX.autoClear = false;
  72036. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  72037. this._blurX.inputTexture = this._texture;
  72038. }
  72039. else {
  72040. this._blurX.alwaysForcePOT = true;
  72041. }
  72042. 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);
  72043. this._blurY.autoClear = false;
  72044. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  72045. this.addPostProcess(this._blurX);
  72046. this.addPostProcess(this._blurY);
  72047. }
  72048. else {
  72049. if (this._blurY) {
  72050. this.removePostProcess(this._blurY);
  72051. this._blurY.dispose();
  72052. this._blurY = null;
  72053. }
  72054. if (this._blurX) {
  72055. this.removePostProcess(this._blurX);
  72056. this._blurX.dispose();
  72057. this._blurX = null;
  72058. }
  72059. }
  72060. };
  72061. /**
  72062. * Clone the mirror texture.
  72063. * @returns the cloned texture
  72064. */
  72065. MirrorTexture.prototype.clone = function () {
  72066. var scene = this.getScene();
  72067. if (!scene) {
  72068. return this;
  72069. }
  72070. var textureSize = this.getSize();
  72071. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  72072. // Base texture
  72073. newTexture.hasAlpha = this.hasAlpha;
  72074. newTexture.level = this.level;
  72075. // Mirror Texture
  72076. newTexture.mirrorPlane = this.mirrorPlane.clone();
  72077. if (this.renderList) {
  72078. newTexture.renderList = this.renderList.slice(0);
  72079. }
  72080. return newTexture;
  72081. };
  72082. /**
  72083. * Serialize the texture to a JSON representation you could use in Parse later on
  72084. * @returns the serialized JSON representation
  72085. */
  72086. MirrorTexture.prototype.serialize = function () {
  72087. if (!this.name) {
  72088. return null;
  72089. }
  72090. var serializationObject = _super.prototype.serialize.call(this);
  72091. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  72092. return serializationObject;
  72093. };
  72094. /**
  72095. * Dispose the texture and release its associated resources.
  72096. */
  72097. MirrorTexture.prototype.dispose = function () {
  72098. _super.prototype.dispose.call(this);
  72099. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  72100. };
  72101. return MirrorTexture;
  72102. }(BABYLON.RenderTargetTexture));
  72103. BABYLON.MirrorTexture = MirrorTexture;
  72104. })(BABYLON || (BABYLON = {}));
  72105. //# sourceMappingURL=babylon.mirrorTexture.js.map
  72106. var BABYLON;
  72107. (function (BABYLON) {
  72108. /**
  72109. * Creates a refraction texture used by refraction channel of the standard material.
  72110. * It is like a mirror but to see through a material.
  72111. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  72112. */
  72113. var RefractionTexture = /** @class */ (function (_super) {
  72114. __extends(RefractionTexture, _super);
  72115. /**
  72116. * Creates a refraction texture used by refraction channel of the standard material.
  72117. * It is like a mirror but to see through a material.
  72118. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  72119. * @param name Define the texture name
  72120. * @param size Define the size of the underlying texture
  72121. * @param scene Define the scene the refraction belongs to
  72122. * @param generateMipMaps Define if we need to generate mips level for the refraction
  72123. */
  72124. function RefractionTexture(name, size, scene, generateMipMaps) {
  72125. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  72126. /**
  72127. * Define the reflection plane we want to use. The refractionPlane is usually set to the constructed refractor.
  72128. * It is possible to directly set the refractionPlane by directly using a BABYLON.Plane(a, b, c, d) where a, b and c give the plane normal vector (a, b, c) and d is a scalar displacement from the refractionPlane to the origin. However in all but the very simplest of situations it is more straight forward to set it to the refractor as stated in the doc.
  72129. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  72130. */
  72131. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  72132. /**
  72133. * Define how deep under the surface we should see.
  72134. */
  72135. _this.depth = 2.0;
  72136. _this.onBeforeRenderObservable.add(function () {
  72137. scene.clipPlane = _this.refractionPlane;
  72138. });
  72139. _this.onAfterRenderObservable.add(function () {
  72140. delete scene.clipPlane;
  72141. });
  72142. return _this;
  72143. }
  72144. /**
  72145. * Clone the refraction texture.
  72146. * @returns the cloned texture
  72147. */
  72148. RefractionTexture.prototype.clone = function () {
  72149. var scene = this.getScene();
  72150. if (!scene) {
  72151. return this;
  72152. }
  72153. var textureSize = this.getSize();
  72154. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  72155. // Base texture
  72156. newTexture.hasAlpha = this.hasAlpha;
  72157. newTexture.level = this.level;
  72158. // Refraction Texture
  72159. newTexture.refractionPlane = this.refractionPlane.clone();
  72160. if (this.renderList) {
  72161. newTexture.renderList = this.renderList.slice(0);
  72162. }
  72163. newTexture.depth = this.depth;
  72164. return newTexture;
  72165. };
  72166. /**
  72167. * Serialize the texture to a JSON representation you could use in Parse later on
  72168. * @returns the serialized JSON representation
  72169. */
  72170. RefractionTexture.prototype.serialize = function () {
  72171. if (!this.name) {
  72172. return null;
  72173. }
  72174. var serializationObject = _super.prototype.serialize.call(this);
  72175. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  72176. serializationObject.depth = this.depth;
  72177. return serializationObject;
  72178. };
  72179. return RefractionTexture;
  72180. }(BABYLON.RenderTargetTexture));
  72181. BABYLON.RefractionTexture = RefractionTexture;
  72182. })(BABYLON || (BABYLON = {}));
  72183. //# sourceMappingURL=babylon.refractionTexture.js.map
  72184. var BABYLON;
  72185. (function (BABYLON) {
  72186. /**
  72187. * A class extending {BABYLON.Texture} allowing drawing on a texture
  72188. * @see http://doc.babylonjs.com/how_to/dynamictexture
  72189. */
  72190. var DynamicTexture = /** @class */ (function (_super) {
  72191. __extends(DynamicTexture, _super);
  72192. /**
  72193. * Creates a {BABYLON.DynamicTexture}
  72194. * @param name defines the name of the texture
  72195. * @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
  72196. * @param scene defines the scene where you want the texture
  72197. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  72198. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  72199. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  72200. */
  72201. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  72202. if (scene === void 0) { scene = null; }
  72203. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72204. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  72205. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  72206. _this.name = name;
  72207. _this._engine = _this.getScene().getEngine();
  72208. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72209. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72210. _this._generateMipMaps = generateMipMaps;
  72211. if (options.getContext) {
  72212. _this._canvas = options;
  72213. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  72214. }
  72215. else {
  72216. _this._canvas = document.createElement("canvas");
  72217. if (options.width || options.width === 0) {
  72218. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  72219. }
  72220. else {
  72221. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  72222. }
  72223. }
  72224. var textureSize = _this.getSize();
  72225. _this._canvas.width = textureSize.width;
  72226. _this._canvas.height = textureSize.height;
  72227. _this._context = _this._canvas.getContext("2d");
  72228. return _this;
  72229. }
  72230. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  72231. /**
  72232. * Gets the current state of canRescale
  72233. */
  72234. get: function () {
  72235. return true;
  72236. },
  72237. enumerable: true,
  72238. configurable: true
  72239. });
  72240. DynamicTexture.prototype._recreate = function (textureSize) {
  72241. this._canvas.width = textureSize.width;
  72242. this._canvas.height = textureSize.height;
  72243. this.releaseInternalTexture();
  72244. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  72245. };
  72246. /**
  72247. * Scales the texture
  72248. * @param ratio the scale factor to apply to both width and height
  72249. */
  72250. DynamicTexture.prototype.scale = function (ratio) {
  72251. var textureSize = this.getSize();
  72252. textureSize.width *= ratio;
  72253. textureSize.height *= ratio;
  72254. this._recreate(textureSize);
  72255. };
  72256. /**
  72257. * Resizes the texture
  72258. * @param width the new width
  72259. * @param height the new height
  72260. */
  72261. DynamicTexture.prototype.scaleTo = function (width, height) {
  72262. var textureSize = this.getSize();
  72263. textureSize.width = width;
  72264. textureSize.height = height;
  72265. this._recreate(textureSize);
  72266. };
  72267. /**
  72268. * Gets the context of the canvas used by the texture
  72269. * @returns the canvas context of the dynamic texture
  72270. */
  72271. DynamicTexture.prototype.getContext = function () {
  72272. return this._context;
  72273. };
  72274. /**
  72275. * Clears the texture
  72276. */
  72277. DynamicTexture.prototype.clear = function () {
  72278. var size = this.getSize();
  72279. this._context.fillRect(0, 0, size.width, size.height);
  72280. };
  72281. /**
  72282. * Updates the texture
  72283. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  72284. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  72285. */
  72286. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  72287. if (premulAlpha === void 0) { premulAlpha = false; }
  72288. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  72289. };
  72290. /**
  72291. * Draws text onto the texture
  72292. * @param text defines the text to be drawn
  72293. * @param x defines the placement of the text from the left
  72294. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  72295. * @param font defines the font to be used with font-style, font-size, font-name
  72296. * @param color defines the color used for the text
  72297. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  72298. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  72299. * @param update defines whether texture is immediately update (default is true)
  72300. */
  72301. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  72302. if (update === void 0) { update = true; }
  72303. var size = this.getSize();
  72304. if (clearColor) {
  72305. this._context.fillStyle = clearColor;
  72306. this._context.fillRect(0, 0, size.width, size.height);
  72307. }
  72308. this._context.font = font;
  72309. if (x === null || x === undefined) {
  72310. var textSize = this._context.measureText(text);
  72311. x = (size.width - textSize.width) / 2;
  72312. }
  72313. if (y === null || y === undefined) {
  72314. var fontSize = parseInt((font.replace(/\D/g, '')));
  72315. y = (size.height / 2) + (fontSize / 3.65);
  72316. }
  72317. this._context.fillStyle = color;
  72318. this._context.fillText(text, x, y);
  72319. if (update) {
  72320. this.update(invertY);
  72321. }
  72322. };
  72323. /**
  72324. * Clones the texture
  72325. * @returns the clone of the texture.
  72326. */
  72327. DynamicTexture.prototype.clone = function () {
  72328. var scene = this.getScene();
  72329. if (!scene) {
  72330. return this;
  72331. }
  72332. var textureSize = this.getSize();
  72333. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  72334. // Base texture
  72335. newTexture.hasAlpha = this.hasAlpha;
  72336. newTexture.level = this.level;
  72337. // Dynamic Texture
  72338. newTexture.wrapU = this.wrapU;
  72339. newTexture.wrapV = this.wrapV;
  72340. return newTexture;
  72341. };
  72342. /**
  72343. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  72344. * @returns a serialized dynamic texture object
  72345. */
  72346. DynamicTexture.prototype.serialize = function () {
  72347. var scene = this.getScene();
  72348. if (scene && !scene.isReady()) {
  72349. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  72350. }
  72351. var serializationObject = _super.prototype.serialize.call(this);
  72352. serializationObject.base64String = this._canvas.toDataURL();
  72353. serializationObject.invertY = this._invertY;
  72354. serializationObject.samplingMode = this.samplingMode;
  72355. return serializationObject;
  72356. };
  72357. /** @hidden */
  72358. DynamicTexture.prototype._rebuild = function () {
  72359. this.update();
  72360. };
  72361. return DynamicTexture;
  72362. }(BABYLON.Texture));
  72363. BABYLON.DynamicTexture = DynamicTexture;
  72364. })(BABYLON || (BABYLON = {}));
  72365. //# sourceMappingURL=babylon.dynamicTexture.js.map
  72366. var BABYLON;
  72367. (function (BABYLON) {
  72368. /**
  72369. * If you want to display a video in your scene, this is the special texture for that.
  72370. * This special texture works similar to other textures, with the exception of a few parameters.
  72371. * @see https://doc.babylonjs.com/how_to/video_texture
  72372. */
  72373. var VideoTexture = /** @class */ (function (_super) {
  72374. __extends(VideoTexture, _super);
  72375. /**
  72376. * Creates a video texture.
  72377. * If you want to display a video in your scene, this is the special texture for that.
  72378. * This special texture works similar to other textures, with the exception of a few parameters.
  72379. * @see https://doc.babylonjs.com/how_to/video_texture
  72380. * @param {string | null} name optional name, will detect from video source, if not defined
  72381. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  72382. * @param {BABYLON.Scene} scene is obviously the current scene.
  72383. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  72384. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  72385. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  72386. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  72387. */
  72388. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  72389. if (generateMipMaps === void 0) { generateMipMaps = false; }
  72390. if (invertY === void 0) { invertY = false; }
  72391. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72392. if (settings === void 0) { settings = {
  72393. autoPlay: true,
  72394. loop: true,
  72395. autoUpdateTexture: true,
  72396. }; }
  72397. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  72398. _this._onUserActionRequestedObservable = null;
  72399. _this._stillImageCaptured = false;
  72400. _this._poster = false;
  72401. _this._createInternalTexture = function () {
  72402. if (_this._texture != null) {
  72403. if (_this._poster) {
  72404. _this._texture.dispose();
  72405. _this._poster = false;
  72406. }
  72407. else {
  72408. return;
  72409. }
  72410. }
  72411. if (!_this._engine.needPOTTextures ||
  72412. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  72413. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  72414. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  72415. }
  72416. else {
  72417. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72418. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72419. _this._generateMipMaps = false;
  72420. }
  72421. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  72422. if (!_this.video.autoplay) {
  72423. var oldHandler_1 = _this.video.onplaying;
  72424. var error_1 = false;
  72425. _this.video.onplaying = function () {
  72426. _this.video.onplaying = oldHandler_1;
  72427. _this._texture.isReady = true;
  72428. _this._updateInternalTexture();
  72429. if (!error_1) {
  72430. _this.video.pause();
  72431. }
  72432. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  72433. _this.onLoadObservable.notifyObservers(_this);
  72434. }
  72435. };
  72436. var playing = _this.video.play();
  72437. if (playing) {
  72438. playing.then(function () {
  72439. // Everything is good.
  72440. })
  72441. .catch(function () {
  72442. error_1 = true;
  72443. // On Chrome for instance, new policies might prevent playing without user interaction.
  72444. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  72445. _this._onUserActionRequestedObservable.notifyObservers(_this);
  72446. }
  72447. });
  72448. }
  72449. else {
  72450. _this.video.onplaying = oldHandler_1;
  72451. _this._texture.isReady = true;
  72452. _this._updateInternalTexture();
  72453. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  72454. _this.onLoadObservable.notifyObservers(_this);
  72455. }
  72456. }
  72457. }
  72458. else {
  72459. _this._texture.isReady = true;
  72460. _this._updateInternalTexture();
  72461. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  72462. _this.onLoadObservable.notifyObservers(_this);
  72463. }
  72464. }
  72465. };
  72466. _this.reset = function () {
  72467. if (_this._texture == null) {
  72468. return;
  72469. }
  72470. if (!_this._poster) {
  72471. _this._texture.dispose();
  72472. _this._texture = null;
  72473. }
  72474. };
  72475. _this._updateInternalTexture = function (e) {
  72476. if (_this._texture == null || !_this._texture.isReady) {
  72477. return;
  72478. }
  72479. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  72480. return;
  72481. }
  72482. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  72483. };
  72484. _this._engine = _this.getScene().getEngine();
  72485. _this._generateMipMaps = generateMipMaps;
  72486. _this._samplingMode = samplingMode;
  72487. _this.autoUpdateTexture = settings.autoUpdateTexture;
  72488. _this.name = name || _this._getName(src);
  72489. _this.video = _this._getVideo(src);
  72490. if (settings.poster) {
  72491. _this.video.poster = settings.poster;
  72492. }
  72493. if (settings.autoPlay !== undefined) {
  72494. _this.video.autoplay = settings.autoPlay;
  72495. }
  72496. if (settings.loop !== undefined) {
  72497. _this.video.loop = settings.loop;
  72498. }
  72499. _this.video.setAttribute("playsinline", "");
  72500. _this.video.addEventListener("canplay", _this._createInternalTexture);
  72501. _this.video.addEventListener("paused", _this._updateInternalTexture);
  72502. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  72503. _this.video.addEventListener("emptied", _this.reset);
  72504. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  72505. _this._createInternalTexture();
  72506. }
  72507. if (settings.poster) {
  72508. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  72509. _this._poster = true;
  72510. }
  72511. return _this;
  72512. }
  72513. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  72514. /**
  72515. * Event triggerd when a dom action is required by the user to play the video.
  72516. * This happens due to recent changes in browser policies preventing video to auto start.
  72517. */
  72518. get: function () {
  72519. if (!this._onUserActionRequestedObservable) {
  72520. this._onUserActionRequestedObservable = new BABYLON.Observable();
  72521. }
  72522. return this._onUserActionRequestedObservable;
  72523. },
  72524. enumerable: true,
  72525. configurable: true
  72526. });
  72527. VideoTexture.prototype._getName = function (src) {
  72528. if (src instanceof HTMLVideoElement) {
  72529. return src.currentSrc;
  72530. }
  72531. if (typeof src === "object") {
  72532. return src.toString();
  72533. }
  72534. return src;
  72535. };
  72536. ;
  72537. VideoTexture.prototype._getVideo = function (src) {
  72538. if (src instanceof HTMLVideoElement) {
  72539. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  72540. return src;
  72541. }
  72542. var video = document.createElement("video");
  72543. if (typeof src === "string") {
  72544. BABYLON.Tools.SetCorsBehavior(src, video);
  72545. video.src = src;
  72546. }
  72547. else {
  72548. BABYLON.Tools.SetCorsBehavior(src[0], video);
  72549. src.forEach(function (url) {
  72550. var source = document.createElement("source");
  72551. source.src = url;
  72552. video.appendChild(source);
  72553. });
  72554. }
  72555. return video;
  72556. };
  72557. ;
  72558. /**
  72559. * @hidden Internal method to initiate `update`.
  72560. */
  72561. VideoTexture.prototype._rebuild = function () {
  72562. this.update();
  72563. };
  72564. /**
  72565. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  72566. */
  72567. VideoTexture.prototype.update = function () {
  72568. if (!this.autoUpdateTexture) {
  72569. // Expecting user to call `updateTexture` manually
  72570. return;
  72571. }
  72572. this.updateTexture(true);
  72573. };
  72574. /**
  72575. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  72576. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  72577. */
  72578. VideoTexture.prototype.updateTexture = function (isVisible) {
  72579. if (!isVisible) {
  72580. return;
  72581. }
  72582. if (this.video.paused && this._stillImageCaptured) {
  72583. return;
  72584. }
  72585. this._stillImageCaptured = true;
  72586. this._updateInternalTexture();
  72587. };
  72588. /**
  72589. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  72590. * @param url New url.
  72591. */
  72592. VideoTexture.prototype.updateURL = function (url) {
  72593. this.video.src = url;
  72594. };
  72595. /**
  72596. * Dispose the texture and release its associated resources.
  72597. */
  72598. VideoTexture.prototype.dispose = function () {
  72599. _super.prototype.dispose.call(this);
  72600. if (this._onUserActionRequestedObservable) {
  72601. this._onUserActionRequestedObservable.clear();
  72602. this._onUserActionRequestedObservable = null;
  72603. }
  72604. this.video.removeEventListener("canplay", this._createInternalTexture);
  72605. this.video.removeEventListener("paused", this._updateInternalTexture);
  72606. this.video.removeEventListener("seeked", this._updateInternalTexture);
  72607. this.video.removeEventListener("emptied", this.reset);
  72608. this.video.pause();
  72609. };
  72610. /**
  72611. * Creates a video texture straight from your WebCam video feed.
  72612. * @param scene Define the scene the texture should be created in
  72613. * @param onReady Define a callback to triggered once the texture will be ready
  72614. * @param constraints Define the constraints to use to create the web cam feed from WebRTC
  72615. */
  72616. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  72617. var video = document.createElement("video");
  72618. video.setAttribute('autoplay', '');
  72619. video.setAttribute('muted', '');
  72620. video.setAttribute('playsinline', '');
  72621. var constraintsDeviceId;
  72622. if (constraints && constraints.deviceId) {
  72623. constraintsDeviceId = {
  72624. exact: constraints.deviceId,
  72625. };
  72626. }
  72627. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  72628. if (navigator.mediaDevices) {
  72629. navigator.mediaDevices.getUserMedia({ video: constraints })
  72630. .then(function (stream) {
  72631. if (video.mozSrcObject !== undefined) {
  72632. // hack for Firefox < 19
  72633. video.mozSrcObject = stream;
  72634. }
  72635. else {
  72636. video.srcObject = stream;
  72637. }
  72638. var onPlaying = function () {
  72639. if (onReady) {
  72640. onReady(new VideoTexture("video", video, scene, true, true));
  72641. }
  72642. video.removeEventListener("playing", onPlaying);
  72643. };
  72644. video.addEventListener("playing", onPlaying);
  72645. video.play();
  72646. })
  72647. .catch(function (err) {
  72648. BABYLON.Tools.Error(err.name);
  72649. });
  72650. }
  72651. else {
  72652. navigator.getUserMedia =
  72653. navigator.getUserMedia ||
  72654. navigator.webkitGetUserMedia ||
  72655. navigator.mozGetUserMedia ||
  72656. navigator.msGetUserMedia;
  72657. if (navigator.getUserMedia) {
  72658. navigator.getUserMedia({
  72659. video: {
  72660. deviceId: constraintsDeviceId,
  72661. width: {
  72662. min: (constraints && constraints.minWidth) || 256,
  72663. max: (constraints && constraints.maxWidth) || 640,
  72664. },
  72665. height: {
  72666. min: (constraints && constraints.minHeight) || 256,
  72667. max: (constraints && constraints.maxHeight) || 480,
  72668. },
  72669. },
  72670. }, function (stream) {
  72671. if (video.mozSrcObject !== undefined) {
  72672. // hack for Firefox < 19
  72673. video.mozSrcObject = stream;
  72674. }
  72675. else {
  72676. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  72677. }
  72678. video.play();
  72679. if (onReady) {
  72680. onReady(new VideoTexture("video", video, scene, true, true));
  72681. }
  72682. }, function (e) {
  72683. BABYLON.Tools.Error(e.name);
  72684. });
  72685. }
  72686. }
  72687. };
  72688. return VideoTexture;
  72689. }(BABYLON.Texture));
  72690. BABYLON.VideoTexture = VideoTexture;
  72691. })(BABYLON || (BABYLON = {}));
  72692. //# sourceMappingURL=babylon.videoTexture.js.map
  72693. var BABYLON;
  72694. (function (BABYLON) {
  72695. /**
  72696. * Raw texture can help creating a texture directly from an array of data.
  72697. * This can be super useful if you either get the data from an uncompressed source or
  72698. * if you wish to create your texture pixel by pixel.
  72699. */
  72700. var RawTexture = /** @class */ (function (_super) {
  72701. __extends(RawTexture, _super);
  72702. /**
  72703. * Instantiates a new RawTexture.
  72704. * Raw texture can help creating a texture directly from an array of data.
  72705. * This can be super useful if you either get the data from an uncompressed source or
  72706. * if you wish to create your texture pixel by pixel.
  72707. * @param data define the array of data to use to create the texture
  72708. * @param width define the width of the texture
  72709. * @param height define the height of the texture
  72710. * @param format define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
  72711. * @param scene define the scene the texture belongs to
  72712. * @param generateMipMaps define whether mip maps should be generated or not
  72713. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  72714. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  72715. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  72716. */
  72717. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  72718. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72719. if (invertY === void 0) { invertY = false; }
  72720. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72721. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72722. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  72723. _this.format = format;
  72724. _this._engine = scene.getEngine();
  72725. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  72726. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72727. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72728. return _this;
  72729. }
  72730. /**
  72731. * Updates the texture underlying data.
  72732. * @param data Define the new data of the texture
  72733. */
  72734. RawTexture.prototype.update = function (data) {
  72735. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  72736. };
  72737. /**
  72738. * Creates a luminance texture from some data.
  72739. * @param data Define the texture data
  72740. * @param width Define the width of the texture
  72741. * @param height Define the height of the texture
  72742. * @param scene Define the scene the texture belongs to
  72743. * @param generateMipMaps Define whether or not to create mip maps for the texture
  72744. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  72745. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  72746. * @returns the luminance texture
  72747. */
  72748. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  72749. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72750. if (invertY === void 0) { invertY = false; }
  72751. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72752. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  72753. };
  72754. /**
  72755. * Creates a luminance alpha texture from some data.
  72756. * @param data Define the texture data
  72757. * @param width Define the width of the texture
  72758. * @param height Define the height of the texture
  72759. * @param scene Define the scene the texture belongs to
  72760. * @param generateMipMaps Define whether or not to create mip maps for the texture
  72761. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  72762. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  72763. * @returns the luminance alpha texture
  72764. */
  72765. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  72766. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72767. if (invertY === void 0) { invertY = false; }
  72768. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72769. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  72770. };
  72771. /**
  72772. * Creates an alpha texture from some data.
  72773. * @param data Define the texture data
  72774. * @param width Define the width of the texture
  72775. * @param height Define the height of the texture
  72776. * @param scene Define the scene the texture belongs to
  72777. * @param generateMipMaps Define whether or not to create mip maps for the texture
  72778. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  72779. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  72780. * @returns the alpha texture
  72781. */
  72782. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  72783. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72784. if (invertY === void 0) { invertY = false; }
  72785. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72786. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  72787. };
  72788. /**
  72789. * Creates a RGB texture from some data.
  72790. * @param data Define the texture data
  72791. * @param width Define the width of the texture
  72792. * @param height Define the height of the texture
  72793. * @param scene Define the scene the texture belongs to
  72794. * @param generateMipMaps Define whether or not to create mip maps for the texture
  72795. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  72796. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  72797. * @returns the RGB alpha texture
  72798. */
  72799. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  72800. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72801. if (invertY === void 0) { invertY = false; }
  72802. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72803. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72804. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  72805. };
  72806. /**
  72807. * Creates a RGBA texture from some data.
  72808. * @param data Define the texture data
  72809. * @param width Define the width of the texture
  72810. * @param height Define the height of the texture
  72811. * @param scene Define the scene the texture belongs to
  72812. * @param generateMipMaps Define whether or not to create mip maps for the texture
  72813. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  72814. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  72815. * @returns the RGBA texture
  72816. */
  72817. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  72818. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72819. if (invertY === void 0) { invertY = false; }
  72820. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72821. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72822. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  72823. };
  72824. /**
  72825. * Creates a R texture from some data.
  72826. * @param data Define the texture data
  72827. * @param width Define the width of the texture
  72828. * @param height Define the height of the texture
  72829. * @param scene Define the scene the texture belongs to
  72830. * @param generateMipMaps Define whether or not to create mip maps for the texture
  72831. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  72832. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  72833. * @returns the R texture
  72834. */
  72835. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  72836. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72837. if (invertY === void 0) { invertY = false; }
  72838. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72839. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  72840. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  72841. };
  72842. return RawTexture;
  72843. }(BABYLON.Texture));
  72844. BABYLON.RawTexture = RawTexture;
  72845. })(BABYLON || (BABYLON = {}));
  72846. //# sourceMappingURL=babylon.rawTexture.js.map
  72847. var BABYLON;
  72848. (function (BABYLON) {
  72849. /**
  72850. * Class used to store 3D textures containing user data
  72851. */
  72852. var RawTexture3D = /** @class */ (function (_super) {
  72853. __extends(RawTexture3D, _super);
  72854. /**
  72855. * Create a new RawTexture3D
  72856. * @param data defines the data of the texture
  72857. * @param width defines the width of the texture
  72858. * @param height defines the height of the texture
  72859. * @param depth defines the depth of the texture
  72860. * @param format defines the texture format to use
  72861. * @param scene defines the hosting scene
  72862. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  72863. * @param invertY defines if texture must be stored with Y axis inverted
  72864. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  72865. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  72866. */
  72867. function RawTexture3D(data, width, height, depth,
  72868. /** Gets or sets the texture format to use */
  72869. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  72870. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72871. if (invertY === void 0) { invertY = false; }
  72872. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72873. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72874. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  72875. _this.format = format;
  72876. _this._engine = scene.getEngine();
  72877. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  72878. _this.is3D = true;
  72879. return _this;
  72880. }
  72881. /**
  72882. * Update the texture with new data
  72883. * @param data defines the data to store in the texture
  72884. */
  72885. RawTexture3D.prototype.update = function (data) {
  72886. if (!this._texture) {
  72887. return;
  72888. }
  72889. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  72890. };
  72891. return RawTexture3D;
  72892. }(BABYLON.Texture));
  72893. BABYLON.RawTexture3D = RawTexture3D;
  72894. })(BABYLON || (BABYLON = {}));
  72895. //# sourceMappingURL=babylon.rawTexture3D.js.map
  72896. var BABYLON;
  72897. (function (BABYLON) {
  72898. /**
  72899. * PostProcessManager is used to manage one or more post processes or post process pipelines
  72900. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  72901. */
  72902. var PostProcessManager = /** @class */ (function () {
  72903. /**
  72904. * Creates a new instance PostProcess
  72905. * @param scene The scene that the post process is associated with.
  72906. */
  72907. function PostProcessManager(scene) {
  72908. this._vertexBuffers = {};
  72909. this._scene = scene;
  72910. }
  72911. PostProcessManager.prototype._prepareBuffers = function () {
  72912. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  72913. return;
  72914. }
  72915. // VBO
  72916. var vertices = [];
  72917. vertices.push(1, 1);
  72918. vertices.push(-1, 1);
  72919. vertices.push(-1, -1);
  72920. vertices.push(1, -1);
  72921. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  72922. this._buildIndexBuffer();
  72923. };
  72924. PostProcessManager.prototype._buildIndexBuffer = function () {
  72925. // Indices
  72926. var indices = [];
  72927. indices.push(0);
  72928. indices.push(1);
  72929. indices.push(2);
  72930. indices.push(0);
  72931. indices.push(2);
  72932. indices.push(3);
  72933. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  72934. };
  72935. /**
  72936. * Rebuilds the vertex buffers of the manager.
  72937. * @hidden
  72938. */
  72939. PostProcessManager.prototype._rebuild = function () {
  72940. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72941. if (!vb) {
  72942. return;
  72943. }
  72944. vb._rebuild();
  72945. this._buildIndexBuffer();
  72946. };
  72947. // Methods
  72948. /**
  72949. * Prepares a frame to be run through a post process.
  72950. * @param sourceTexture The input texture to the post procesess. (default: null)
  72951. * @param postProcesses An array of post processes to be run. (default: null)
  72952. * @returns True if the post processes were able to be run.
  72953. * @hidden
  72954. */
  72955. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  72956. if (sourceTexture === void 0) { sourceTexture = null; }
  72957. if (postProcesses === void 0) { postProcesses = null; }
  72958. var camera = this._scene.activeCamera;
  72959. if (!camera) {
  72960. return false;
  72961. }
  72962. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  72963. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  72964. return false;
  72965. }
  72966. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  72967. return true;
  72968. };
  72969. /**
  72970. * Manually render a set of post processes to a texture.
  72971. * @param postProcesses An array of post processes to be run.
  72972. * @param targetTexture The target texture to render to.
  72973. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  72974. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  72975. * @param lodLevel defines which lod of the texture to render to
  72976. */
  72977. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  72978. if (targetTexture === void 0) { targetTexture = null; }
  72979. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  72980. if (faceIndex === void 0) { faceIndex = 0; }
  72981. if (lodLevel === void 0) { lodLevel = 0; }
  72982. var engine = this._scene.getEngine();
  72983. for (var index = 0; index < postProcesses.length; index++) {
  72984. if (index < postProcesses.length - 1) {
  72985. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  72986. }
  72987. else {
  72988. if (targetTexture) {
  72989. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  72990. }
  72991. else {
  72992. engine.restoreDefaultFramebuffer();
  72993. }
  72994. }
  72995. var pp = postProcesses[index];
  72996. var effect = pp.apply();
  72997. if (effect) {
  72998. pp.onBeforeRenderObservable.notifyObservers(effect);
  72999. // VBOs
  73000. this._prepareBuffers();
  73001. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  73002. // Draw order
  73003. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  73004. pp.onAfterRenderObservable.notifyObservers(effect);
  73005. }
  73006. }
  73007. // Restore depth buffer
  73008. engine.setDepthBuffer(true);
  73009. engine.setDepthWrite(true);
  73010. };
  73011. /**
  73012. * Finalize the result of the output of the postprocesses.
  73013. * @param doNotPresent If true the result will not be displayed to the screen.
  73014. * @param targetTexture The target texture to render to.
  73015. * @param faceIndex The index of the face to bind the target texture to.
  73016. * @param postProcesses The array of post processes to render.
  73017. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  73018. * @hidden
  73019. */
  73020. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  73021. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  73022. var camera = this._scene.activeCamera;
  73023. if (!camera) {
  73024. return;
  73025. }
  73026. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  73027. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  73028. return;
  73029. }
  73030. var engine = this._scene.getEngine();
  73031. for (var index = 0, len = postProcesses.length; index < len; index++) {
  73032. var pp = postProcesses[index];
  73033. if (index < len - 1) {
  73034. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  73035. }
  73036. else {
  73037. if (targetTexture) {
  73038. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  73039. pp._outputTexture = targetTexture;
  73040. }
  73041. else {
  73042. engine.restoreDefaultFramebuffer();
  73043. pp._outputTexture = null;
  73044. }
  73045. }
  73046. if (doNotPresent) {
  73047. break;
  73048. }
  73049. var effect = pp.apply();
  73050. if (effect) {
  73051. pp.onBeforeRenderObservable.notifyObservers(effect);
  73052. // VBOs
  73053. this._prepareBuffers();
  73054. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  73055. // Draw order
  73056. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  73057. pp.onAfterRenderObservable.notifyObservers(effect);
  73058. }
  73059. }
  73060. // Restore states
  73061. engine.setDepthBuffer(true);
  73062. engine.setDepthWrite(true);
  73063. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  73064. };
  73065. /**
  73066. * Disposes of the post process manager.
  73067. */
  73068. PostProcessManager.prototype.dispose = function () {
  73069. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73070. if (buffer) {
  73071. buffer.dispose();
  73072. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73073. }
  73074. if (this._indexBuffer) {
  73075. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  73076. this._indexBuffer = null;
  73077. }
  73078. };
  73079. return PostProcessManager;
  73080. }());
  73081. BABYLON.PostProcessManager = PostProcessManager;
  73082. })(BABYLON || (BABYLON = {}));
  73083. //# sourceMappingURL=babylon.postProcessManager.js.map
  73084. var BABYLON;
  73085. (function (BABYLON) {
  73086. /**
  73087. * PostProcess can be used to apply a shader to a texture after it has been rendered
  73088. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  73089. */
  73090. var PostProcess = /** @class */ (function () {
  73091. /**
  73092. * Creates a new instance PostProcess
  73093. * @param name The name of the PostProcess.
  73094. * @param fragmentUrl The url of the fragment shader to be used.
  73095. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  73096. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  73097. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  73098. * @param camera The camera to apply the render pass to.
  73099. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73100. * @param engine The engine which the post process will be applied. (default: current engine)
  73101. * @param reusable If the post process can be reused on the same frame. (default: false)
  73102. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  73103. * @param textureType Type of textures used when performing the post process. (default: 0)
  73104. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  73105. * @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
  73106. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  73107. */
  73108. function PostProcess(
  73109. /** Name of the PostProcess. */
  73110. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  73111. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  73112. if (defines === void 0) { defines = null; }
  73113. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73114. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  73115. if (blockCompilation === void 0) { blockCompilation = false; }
  73116. this.name = name;
  73117. /**
  73118. * Width of the texture to apply the post process on
  73119. */
  73120. this.width = -1;
  73121. /**
  73122. * Height of the texture to apply the post process on
  73123. */
  73124. this.height = -1;
  73125. /**
  73126. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  73127. * @hidden
  73128. */
  73129. this._outputTexture = null;
  73130. /**
  73131. * If the buffer needs to be cleared before applying the post process. (default: true)
  73132. * Should be set to false if shader will overwrite all previous pixels.
  73133. */
  73134. this.autoClear = true;
  73135. /**
  73136. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  73137. */
  73138. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  73139. /**
  73140. * Animations to be used for the post processing
  73141. */
  73142. this.animations = new Array();
  73143. /**
  73144. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  73145. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  73146. */
  73147. this.enablePixelPerfectMode = false;
  73148. /**
  73149. * Force the postprocess to be applied without taking in account viewport
  73150. */
  73151. this.forceFullscreenViewport = true;
  73152. /**
  73153. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  73154. *
  73155. * | Value | Type | Description |
  73156. * | ----- | ----------------------------------- | ----------- |
  73157. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  73158. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  73159. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  73160. *
  73161. */
  73162. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  73163. /**
  73164. * Force textures to be a power of two (default: false)
  73165. */
  73166. this.alwaysForcePOT = false;
  73167. this._samples = 1;
  73168. /**
  73169. * Modify the scale of the post process to be the same as the viewport (default: false)
  73170. */
  73171. this.adaptScaleToCurrentViewport = false;
  73172. this._reusable = false;
  73173. /**
  73174. * Smart array of input and output textures for the post process.
  73175. * @hidden
  73176. */
  73177. this._textures = new BABYLON.SmartArray(2);
  73178. /**
  73179. * The index in _textures that corresponds to the output texture.
  73180. * @hidden
  73181. */
  73182. this._currentRenderTextureInd = 0;
  73183. this._scaleRatio = new BABYLON.Vector2(1, 1);
  73184. this._texelSize = BABYLON.Vector2.Zero();
  73185. // Events
  73186. /**
  73187. * An event triggered when the postprocess is activated.
  73188. */
  73189. this.onActivateObservable = new BABYLON.Observable();
  73190. /**
  73191. * An event triggered when the postprocess changes its size.
  73192. */
  73193. this.onSizeChangedObservable = new BABYLON.Observable();
  73194. /**
  73195. * An event triggered when the postprocess applies its effect.
  73196. */
  73197. this.onApplyObservable = new BABYLON.Observable();
  73198. /**
  73199. * An event triggered before rendering the postprocess
  73200. */
  73201. this.onBeforeRenderObservable = new BABYLON.Observable();
  73202. /**
  73203. * An event triggered after rendering the postprocess
  73204. */
  73205. this.onAfterRenderObservable = new BABYLON.Observable();
  73206. if (camera != null) {
  73207. this._camera = camera;
  73208. this._scene = camera.getScene();
  73209. camera.attachPostProcess(this);
  73210. this._engine = this._scene.getEngine();
  73211. this._scene.postProcesses.push(this);
  73212. }
  73213. else if (engine) {
  73214. this._engine = engine;
  73215. this._engine.postProcesses.push(this);
  73216. }
  73217. this._options = options;
  73218. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  73219. this._reusable = reusable || false;
  73220. this._textureType = textureType;
  73221. this._samplers = samplers || [];
  73222. this._samplers.push("textureSampler");
  73223. this._fragmentUrl = fragmentUrl;
  73224. this._vertexUrl = vertexUrl;
  73225. this._parameters = parameters || [];
  73226. this._parameters.push("scale");
  73227. this._indexParameters = indexParameters;
  73228. if (!blockCompilation) {
  73229. this.updateEffect(defines);
  73230. }
  73231. }
  73232. Object.defineProperty(PostProcess.prototype, "samples", {
  73233. /**
  73234. * Number of sample textures (default: 1)
  73235. */
  73236. get: function () {
  73237. return this._samples;
  73238. },
  73239. set: function (n) {
  73240. var _this = this;
  73241. this._samples = n;
  73242. this._textures.forEach(function (texture) {
  73243. if (texture.samples !== _this._samples) {
  73244. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  73245. }
  73246. });
  73247. },
  73248. enumerable: true,
  73249. configurable: true
  73250. });
  73251. Object.defineProperty(PostProcess.prototype, "onActivate", {
  73252. /**
  73253. * A function that is added to the onActivateObservable
  73254. */
  73255. set: function (callback) {
  73256. if (this._onActivateObserver) {
  73257. this.onActivateObservable.remove(this._onActivateObserver);
  73258. }
  73259. if (callback) {
  73260. this._onActivateObserver = this.onActivateObservable.add(callback);
  73261. }
  73262. },
  73263. enumerable: true,
  73264. configurable: true
  73265. });
  73266. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  73267. /**
  73268. * A function that is added to the onSizeChangedObservable
  73269. */
  73270. set: function (callback) {
  73271. if (this._onSizeChangedObserver) {
  73272. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  73273. }
  73274. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  73275. },
  73276. enumerable: true,
  73277. configurable: true
  73278. });
  73279. Object.defineProperty(PostProcess.prototype, "onApply", {
  73280. /**
  73281. * A function that is added to the onApplyObservable
  73282. */
  73283. set: function (callback) {
  73284. if (this._onApplyObserver) {
  73285. this.onApplyObservable.remove(this._onApplyObserver);
  73286. }
  73287. this._onApplyObserver = this.onApplyObservable.add(callback);
  73288. },
  73289. enumerable: true,
  73290. configurable: true
  73291. });
  73292. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  73293. /**
  73294. * A function that is added to the onBeforeRenderObservable
  73295. */
  73296. set: function (callback) {
  73297. if (this._onBeforeRenderObserver) {
  73298. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  73299. }
  73300. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  73301. },
  73302. enumerable: true,
  73303. configurable: true
  73304. });
  73305. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  73306. /**
  73307. * A function that is added to the onAfterRenderObservable
  73308. */
  73309. set: function (callback) {
  73310. if (this._onAfterRenderObserver) {
  73311. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  73312. }
  73313. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  73314. },
  73315. enumerable: true,
  73316. configurable: true
  73317. });
  73318. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  73319. /**
  73320. * 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
  73321. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  73322. */
  73323. get: function () {
  73324. return this._textures.data[this._currentRenderTextureInd];
  73325. },
  73326. set: function (value) {
  73327. this._forcedOutputTexture = value;
  73328. },
  73329. enumerable: true,
  73330. configurable: true
  73331. });
  73332. /**
  73333. * Gets the camera which post process is applied to.
  73334. * @returns The camera the post process is applied to.
  73335. */
  73336. PostProcess.prototype.getCamera = function () {
  73337. return this._camera;
  73338. };
  73339. Object.defineProperty(PostProcess.prototype, "texelSize", {
  73340. /**
  73341. * Gets the texel size of the postprocess.
  73342. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  73343. */
  73344. get: function () {
  73345. if (this._shareOutputWithPostProcess) {
  73346. return this._shareOutputWithPostProcess.texelSize;
  73347. }
  73348. if (this._forcedOutputTexture) {
  73349. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  73350. }
  73351. return this._texelSize;
  73352. },
  73353. enumerable: true,
  73354. configurable: true
  73355. });
  73356. /**
  73357. * Gets the engine which this post process belongs to.
  73358. * @returns The engine the post process was enabled with.
  73359. */
  73360. PostProcess.prototype.getEngine = function () {
  73361. return this._engine;
  73362. };
  73363. /**
  73364. * The effect that is created when initializing the post process.
  73365. * @returns The created effect corrisponding the the postprocess.
  73366. */
  73367. PostProcess.prototype.getEffect = function () {
  73368. return this._effect;
  73369. };
  73370. /**
  73371. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  73372. * @param postProcess The post process to share the output with.
  73373. * @returns This post process.
  73374. */
  73375. PostProcess.prototype.shareOutputWith = function (postProcess) {
  73376. this._disposeTextures();
  73377. this._shareOutputWithPostProcess = postProcess;
  73378. return this;
  73379. };
  73380. /**
  73381. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  73382. * This should be called if the post process that shares output with this post process is disabled/disposed.
  73383. */
  73384. PostProcess.prototype.useOwnOutput = function () {
  73385. if (this._textures.length == 0) {
  73386. this._textures = new BABYLON.SmartArray(2);
  73387. }
  73388. this._shareOutputWithPostProcess = null;
  73389. };
  73390. /**
  73391. * Updates the effect with the current post process compile time values and recompiles the shader.
  73392. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  73393. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  73394. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  73395. * @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
  73396. * @param onCompiled Called when the shader has been compiled.
  73397. * @param onError Called if there is an error when compiling a shader.
  73398. */
  73399. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  73400. if (defines === void 0) { defines = null; }
  73401. if (uniforms === void 0) { uniforms = null; }
  73402. if (samplers === void 0) { samplers = null; }
  73403. 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);
  73404. };
  73405. /**
  73406. * The post process is reusable if it can be used multiple times within one frame.
  73407. * @returns If the post process is reusable
  73408. */
  73409. PostProcess.prototype.isReusable = function () {
  73410. return this._reusable;
  73411. };
  73412. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  73413. PostProcess.prototype.markTextureDirty = function () {
  73414. this.width = -1;
  73415. };
  73416. /**
  73417. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  73418. * 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.
  73419. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  73420. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  73421. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  73422. * @returns The target texture that was bound to be written to.
  73423. */
  73424. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  73425. var _this = this;
  73426. if (sourceTexture === void 0) { sourceTexture = null; }
  73427. camera = camera || this._camera;
  73428. var scene = camera.getScene();
  73429. var engine = scene.getEngine();
  73430. var maxSize = engine.getCaps().maxTextureSize;
  73431. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  73432. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  73433. // 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
  73434. var webVRCamera = camera.parent;
  73435. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  73436. requiredWidth /= 2;
  73437. }
  73438. var desiredWidth = (this._options.width || requiredWidth);
  73439. var desiredHeight = this._options.height || requiredHeight;
  73440. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  73441. if (this.adaptScaleToCurrentViewport) {
  73442. var currentViewport = engine.currentViewport;
  73443. if (currentViewport) {
  73444. desiredWidth *= currentViewport.width;
  73445. desiredHeight *= currentViewport.height;
  73446. }
  73447. }
  73448. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  73449. if (!this._options.width) {
  73450. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  73451. }
  73452. if (!this._options.height) {
  73453. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  73454. }
  73455. }
  73456. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  73457. if (this._textures.length > 0) {
  73458. for (var i = 0; i < this._textures.length; i++) {
  73459. this._engine._releaseTexture(this._textures.data[i]);
  73460. }
  73461. this._textures.reset();
  73462. }
  73463. this.width = desiredWidth;
  73464. this.height = desiredHeight;
  73465. var textureSize = { width: this.width, height: this.height };
  73466. var textureOptions = {
  73467. generateMipMaps: false,
  73468. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  73469. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  73470. samplingMode: this.renderTargetSamplingMode,
  73471. type: this._textureType
  73472. };
  73473. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  73474. if (this._reusable) {
  73475. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  73476. }
  73477. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  73478. this.onSizeChangedObservable.notifyObservers(this);
  73479. }
  73480. this._textures.forEach(function (texture) {
  73481. if (texture.samples !== _this.samples) {
  73482. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  73483. }
  73484. });
  73485. }
  73486. var target;
  73487. if (this._shareOutputWithPostProcess) {
  73488. target = this._shareOutputWithPostProcess.inputTexture;
  73489. }
  73490. else if (this._forcedOutputTexture) {
  73491. target = this._forcedOutputTexture;
  73492. this.width = this._forcedOutputTexture.width;
  73493. this.height = this._forcedOutputTexture.height;
  73494. }
  73495. else {
  73496. target = this.inputTexture;
  73497. }
  73498. // Bind the input of this post process to be used as the output of the previous post process.
  73499. if (this.enablePixelPerfectMode) {
  73500. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  73501. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  73502. }
  73503. else {
  73504. this._scaleRatio.copyFromFloats(1, 1);
  73505. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  73506. }
  73507. this.onActivateObservable.notifyObservers(camera);
  73508. // Clear
  73509. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  73510. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  73511. }
  73512. if (this._reusable) {
  73513. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  73514. }
  73515. return target;
  73516. };
  73517. Object.defineProperty(PostProcess.prototype, "isSupported", {
  73518. /**
  73519. * If the post process is supported.
  73520. */
  73521. get: function () {
  73522. return this._effect.isSupported;
  73523. },
  73524. enumerable: true,
  73525. configurable: true
  73526. });
  73527. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  73528. /**
  73529. * The aspect ratio of the output texture.
  73530. */
  73531. get: function () {
  73532. if (this._shareOutputWithPostProcess) {
  73533. return this._shareOutputWithPostProcess.aspectRatio;
  73534. }
  73535. if (this._forcedOutputTexture) {
  73536. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  73537. }
  73538. return this.width / this.height;
  73539. },
  73540. enumerable: true,
  73541. configurable: true
  73542. });
  73543. /**
  73544. * Get a value indicating if the post-process is ready to be used
  73545. * @returns true if the post-process is ready (shader is compiled)
  73546. */
  73547. PostProcess.prototype.isReady = function () {
  73548. return this._effect && this._effect.isReady();
  73549. };
  73550. /**
  73551. * Binds all textures and uniforms to the shader, this will be run on every pass.
  73552. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  73553. */
  73554. PostProcess.prototype.apply = function () {
  73555. // Check
  73556. if (!this._effect || !this._effect.isReady())
  73557. return null;
  73558. // States
  73559. this._engine.enableEffect(this._effect);
  73560. this._engine.setState(false);
  73561. this._engine.setDepthBuffer(false);
  73562. this._engine.setDepthWrite(false);
  73563. // Alpha
  73564. this._engine.setAlphaMode(this.alphaMode);
  73565. if (this.alphaConstants) {
  73566. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  73567. }
  73568. // Bind the output texture of the preivous post process as the input to this post process.
  73569. var source;
  73570. if (this._shareOutputWithPostProcess) {
  73571. source = this._shareOutputWithPostProcess.inputTexture;
  73572. }
  73573. else if (this._forcedOutputTexture) {
  73574. source = this._forcedOutputTexture;
  73575. }
  73576. else {
  73577. source = this.inputTexture;
  73578. }
  73579. this._effect._bindTexture("textureSampler", source);
  73580. // Parameters
  73581. this._effect.setVector2("scale", this._scaleRatio);
  73582. this.onApplyObservable.notifyObservers(this._effect);
  73583. return this._effect;
  73584. };
  73585. PostProcess.prototype._disposeTextures = function () {
  73586. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  73587. return;
  73588. }
  73589. if (this._textures.length > 0) {
  73590. for (var i = 0; i < this._textures.length; i++) {
  73591. this._engine._releaseTexture(this._textures.data[i]);
  73592. }
  73593. }
  73594. this._textures.dispose();
  73595. };
  73596. /**
  73597. * Disposes the post process.
  73598. * @param camera The camera to dispose the post process on.
  73599. */
  73600. PostProcess.prototype.dispose = function (camera) {
  73601. camera = camera || this._camera;
  73602. this._disposeTextures();
  73603. if (this._scene) {
  73604. var index_1 = this._scene.postProcesses.indexOf(this);
  73605. if (index_1 !== -1) {
  73606. this._scene.postProcesses.splice(index_1, 1);
  73607. }
  73608. }
  73609. else {
  73610. var index_2 = this._engine.postProcesses.indexOf(this);
  73611. if (index_2 !== -1) {
  73612. this._engine.postProcesses.splice(index_2, 1);
  73613. }
  73614. }
  73615. if (!camera) {
  73616. return;
  73617. }
  73618. camera.detachPostProcess(this);
  73619. var index = camera._postProcesses.indexOf(this);
  73620. if (index === 0 && camera._postProcesses.length > 0) {
  73621. var firstPostProcess = this._camera._getFirstPostProcess();
  73622. if (firstPostProcess) {
  73623. firstPostProcess.markTextureDirty();
  73624. }
  73625. }
  73626. this.onActivateObservable.clear();
  73627. this.onAfterRenderObservable.clear();
  73628. this.onApplyObservable.clear();
  73629. this.onBeforeRenderObservable.clear();
  73630. this.onSizeChangedObservable.clear();
  73631. };
  73632. return PostProcess;
  73633. }());
  73634. BABYLON.PostProcess = PostProcess;
  73635. })(BABYLON || (BABYLON = {}));
  73636. //# sourceMappingURL=babylon.postProcess.js.map
  73637. var BABYLON;
  73638. (function (BABYLON) {
  73639. var PassPostProcess = /** @class */ (function (_super) {
  73640. __extends(PassPostProcess, _super);
  73641. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73642. if (camera === void 0) { camera = null; }
  73643. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73644. if (blockCompilation === void 0) { blockCompilation = false; }
  73645. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  73646. }
  73647. return PassPostProcess;
  73648. }(BABYLON.PostProcess));
  73649. BABYLON.PassPostProcess = PassPostProcess;
  73650. })(BABYLON || (BABYLON = {}));
  73651. //# sourceMappingURL=babylon.passPostProcess.js.map
  73652. var __assign = (this && this.__assign) || function () {
  73653. __assign = Object.assign || function(t) {
  73654. for (var s, i = 1, n = arguments.length; i < n; i++) {
  73655. s = arguments[i];
  73656. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  73657. t[p] = s[p];
  73658. }
  73659. return t;
  73660. };
  73661. return __assign.apply(this, arguments);
  73662. };
  73663. var BABYLON;
  73664. (function (BABYLON) {
  73665. /**
  73666. * Default implementation IShadowGenerator.
  73667. * This is the main object responsible of generating shadows in the framework.
  73668. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  73669. */
  73670. var ShadowGenerator = /** @class */ (function () {
  73671. /**
  73672. * Creates a ShadowGenerator object.
  73673. * A ShadowGenerator is the required tool to use the shadows.
  73674. * Each light casting shadows needs to use its own ShadowGenerator.
  73675. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  73676. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  73677. * @param light The light object generating the shadows.
  73678. * @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.
  73679. */
  73680. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  73681. this._bias = 0.00005;
  73682. this._normalBias = 0;
  73683. this._blurBoxOffset = 1;
  73684. this._blurScale = 2;
  73685. this._blurKernel = 1;
  73686. this._useKernelBlur = false;
  73687. this._filter = ShadowGenerator.FILTER_NONE;
  73688. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  73689. this._contactHardeningLightSizeUVRatio = 0.1;
  73690. this._darkness = 0;
  73691. this._transparencyShadow = false;
  73692. /**
  73693. * Controls the extent to which the shadows fade out at the edge of the frustum
  73694. * Used only by directionals and spots
  73695. */
  73696. this.frustumEdgeFalloff = 0;
  73697. /**
  73698. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  73699. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  73700. * It might on the other hand introduce peter panning.
  73701. */
  73702. this.forceBackFacesOnly = false;
  73703. this._lightDirection = BABYLON.Vector3.Zero();
  73704. this._viewMatrix = BABYLON.Matrix.Zero();
  73705. this._projectionMatrix = BABYLON.Matrix.Zero();
  73706. this._transformMatrix = BABYLON.Matrix.Zero();
  73707. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  73708. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  73709. this._currentFaceIndex = 0;
  73710. this._currentFaceIndexCache = 0;
  73711. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  73712. this._mapSize = mapSize;
  73713. this._light = light;
  73714. this._scene = light.getScene();
  73715. light._shadowGenerator = this;
  73716. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  73717. if (!component) {
  73718. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  73719. this._scene._addComponent(component);
  73720. }
  73721. // Texture type fallback from float to int if not supported.
  73722. var caps = this._scene.getEngine().getCaps();
  73723. if (!useFullFloatFirst) {
  73724. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  73725. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73726. }
  73727. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  73728. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73729. }
  73730. else {
  73731. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73732. }
  73733. }
  73734. else {
  73735. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  73736. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73737. }
  73738. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  73739. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73740. }
  73741. else {
  73742. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73743. }
  73744. }
  73745. this._initializeGenerator();
  73746. this._applyFilterValues();
  73747. }
  73748. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  73749. /**
  73750. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  73751. */
  73752. get: function () {
  73753. return this._bias;
  73754. },
  73755. /**
  73756. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  73757. */
  73758. set: function (bias) {
  73759. this._bias = bias;
  73760. },
  73761. enumerable: true,
  73762. configurable: true
  73763. });
  73764. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  73765. /**
  73766. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  73767. */
  73768. get: function () {
  73769. return this._normalBias;
  73770. },
  73771. /**
  73772. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  73773. */
  73774. set: function (normalBias) {
  73775. this._normalBias = normalBias;
  73776. },
  73777. enumerable: true,
  73778. configurable: true
  73779. });
  73780. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  73781. /**
  73782. * Gets the blur box offset: offset applied during the blur pass.
  73783. * Only usefull if useKernelBlur = false
  73784. */
  73785. get: function () {
  73786. return this._blurBoxOffset;
  73787. },
  73788. /**
  73789. * Sets the blur box offset: offset applied during the blur pass.
  73790. * Only usefull if useKernelBlur = false
  73791. */
  73792. set: function (value) {
  73793. if (this._blurBoxOffset === value) {
  73794. return;
  73795. }
  73796. this._blurBoxOffset = value;
  73797. this._disposeBlurPostProcesses();
  73798. },
  73799. enumerable: true,
  73800. configurable: true
  73801. });
  73802. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  73803. /**
  73804. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  73805. * 2 means half of the size.
  73806. */
  73807. get: function () {
  73808. return this._blurScale;
  73809. },
  73810. /**
  73811. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  73812. * 2 means half of the size.
  73813. */
  73814. set: function (value) {
  73815. if (this._blurScale === value) {
  73816. return;
  73817. }
  73818. this._blurScale = value;
  73819. this._disposeBlurPostProcesses();
  73820. },
  73821. enumerable: true,
  73822. configurable: true
  73823. });
  73824. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  73825. /**
  73826. * Gets the blur kernel: kernel size of the blur pass.
  73827. * Only usefull if useKernelBlur = true
  73828. */
  73829. get: function () {
  73830. return this._blurKernel;
  73831. },
  73832. /**
  73833. * Sets the blur kernel: kernel size of the blur pass.
  73834. * Only usefull if useKernelBlur = true
  73835. */
  73836. set: function (value) {
  73837. if (this._blurKernel === value) {
  73838. return;
  73839. }
  73840. this._blurKernel = value;
  73841. this._disposeBlurPostProcesses();
  73842. },
  73843. enumerable: true,
  73844. configurable: true
  73845. });
  73846. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  73847. /**
  73848. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  73849. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  73850. */
  73851. get: function () {
  73852. return this._useKernelBlur;
  73853. },
  73854. /**
  73855. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  73856. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  73857. */
  73858. set: function (value) {
  73859. if (this._useKernelBlur === value) {
  73860. return;
  73861. }
  73862. this._useKernelBlur = value;
  73863. this._disposeBlurPostProcesses();
  73864. },
  73865. enumerable: true,
  73866. configurable: true
  73867. });
  73868. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  73869. /**
  73870. * Gets the depth scale used in ESM mode.
  73871. */
  73872. get: function () {
  73873. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  73874. },
  73875. /**
  73876. * Sets the depth scale used in ESM mode.
  73877. * This can override the scale stored on the light.
  73878. */
  73879. set: function (value) {
  73880. this._depthScale = value;
  73881. },
  73882. enumerable: true,
  73883. configurable: true
  73884. });
  73885. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  73886. /**
  73887. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  73888. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  73889. */
  73890. get: function () {
  73891. return this._filter;
  73892. },
  73893. /**
  73894. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  73895. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  73896. */
  73897. set: function (value) {
  73898. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  73899. if (this._light.needCube()) {
  73900. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  73901. this.useExponentialShadowMap = true;
  73902. return;
  73903. }
  73904. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  73905. this.useCloseExponentialShadowMap = true;
  73906. return;
  73907. }
  73908. // PCF on cubemap would also be expensive
  73909. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  73910. this.usePoissonSampling = true;
  73911. return;
  73912. }
  73913. }
  73914. // Weblg1 fallback for PCF.
  73915. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  73916. if (this._scene.getEngine().webGLVersion === 1) {
  73917. this.usePoissonSampling = true;
  73918. return;
  73919. }
  73920. }
  73921. if (this._filter === value) {
  73922. return;
  73923. }
  73924. this._filter = value;
  73925. this._disposeBlurPostProcesses();
  73926. this._applyFilterValues();
  73927. this._light._markMeshesAsLightDirty();
  73928. },
  73929. enumerable: true,
  73930. configurable: true
  73931. });
  73932. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  73933. /**
  73934. * Gets if the current filter is set to Poisson Sampling.
  73935. */
  73936. get: function () {
  73937. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  73938. },
  73939. /**
  73940. * Sets the current filter to Poisson Sampling.
  73941. */
  73942. set: function (value) {
  73943. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  73944. return;
  73945. }
  73946. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  73947. },
  73948. enumerable: true,
  73949. configurable: true
  73950. });
  73951. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  73952. /**
  73953. * Gets if the current filter is set to VSM.
  73954. * DEPRECATED. Should use useExponentialShadowMap instead.
  73955. */
  73956. get: function () {
  73957. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  73958. return this.useExponentialShadowMap;
  73959. },
  73960. /**
  73961. * Sets the current filter is to VSM.
  73962. * DEPRECATED. Should use useExponentialShadowMap instead.
  73963. */
  73964. set: function (value) {
  73965. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  73966. this.useExponentialShadowMap = value;
  73967. },
  73968. enumerable: true,
  73969. configurable: true
  73970. });
  73971. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  73972. /**
  73973. * Gets if the current filter is set to blurred VSM.
  73974. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  73975. */
  73976. get: function () {
  73977. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  73978. return this.useBlurExponentialShadowMap;
  73979. },
  73980. /**
  73981. * Sets the current filter is to blurred VSM.
  73982. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  73983. */
  73984. set: function (value) {
  73985. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  73986. this.useBlurExponentialShadowMap = value;
  73987. },
  73988. enumerable: true,
  73989. configurable: true
  73990. });
  73991. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  73992. /**
  73993. * Gets if the current filter is set to ESM.
  73994. */
  73995. get: function () {
  73996. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  73997. },
  73998. /**
  73999. * Sets the current filter is to ESM.
  74000. */
  74001. set: function (value) {
  74002. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  74003. return;
  74004. }
  74005. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  74006. },
  74007. enumerable: true,
  74008. configurable: true
  74009. });
  74010. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  74011. /**
  74012. * Gets if the current filter is set to filtered ESM.
  74013. */
  74014. get: function () {
  74015. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  74016. },
  74017. /**
  74018. * Gets if the current filter is set to filtered ESM.
  74019. */
  74020. set: function (value) {
  74021. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  74022. return;
  74023. }
  74024. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  74025. },
  74026. enumerable: true,
  74027. configurable: true
  74028. });
  74029. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  74030. /**
  74031. * Gets if the current filter is set to "close ESM" (using the inverse of the
  74032. * exponential to prevent steep falloff artifacts).
  74033. */
  74034. get: function () {
  74035. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  74036. },
  74037. /**
  74038. * Sets the current filter to "close ESM" (using the inverse of the
  74039. * exponential to prevent steep falloff artifacts).
  74040. */
  74041. set: function (value) {
  74042. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  74043. return;
  74044. }
  74045. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  74046. },
  74047. enumerable: true,
  74048. configurable: true
  74049. });
  74050. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  74051. /**
  74052. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  74053. * exponential to prevent steep falloff artifacts).
  74054. */
  74055. get: function () {
  74056. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  74057. },
  74058. /**
  74059. * Sets the current filter to filtered "close ESM" (using the inverse of the
  74060. * exponential to prevent steep falloff artifacts).
  74061. */
  74062. set: function (value) {
  74063. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  74064. return;
  74065. }
  74066. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  74067. },
  74068. enumerable: true,
  74069. configurable: true
  74070. });
  74071. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  74072. /**
  74073. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  74074. */
  74075. get: function () {
  74076. return this.filter === ShadowGenerator.FILTER_PCF;
  74077. },
  74078. /**
  74079. * Sets the current filter to "PCF" (percentage closer filtering).
  74080. */
  74081. set: function (value) {
  74082. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  74083. return;
  74084. }
  74085. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  74086. },
  74087. enumerable: true,
  74088. configurable: true
  74089. });
  74090. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  74091. /**
  74092. * Gets the PCF or PCSS Quality.
  74093. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  74094. */
  74095. get: function () {
  74096. return this._filteringQuality;
  74097. },
  74098. /**
  74099. * Sets the PCF or PCSS Quality.
  74100. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  74101. */
  74102. set: function (filteringQuality) {
  74103. this._filteringQuality = filteringQuality;
  74104. },
  74105. enumerable: true,
  74106. configurable: true
  74107. });
  74108. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  74109. /**
  74110. * Gets if the current filter is set to "PCSS" (contact hardening).
  74111. */
  74112. get: function () {
  74113. return this.filter === ShadowGenerator.FILTER_PCSS;
  74114. },
  74115. /**
  74116. * Sets the current filter to "PCSS" (contact hardening).
  74117. */
  74118. set: function (value) {
  74119. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  74120. return;
  74121. }
  74122. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  74123. },
  74124. enumerable: true,
  74125. configurable: true
  74126. });
  74127. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  74128. /**
  74129. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  74130. * Using a ratio helps keeping shape stability independently of the map size.
  74131. *
  74132. * It does not account for the light projection as it was having too much
  74133. * instability during the light setup or during light position changes.
  74134. *
  74135. * Only valid if useContactHardeningShadow is true.
  74136. */
  74137. get: function () {
  74138. return this._contactHardeningLightSizeUVRatio;
  74139. },
  74140. /**
  74141. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  74142. * Using a ratio helps keeping shape stability independently of the map size.
  74143. *
  74144. * It does not account for the light projection as it was having too much
  74145. * instability during the light setup or during light position changes.
  74146. *
  74147. * Only valid if useContactHardeningShadow is true.
  74148. */
  74149. set: function (contactHardeningLightSizeUVRatio) {
  74150. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  74151. },
  74152. enumerable: true,
  74153. configurable: true
  74154. });
  74155. /**
  74156. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  74157. * 0 means strongest and 1 would means no shadow.
  74158. * @returns the darkness.
  74159. */
  74160. ShadowGenerator.prototype.getDarkness = function () {
  74161. return this._darkness;
  74162. };
  74163. /**
  74164. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  74165. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  74166. * @returns the shadow generator allowing fluent coding.
  74167. */
  74168. ShadowGenerator.prototype.setDarkness = function (darkness) {
  74169. if (darkness >= 1.0)
  74170. this._darkness = 1.0;
  74171. else if (darkness <= 0.0)
  74172. this._darkness = 0.0;
  74173. else
  74174. this._darkness = darkness;
  74175. return this;
  74176. };
  74177. /**
  74178. * Sets the ability to have transparent shadow (boolean).
  74179. * @param transparent True if transparent else False
  74180. * @returns the shadow generator allowing fluent coding
  74181. */
  74182. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  74183. this._transparencyShadow = transparent;
  74184. return this;
  74185. };
  74186. /**
  74187. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  74188. * @returns The render target texture if present otherwise, null
  74189. */
  74190. ShadowGenerator.prototype.getShadowMap = function () {
  74191. return this._shadowMap;
  74192. };
  74193. /**
  74194. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  74195. * @returns The render target texture if the shadow map is present otherwise, null
  74196. */
  74197. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  74198. if (this._shadowMap2) {
  74199. return this._shadowMap2;
  74200. }
  74201. return this._shadowMap;
  74202. };
  74203. /**
  74204. * Helper function to add a mesh and its descendants to the list of shadow casters.
  74205. * @param mesh Mesh to add
  74206. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  74207. * @returns the Shadow Generator itself
  74208. */
  74209. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  74210. if (includeDescendants === void 0) { includeDescendants = true; }
  74211. var _a;
  74212. if (!this._shadowMap) {
  74213. return this;
  74214. }
  74215. if (!this._shadowMap.renderList) {
  74216. this._shadowMap.renderList = [];
  74217. }
  74218. this._shadowMap.renderList.push(mesh);
  74219. if (includeDescendants) {
  74220. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  74221. }
  74222. return this;
  74223. };
  74224. /**
  74225. * Helper function to remove a mesh and its descendants from the list of shadow casters
  74226. * @param mesh Mesh to remove
  74227. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  74228. * @returns the Shadow Generator itself
  74229. */
  74230. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  74231. if (includeDescendants === void 0) { includeDescendants = true; }
  74232. if (!this._shadowMap || !this._shadowMap.renderList) {
  74233. return this;
  74234. }
  74235. var index = this._shadowMap.renderList.indexOf(mesh);
  74236. if (index !== -1) {
  74237. this._shadowMap.renderList.splice(index, 1);
  74238. }
  74239. if (includeDescendants) {
  74240. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  74241. var child = _a[_i];
  74242. this.removeShadowCaster(child);
  74243. }
  74244. }
  74245. return this;
  74246. };
  74247. /**
  74248. * Returns the associated light object.
  74249. * @returns the light generating the shadow
  74250. */
  74251. ShadowGenerator.prototype.getLight = function () {
  74252. return this._light;
  74253. };
  74254. ShadowGenerator.prototype._initializeGenerator = function () {
  74255. this._light._markMeshesAsLightDirty();
  74256. this._initializeShadowMap();
  74257. };
  74258. ShadowGenerator.prototype._initializeShadowMap = function () {
  74259. var _this = this;
  74260. // Render target
  74261. var engine = this._scene.getEngine();
  74262. if (engine.webGLVersion > 1) {
  74263. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  74264. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  74265. }
  74266. else {
  74267. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  74268. }
  74269. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74270. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74271. this._shadowMap.anisotropicFilteringLevel = 1;
  74272. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74273. this._shadowMap.renderParticles = false;
  74274. this._shadowMap.ignoreCameraViewport = true;
  74275. // Record Face Index before render.
  74276. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  74277. _this._currentFaceIndex = faceIndex;
  74278. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  74279. engine.setColorWrite(false);
  74280. }
  74281. });
  74282. // Custom render function.
  74283. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  74284. // Blur if required afer render.
  74285. this._shadowMap.onAfterUnbindObservable.add(function () {
  74286. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  74287. engine.setColorWrite(true);
  74288. }
  74289. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  74290. return;
  74291. }
  74292. var shadowMap = _this.getShadowMapForRendering();
  74293. if (shadowMap) {
  74294. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  74295. }
  74296. });
  74297. // Clear according to the chosen filter.
  74298. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  74299. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  74300. this._shadowMap.onClearObservable.add(function (engine) {
  74301. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  74302. engine.clear(clearOne, false, true, false);
  74303. }
  74304. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  74305. engine.clear(clearZero, true, true, false);
  74306. }
  74307. else {
  74308. engine.clear(clearOne, true, true, false);
  74309. }
  74310. });
  74311. };
  74312. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  74313. var _this = this;
  74314. var engine = this._scene.getEngine();
  74315. var targetSize = this._mapSize / this.blurScale;
  74316. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  74317. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  74318. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74319. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74320. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74321. }
  74322. if (this.useKernelBlur) {
  74323. 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);
  74324. this._kernelBlurXPostprocess.width = targetSize;
  74325. this._kernelBlurXPostprocess.height = targetSize;
  74326. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  74327. effect.setTexture("textureSampler", _this._shadowMap);
  74328. });
  74329. 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);
  74330. this._kernelBlurXPostprocess.autoClear = false;
  74331. this._kernelBlurYPostprocess.autoClear = false;
  74332. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74333. this._kernelBlurXPostprocess.packedFloat = true;
  74334. this._kernelBlurYPostprocess.packedFloat = true;
  74335. }
  74336. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  74337. }
  74338. else {
  74339. 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);
  74340. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  74341. effect.setFloat2("screenSize", targetSize, targetSize);
  74342. effect.setTexture("textureSampler", _this._shadowMap);
  74343. });
  74344. this._boxBlurPostprocess.autoClear = false;
  74345. this._blurPostProcesses = [this._boxBlurPostprocess];
  74346. }
  74347. };
  74348. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  74349. var index;
  74350. var engine = this._scene.getEngine();
  74351. if (depthOnlySubMeshes.length) {
  74352. engine.setColorWrite(false);
  74353. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  74354. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  74355. }
  74356. engine.setColorWrite(true);
  74357. }
  74358. for (index = 0; index < opaqueSubMeshes.length; index++) {
  74359. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  74360. }
  74361. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  74362. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  74363. }
  74364. if (this._transparencyShadow) {
  74365. for (index = 0; index < transparentSubMeshes.length; index++) {
  74366. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  74367. }
  74368. }
  74369. };
  74370. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  74371. var _this = this;
  74372. var mesh = subMesh.getRenderingMesh();
  74373. var scene = this._scene;
  74374. var engine = scene.getEngine();
  74375. var material = subMesh.getMaterial();
  74376. if (!material) {
  74377. return;
  74378. }
  74379. // Culling
  74380. engine.setState(material.backFaceCulling);
  74381. // Managing instances
  74382. var batch = mesh._getInstancesRenderList(subMesh._id);
  74383. if (batch.mustReturn) {
  74384. return;
  74385. }
  74386. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  74387. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  74388. engine.enableEffect(this._effect);
  74389. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  74390. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  74391. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  74392. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  74393. this._effect.setVector3("lightData", this._cachedDirection);
  74394. }
  74395. else {
  74396. this._effect.setVector3("lightData", this._cachedPosition);
  74397. }
  74398. if (scene.activeCamera) {
  74399. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  74400. }
  74401. // Alpha test
  74402. if (material && material.needAlphaTesting()) {
  74403. var alphaTexture = material.getAlphaTestTexture();
  74404. if (alphaTexture) {
  74405. this._effect.setTexture("diffuseSampler", alphaTexture);
  74406. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  74407. }
  74408. }
  74409. // Bones
  74410. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  74411. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  74412. }
  74413. // Morph targets
  74414. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  74415. if (this.forceBackFacesOnly) {
  74416. engine.setState(true, 0, false, true);
  74417. }
  74418. // Draw
  74419. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  74420. if (this.forceBackFacesOnly) {
  74421. engine.setState(true, 0, false, false);
  74422. }
  74423. }
  74424. else {
  74425. // Need to reset refresh rate of the shadowMap
  74426. if (this._shadowMap) {
  74427. this._shadowMap.resetRefreshCounter();
  74428. }
  74429. }
  74430. };
  74431. ShadowGenerator.prototype._applyFilterValues = function () {
  74432. if (!this._shadowMap) {
  74433. return;
  74434. }
  74435. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  74436. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  74437. }
  74438. else {
  74439. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74440. }
  74441. };
  74442. /**
  74443. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  74444. * @param onCompiled Callback triggered at the and of the effects compilation
  74445. * @param options Sets of optional options forcing the compilation with different modes
  74446. */
  74447. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  74448. var _this = this;
  74449. var localOptions = __assign({ useInstances: false }, options);
  74450. var shadowMap = this.getShadowMap();
  74451. if (!shadowMap) {
  74452. if (onCompiled) {
  74453. onCompiled(this);
  74454. }
  74455. return;
  74456. }
  74457. var renderList = shadowMap.renderList;
  74458. if (!renderList) {
  74459. if (onCompiled) {
  74460. onCompiled(this);
  74461. }
  74462. return;
  74463. }
  74464. var subMeshes = new Array();
  74465. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  74466. var mesh = renderList_1[_i];
  74467. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  74468. }
  74469. if (subMeshes.length === 0) {
  74470. if (onCompiled) {
  74471. onCompiled(this);
  74472. }
  74473. return;
  74474. }
  74475. var currentIndex = 0;
  74476. var checkReady = function () {
  74477. if (!_this._scene || !_this._scene.getEngine()) {
  74478. return;
  74479. }
  74480. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  74481. currentIndex++;
  74482. if (currentIndex >= subMeshes.length) {
  74483. if (onCompiled) {
  74484. onCompiled(_this);
  74485. }
  74486. return;
  74487. }
  74488. }
  74489. setTimeout(checkReady, 16);
  74490. };
  74491. checkReady();
  74492. };
  74493. /**
  74494. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  74495. * @param options Sets of optional options forcing the compilation with different modes
  74496. * @returns A promise that resolves when the compilation completes
  74497. */
  74498. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  74499. var _this = this;
  74500. return new Promise(function (resolve) {
  74501. _this.forceCompilation(function () {
  74502. resolve();
  74503. }, options);
  74504. });
  74505. };
  74506. /**
  74507. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  74508. * @param subMesh The submesh we want to render in the shadow map
  74509. * @param useInstances Defines wether will draw in the map using instances
  74510. * @returns true if ready otherwise, false
  74511. */
  74512. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  74513. var defines = [];
  74514. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74515. defines.push("#define FLOAT");
  74516. }
  74517. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  74518. defines.push("#define ESM");
  74519. }
  74520. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  74521. defines.push("#define DEPTHTEXTURE");
  74522. }
  74523. var attribs = [BABYLON.VertexBuffer.PositionKind];
  74524. var mesh = subMesh.getMesh();
  74525. var material = subMesh.getMaterial();
  74526. // Normal bias.
  74527. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  74528. attribs.push(BABYLON.VertexBuffer.NormalKind);
  74529. defines.push("#define NORMAL");
  74530. if (mesh.nonUniformScaling) {
  74531. defines.push("#define NONUNIFORMSCALING");
  74532. }
  74533. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  74534. defines.push("#define DIRECTIONINLIGHTDATA");
  74535. }
  74536. }
  74537. // Alpha test
  74538. if (material && material.needAlphaTesting()) {
  74539. var alphaTexture = material.getAlphaTestTexture();
  74540. if (alphaTexture) {
  74541. defines.push("#define ALPHATEST");
  74542. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  74543. attribs.push(BABYLON.VertexBuffer.UVKind);
  74544. defines.push("#define UV1");
  74545. }
  74546. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  74547. if (alphaTexture.coordinatesIndex === 1) {
  74548. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  74549. defines.push("#define UV2");
  74550. }
  74551. }
  74552. }
  74553. }
  74554. // Bones
  74555. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  74556. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  74557. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  74558. if (mesh.numBoneInfluencers > 4) {
  74559. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  74560. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  74561. }
  74562. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  74563. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  74564. }
  74565. else {
  74566. defines.push("#define NUM_BONE_INFLUENCERS 0");
  74567. }
  74568. // Morph targets
  74569. var manager = mesh.morphTargetManager;
  74570. var morphInfluencers = 0;
  74571. if (manager) {
  74572. if (manager.numInfluencers > 0) {
  74573. defines.push("#define MORPHTARGETS");
  74574. morphInfluencers = manager.numInfluencers;
  74575. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  74576. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  74577. }
  74578. }
  74579. // Instances
  74580. if (useInstances) {
  74581. defines.push("#define INSTANCES");
  74582. attribs.push("world0");
  74583. attribs.push("world1");
  74584. attribs.push("world2");
  74585. attribs.push("world3");
  74586. }
  74587. // Get correct effect
  74588. var join = defines.join("\n");
  74589. if (this._cachedDefines !== join) {
  74590. this._cachedDefines = join;
  74591. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  74592. }
  74593. if (!this._effect.isReady()) {
  74594. return false;
  74595. }
  74596. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  74597. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  74598. this._initializeBlurRTTAndPostProcesses();
  74599. }
  74600. }
  74601. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  74602. return false;
  74603. }
  74604. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  74605. return false;
  74606. }
  74607. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  74608. return false;
  74609. }
  74610. return true;
  74611. };
  74612. /**
  74613. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  74614. * @param defines Defines of the material we want to update
  74615. * @param lightIndex Index of the light in the enabled light list of the material
  74616. */
  74617. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  74618. var scene = this._scene;
  74619. var light = this._light;
  74620. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  74621. return;
  74622. }
  74623. defines["SHADOW" + lightIndex] = true;
  74624. if (this.useContactHardeningShadow) {
  74625. defines["SHADOWPCSS" + lightIndex] = true;
  74626. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  74627. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  74628. }
  74629. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  74630. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  74631. }
  74632. // else default to high.
  74633. }
  74634. if (this.usePercentageCloserFiltering) {
  74635. defines["SHADOWPCF" + lightIndex] = true;
  74636. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  74637. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  74638. }
  74639. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  74640. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  74641. }
  74642. // else default to high.
  74643. }
  74644. else if (this.usePoissonSampling) {
  74645. defines["SHADOWPOISSON" + lightIndex] = true;
  74646. }
  74647. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  74648. defines["SHADOWESM" + lightIndex] = true;
  74649. }
  74650. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  74651. defines["SHADOWCLOSEESM" + lightIndex] = true;
  74652. }
  74653. if (light.needCube()) {
  74654. defines["SHADOWCUBE" + lightIndex] = true;
  74655. }
  74656. };
  74657. /**
  74658. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  74659. * defined in the generator but impacting the effect).
  74660. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  74661. * @param effect The effect we are binfing the information for
  74662. */
  74663. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  74664. var light = this._light;
  74665. var scene = this._scene;
  74666. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  74667. return;
  74668. }
  74669. var camera = scene.activeCamera;
  74670. if (!camera) {
  74671. return;
  74672. }
  74673. var shadowMap = this.getShadowMap();
  74674. if (!shadowMap) {
  74675. return;
  74676. }
  74677. if (!light.needCube()) {
  74678. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  74679. }
  74680. // Only PCF uses depth stencil texture.
  74681. if (this._filter === ShadowGenerator.FILTER_PCF) {
  74682. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  74683. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  74684. }
  74685. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  74686. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  74687. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  74688. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  74689. }
  74690. else {
  74691. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  74692. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  74693. }
  74694. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  74695. };
  74696. /**
  74697. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  74698. * (eq to shadow prjection matrix * light transform matrix)
  74699. * @returns The transform matrix used to create the shadow map
  74700. */
  74701. ShadowGenerator.prototype.getTransformMatrix = function () {
  74702. var scene = this._scene;
  74703. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  74704. return this._transformMatrix;
  74705. }
  74706. this._currentRenderID = scene.getRenderId();
  74707. this._currentFaceIndexCache = this._currentFaceIndex;
  74708. var lightPosition = this._light.position;
  74709. if (this._light.computeTransformedInformation()) {
  74710. lightPosition = this._light.transformedPosition;
  74711. }
  74712. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  74713. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  74714. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  74715. }
  74716. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  74717. this._cachedPosition.copyFrom(lightPosition);
  74718. this._cachedDirection.copyFrom(this._lightDirection);
  74719. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  74720. var shadowMap = this.getShadowMap();
  74721. if (shadowMap) {
  74722. var renderList = shadowMap.renderList;
  74723. if (renderList) {
  74724. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  74725. }
  74726. }
  74727. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  74728. }
  74729. return this._transformMatrix;
  74730. };
  74731. /**
  74732. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  74733. * Cube and 2D textures for instance.
  74734. */
  74735. ShadowGenerator.prototype.recreateShadowMap = function () {
  74736. var shadowMap = this._shadowMap;
  74737. if (!shadowMap) {
  74738. return;
  74739. }
  74740. // Track render list.
  74741. var renderList = shadowMap.renderList;
  74742. // Clean up existing data.
  74743. this._disposeRTTandPostProcesses();
  74744. // Reinitializes.
  74745. this._initializeGenerator();
  74746. // Reaffect the filter to ensure a correct fallback if necessary.
  74747. this.filter = this.filter;
  74748. // Reaffect the filter.
  74749. this._applyFilterValues();
  74750. // Reaffect Render List.
  74751. this._shadowMap.renderList = renderList;
  74752. };
  74753. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  74754. if (this._shadowMap2) {
  74755. this._shadowMap2.dispose();
  74756. this._shadowMap2 = null;
  74757. }
  74758. if (this._boxBlurPostprocess) {
  74759. this._boxBlurPostprocess.dispose();
  74760. this._boxBlurPostprocess = null;
  74761. }
  74762. if (this._kernelBlurXPostprocess) {
  74763. this._kernelBlurXPostprocess.dispose();
  74764. this._kernelBlurXPostprocess = null;
  74765. }
  74766. if (this._kernelBlurYPostprocess) {
  74767. this._kernelBlurYPostprocess.dispose();
  74768. this._kernelBlurYPostprocess = null;
  74769. }
  74770. this._blurPostProcesses = [];
  74771. };
  74772. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  74773. if (this._shadowMap) {
  74774. this._shadowMap.dispose();
  74775. this._shadowMap = null;
  74776. }
  74777. this._disposeBlurPostProcesses();
  74778. };
  74779. /**
  74780. * Disposes the ShadowGenerator.
  74781. * Returns nothing.
  74782. */
  74783. ShadowGenerator.prototype.dispose = function () {
  74784. this._disposeRTTandPostProcesses();
  74785. if (this._light) {
  74786. this._light._shadowGenerator = null;
  74787. this._light._markMeshesAsLightDirty();
  74788. }
  74789. };
  74790. /**
  74791. * Serializes the shadow generator setup to a json object.
  74792. * @returns The serialized JSON object
  74793. */
  74794. ShadowGenerator.prototype.serialize = function () {
  74795. var serializationObject = {};
  74796. var shadowMap = this.getShadowMap();
  74797. if (!shadowMap) {
  74798. return serializationObject;
  74799. }
  74800. serializationObject.lightId = this._light.id;
  74801. serializationObject.mapSize = shadowMap.getRenderSize();
  74802. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  74803. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  74804. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  74805. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  74806. serializationObject.usePoissonSampling = this.usePoissonSampling;
  74807. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  74808. serializationObject.depthScale = this.depthScale;
  74809. serializationObject.darkness = this.getDarkness();
  74810. serializationObject.blurBoxOffset = this.blurBoxOffset;
  74811. serializationObject.blurKernel = this.blurKernel;
  74812. serializationObject.blurScale = this.blurScale;
  74813. serializationObject.useKernelBlur = this.useKernelBlur;
  74814. serializationObject.transparencyShadow = this._transparencyShadow;
  74815. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  74816. serializationObject.bias = this.bias;
  74817. serializationObject.normalBias = this.normalBias;
  74818. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  74819. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  74820. serializationObject.filteringQuality = this.filteringQuality;
  74821. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  74822. serializationObject.renderList = [];
  74823. if (shadowMap.renderList) {
  74824. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  74825. var mesh = shadowMap.renderList[meshIndex];
  74826. serializationObject.renderList.push(mesh.id);
  74827. }
  74828. }
  74829. return serializationObject;
  74830. };
  74831. /**
  74832. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  74833. * @param parsedShadowGenerator The JSON object to parse
  74834. * @param scene The scene to create the shadow map for
  74835. * @returns The parsed shadow generator
  74836. */
  74837. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  74838. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  74839. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  74840. var shadowMap = shadowGenerator.getShadowMap();
  74841. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  74842. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  74843. meshes.forEach(function (mesh) {
  74844. if (!shadowMap) {
  74845. return;
  74846. }
  74847. if (!shadowMap.renderList) {
  74848. shadowMap.renderList = [];
  74849. }
  74850. shadowMap.renderList.push(mesh);
  74851. });
  74852. }
  74853. if (parsedShadowGenerator.usePoissonSampling) {
  74854. shadowGenerator.usePoissonSampling = true;
  74855. }
  74856. else if (parsedShadowGenerator.useExponentialShadowMap) {
  74857. shadowGenerator.useExponentialShadowMap = true;
  74858. }
  74859. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  74860. shadowGenerator.useBlurExponentialShadowMap = true;
  74861. }
  74862. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  74863. shadowGenerator.useCloseExponentialShadowMap = true;
  74864. }
  74865. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  74866. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  74867. }
  74868. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  74869. shadowGenerator.usePercentageCloserFiltering = true;
  74870. }
  74871. else if (parsedShadowGenerator.useContactHardeningShadow) {
  74872. shadowGenerator.useContactHardeningShadow = true;
  74873. }
  74874. if (parsedShadowGenerator.filteringQuality) {
  74875. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  74876. }
  74877. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  74878. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  74879. }
  74880. // Backward compat
  74881. else if (parsedShadowGenerator.useVarianceShadowMap) {
  74882. shadowGenerator.useExponentialShadowMap = true;
  74883. }
  74884. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  74885. shadowGenerator.useBlurExponentialShadowMap = true;
  74886. }
  74887. if (parsedShadowGenerator.depthScale) {
  74888. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  74889. }
  74890. if (parsedShadowGenerator.blurScale) {
  74891. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  74892. }
  74893. if (parsedShadowGenerator.blurBoxOffset) {
  74894. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  74895. }
  74896. if (parsedShadowGenerator.useKernelBlur) {
  74897. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  74898. }
  74899. if (parsedShadowGenerator.blurKernel) {
  74900. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  74901. }
  74902. if (parsedShadowGenerator.bias !== undefined) {
  74903. shadowGenerator.bias = parsedShadowGenerator.bias;
  74904. }
  74905. if (parsedShadowGenerator.normalBias !== undefined) {
  74906. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  74907. }
  74908. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  74909. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  74910. }
  74911. if (parsedShadowGenerator.darkness) {
  74912. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  74913. }
  74914. if (parsedShadowGenerator.transparencyShadow) {
  74915. shadowGenerator.setTransparencyShadow(true);
  74916. }
  74917. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  74918. return shadowGenerator;
  74919. };
  74920. /**
  74921. * Shadow generator mode None: no filtering applied.
  74922. */
  74923. ShadowGenerator.FILTER_NONE = 0;
  74924. /**
  74925. * Shadow generator mode ESM: Exponential Shadow Mapping.
  74926. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  74927. */
  74928. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  74929. /**
  74930. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  74931. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  74932. */
  74933. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  74934. /**
  74935. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  74936. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  74937. */
  74938. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  74939. /**
  74940. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  74941. * edge artifacts on steep falloff.
  74942. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  74943. */
  74944. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  74945. /**
  74946. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  74947. * edge artifacts on steep falloff.
  74948. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  74949. */
  74950. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  74951. /**
  74952. * Shadow generator mode PCF: Percentage Closer Filtering
  74953. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  74954. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  74955. */
  74956. ShadowGenerator.FILTER_PCF = 6;
  74957. /**
  74958. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  74959. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  74960. * Contact Hardening
  74961. */
  74962. ShadowGenerator.FILTER_PCSS = 7;
  74963. /**
  74964. * Reserved for PCF and PCSS
  74965. * Highest Quality.
  74966. *
  74967. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  74968. *
  74969. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  74970. */
  74971. ShadowGenerator.QUALITY_HIGH = 0;
  74972. /**
  74973. * Reserved for PCF and PCSS
  74974. * Good tradeoff for quality/perf cross devices
  74975. *
  74976. * Execute PCF on a 3*3 kernel.
  74977. *
  74978. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  74979. */
  74980. ShadowGenerator.QUALITY_MEDIUM = 1;
  74981. /**
  74982. * Reserved for PCF and PCSS
  74983. * The lowest quality but the fastest.
  74984. *
  74985. * Execute PCF on a 1*1 kernel.
  74986. *
  74987. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  74988. */
  74989. ShadowGenerator.QUALITY_LOW = 2;
  74990. return ShadowGenerator;
  74991. }());
  74992. BABYLON.ShadowGenerator = ShadowGenerator;
  74993. })(BABYLON || (BABYLON = {}));
  74994. //# sourceMappingURL=babylon.shadowGenerator.js.map
  74995. var BABYLON;
  74996. (function (BABYLON) {
  74997. // Adds the parser to the scene parsers.
  74998. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  74999. // Shadows
  75000. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  75001. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  75002. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  75003. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  75004. // SG would be available on their associated lights
  75005. }
  75006. }
  75007. });
  75008. /**
  75009. * Defines the shadow generator component responsible to manage any shadow generators
  75010. * in a given scene.
  75011. */
  75012. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  75013. /**
  75014. * Creates a new instance of the component for the given scene
  75015. * @param scene Defines the scene to register the component in
  75016. */
  75017. function ShadowGeneratorSceneComponent(scene) {
  75018. /**
  75019. * The component name helpfull to identify the component in the list of scene components.
  75020. */
  75021. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  75022. this.scene = scene;
  75023. }
  75024. /**
  75025. * Registers the component in a given scene
  75026. */
  75027. ShadowGeneratorSceneComponent.prototype.register = function () {
  75028. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  75029. };
  75030. /**
  75031. * Rebuilds the elements related to this component in case of
  75032. * context lost for instance.
  75033. */
  75034. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  75035. // Nothing To Do Here.
  75036. };
  75037. /**
  75038. * Serializes the component data to the specified json object
  75039. * @param serializationObject The object to serialize to
  75040. */
  75041. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  75042. // Shadows
  75043. serializationObject.shadowGenerators = [];
  75044. var lights = this.scene.lights;
  75045. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  75046. var light = lights_1[_i];
  75047. var shadowGenerator = light.getShadowGenerator();
  75048. if (shadowGenerator) {
  75049. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  75050. }
  75051. }
  75052. };
  75053. /**
  75054. * Adds all the element from the container to the scene
  75055. * @param container the container holding the elements
  75056. */
  75057. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  75058. // Nothing To Do Here. (directly attached to a light)
  75059. };
  75060. /**
  75061. * Removes all the elements in the container from the scene
  75062. * @param container contains the elements to remove
  75063. */
  75064. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  75065. // Nothing To Do Here. (directly attached to a light)
  75066. };
  75067. /**
  75068. * Rebuilds the elements related to this component in case of
  75069. * context lost for instance.
  75070. */
  75071. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  75072. // Nothing To Do Here.
  75073. };
  75074. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  75075. // Shadows
  75076. var scene = this.scene;
  75077. if (this.scene.shadowsEnabled) {
  75078. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  75079. var light = scene.lights[lightIndex];
  75080. var shadowGenerator = light.getShadowGenerator();
  75081. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  75082. var shadowMap = (shadowGenerator.getShadowMap());
  75083. if (scene.textures.indexOf(shadowMap) !== -1) {
  75084. renderTargets.push(shadowMap);
  75085. }
  75086. }
  75087. }
  75088. }
  75089. };
  75090. return ShadowGeneratorSceneComponent;
  75091. }());
  75092. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  75093. })(BABYLON || (BABYLON = {}));
  75094. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  75095. var BABYLON;
  75096. (function (BABYLON) {
  75097. var DefaultLoadingScreen = /** @class */ (function () {
  75098. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  75099. if (_loadingText === void 0) { _loadingText = ""; }
  75100. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  75101. var _this = this;
  75102. this._renderingCanvas = _renderingCanvas;
  75103. this._loadingText = _loadingText;
  75104. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  75105. // Resize
  75106. this._resizeLoadingUI = function () {
  75107. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  75108. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  75109. if (!_this._loadingDiv) {
  75110. return;
  75111. }
  75112. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  75113. _this._loadingDiv.style.left = canvasRect.left + "px";
  75114. _this._loadingDiv.style.top = canvasRect.top + "px";
  75115. _this._loadingDiv.style.width = canvasRect.width + "px";
  75116. _this._loadingDiv.style.height = canvasRect.height + "px";
  75117. };
  75118. }
  75119. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  75120. if (this._loadingDiv) {
  75121. // Do not add a loading screen if there is already one
  75122. return;
  75123. }
  75124. this._loadingDiv = document.createElement("div");
  75125. this._loadingDiv.id = "babylonjsLoadingDiv";
  75126. this._loadingDiv.style.opacity = "0";
  75127. this._loadingDiv.style.transition = "opacity 1.5s ease";
  75128. this._loadingDiv.style.pointerEvents = "none";
  75129. // Loading text
  75130. this._loadingTextDiv = document.createElement("div");
  75131. this._loadingTextDiv.style.position = "absolute";
  75132. this._loadingTextDiv.style.left = "0";
  75133. this._loadingTextDiv.style.top = "50%";
  75134. this._loadingTextDiv.style.marginTop = "80px";
  75135. this._loadingTextDiv.style.width = "100%";
  75136. this._loadingTextDiv.style.height = "20px";
  75137. this._loadingTextDiv.style.fontFamily = "Arial";
  75138. this._loadingTextDiv.style.fontSize = "14px";
  75139. this._loadingTextDiv.style.color = "white";
  75140. this._loadingTextDiv.style.textAlign = "center";
  75141. this._loadingTextDiv.innerHTML = "Loading";
  75142. this._loadingDiv.appendChild(this._loadingTextDiv);
  75143. //set the predefined text
  75144. this._loadingTextDiv.innerHTML = this._loadingText;
  75145. // Generating keyframes
  75146. var style = document.createElement('style');
  75147. style.type = 'text/css';
  75148. 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 }";
  75149. style.innerHTML = keyFrames;
  75150. document.getElementsByTagName('head')[0].appendChild(style);
  75151. // Loading img
  75152. var imgBack = new Image();
  75153. 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";
  75154. imgBack.style.position = "absolute";
  75155. imgBack.style.left = "50%";
  75156. imgBack.style.top = "50%";
  75157. imgBack.style.marginLeft = "-60px";
  75158. imgBack.style.marginTop = "-60px";
  75159. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  75160. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  75161. imgBack.style.transformOrigin = "50% 50%";
  75162. imgBack.style.webkitTransformOrigin = "50% 50%";
  75163. this._loadingDiv.appendChild(imgBack);
  75164. this._resizeLoadingUI();
  75165. window.addEventListener("resize", this._resizeLoadingUI);
  75166. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  75167. document.body.appendChild(this._loadingDiv);
  75168. this._loadingDiv.style.opacity = "1";
  75169. };
  75170. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  75171. var _this = this;
  75172. if (!this._loadingDiv) {
  75173. return;
  75174. }
  75175. var onTransitionEnd = function () {
  75176. if (!_this._loadingDiv) {
  75177. return;
  75178. }
  75179. document.body.removeChild(_this._loadingDiv);
  75180. window.removeEventListener("resize", _this._resizeLoadingUI);
  75181. _this._loadingDiv = null;
  75182. };
  75183. this._loadingDiv.style.opacity = "0";
  75184. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  75185. };
  75186. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  75187. set: function (text) {
  75188. this._loadingText = text;
  75189. if (this._loadingTextDiv) {
  75190. this._loadingTextDiv.innerHTML = this._loadingText;
  75191. }
  75192. },
  75193. enumerable: true,
  75194. configurable: true
  75195. });
  75196. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  75197. get: function () {
  75198. return this._loadingDivBackgroundColor;
  75199. },
  75200. set: function (color) {
  75201. this._loadingDivBackgroundColor = color;
  75202. if (!this._loadingDiv) {
  75203. return;
  75204. }
  75205. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  75206. },
  75207. enumerable: true,
  75208. configurable: true
  75209. });
  75210. return DefaultLoadingScreen;
  75211. }());
  75212. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  75213. })(BABYLON || (BABYLON = {}));
  75214. //# sourceMappingURL=babylon.loadingScreen.js.map
  75215. var BABYLON;
  75216. (function (BABYLON) {
  75217. var SceneLoaderProgressEvent = /** @class */ (function () {
  75218. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  75219. this.lengthComputable = lengthComputable;
  75220. this.loaded = loaded;
  75221. this.total = total;
  75222. }
  75223. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  75224. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  75225. };
  75226. return SceneLoaderProgressEvent;
  75227. }());
  75228. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  75229. var SceneLoader = /** @class */ (function () {
  75230. function SceneLoader() {
  75231. }
  75232. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  75233. get: function () {
  75234. return 0;
  75235. },
  75236. enumerable: true,
  75237. configurable: true
  75238. });
  75239. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  75240. get: function () {
  75241. return 1;
  75242. },
  75243. enumerable: true,
  75244. configurable: true
  75245. });
  75246. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  75247. get: function () {
  75248. return 2;
  75249. },
  75250. enumerable: true,
  75251. configurable: true
  75252. });
  75253. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  75254. get: function () {
  75255. return 3;
  75256. },
  75257. enumerable: true,
  75258. configurable: true
  75259. });
  75260. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  75261. get: function () {
  75262. return SceneLoader._ForceFullSceneLoadingForIncremental;
  75263. },
  75264. set: function (value) {
  75265. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  75266. },
  75267. enumerable: true,
  75268. configurable: true
  75269. });
  75270. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  75271. get: function () {
  75272. return SceneLoader._ShowLoadingScreen;
  75273. },
  75274. set: function (value) {
  75275. SceneLoader._ShowLoadingScreen = value;
  75276. },
  75277. enumerable: true,
  75278. configurable: true
  75279. });
  75280. Object.defineProperty(SceneLoader, "loggingLevel", {
  75281. get: function () {
  75282. return SceneLoader._loggingLevel;
  75283. },
  75284. set: function (value) {
  75285. SceneLoader._loggingLevel = value;
  75286. },
  75287. enumerable: true,
  75288. configurable: true
  75289. });
  75290. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  75291. get: function () {
  75292. return SceneLoader._CleanBoneMatrixWeights;
  75293. },
  75294. set: function (value) {
  75295. SceneLoader._CleanBoneMatrixWeights = value;
  75296. },
  75297. enumerable: true,
  75298. configurable: true
  75299. });
  75300. SceneLoader._getDefaultPlugin = function () {
  75301. return SceneLoader._registeredPlugins[".babylon"];
  75302. };
  75303. SceneLoader._getPluginForExtension = function (extension) {
  75304. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  75305. if (registeredPlugin) {
  75306. return registeredPlugin;
  75307. }
  75308. 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");
  75309. return SceneLoader._getDefaultPlugin();
  75310. };
  75311. SceneLoader._getPluginForDirectLoad = function (data) {
  75312. for (var extension in SceneLoader._registeredPlugins) {
  75313. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  75314. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  75315. return SceneLoader._registeredPlugins[extension];
  75316. }
  75317. }
  75318. return SceneLoader._getDefaultPlugin();
  75319. };
  75320. SceneLoader._getPluginForFilename = function (sceneFilename) {
  75321. var queryStringPosition = sceneFilename.indexOf("?");
  75322. if (queryStringPosition !== -1) {
  75323. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  75324. }
  75325. var dotPosition = sceneFilename.lastIndexOf(".");
  75326. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  75327. return SceneLoader._getPluginForExtension(extension);
  75328. };
  75329. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  75330. SceneLoader._getDirectLoad = function (sceneFilename) {
  75331. if (sceneFilename.substr(0, 5) === "data:") {
  75332. return sceneFilename.substr(5);
  75333. }
  75334. return null;
  75335. };
  75336. SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  75337. var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  75338. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  75339. var plugin;
  75340. if (registeredPlugin.plugin.createPlugin) {
  75341. plugin = registeredPlugin.plugin.createPlugin();
  75342. }
  75343. else {
  75344. plugin = registeredPlugin.plugin;
  75345. }
  75346. var useArrayBuffer = registeredPlugin.isBinary;
  75347. var database;
  75348. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  75349. var dataCallback = function (data, responseURL) {
  75350. if (scene.isDisposed) {
  75351. onError("Scene has been disposed");
  75352. return;
  75353. }
  75354. scene.database = database;
  75355. onSuccess(plugin, data, responseURL);
  75356. };
  75357. var request = null;
  75358. var pluginDisposed = false;
  75359. var onDisposeObservable = plugin.onDisposeObservable;
  75360. if (onDisposeObservable) {
  75361. onDisposeObservable.add(function () {
  75362. pluginDisposed = true;
  75363. if (request) {
  75364. request.abort();
  75365. request = null;
  75366. }
  75367. onDispose();
  75368. });
  75369. }
  75370. var manifestChecked = function () {
  75371. if (pluginDisposed) {
  75372. return;
  75373. }
  75374. request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
  75375. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  75376. } : undefined, database, useArrayBuffer, function (request, exception) {
  75377. onError("Failed to load scene." + (exception ? " " + exception.message : ""), exception);
  75378. });
  75379. };
  75380. if (directLoad) {
  75381. dataCallback(directLoad);
  75382. return plugin;
  75383. }
  75384. if (fileInfo.rootUrl.indexOf("file:") === -1) {
  75385. var engine = scene.getEngine();
  75386. var canUseOfflineSupport = engine.enableOfflineSupport;
  75387. if (canUseOfflineSupport) {
  75388. // Also check for exceptions
  75389. var exceptionFound = false;
  75390. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  75391. var regex = _a[_i];
  75392. if (regex.test(fileInfo.url)) {
  75393. exceptionFound = true;
  75394. break;
  75395. }
  75396. }
  75397. canUseOfflineSupport = !exceptionFound;
  75398. }
  75399. if (canUseOfflineSupport) {
  75400. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  75401. database = new BABYLON.Database(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  75402. }
  75403. else {
  75404. manifestChecked();
  75405. }
  75406. }
  75407. // Loading file from disk via input file or drag'n'drop
  75408. else {
  75409. var file = BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  75410. if (file) {
  75411. request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  75412. }
  75413. else {
  75414. onError("Unable to find file named " + fileInfo.name);
  75415. }
  75416. }
  75417. return plugin;
  75418. };
  75419. SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
  75420. var url;
  75421. var name;
  75422. if (!sceneFilename) {
  75423. url = rootUrl;
  75424. name = BABYLON.Tools.GetFilename(rootUrl);
  75425. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  75426. }
  75427. else {
  75428. if (sceneFilename.substr(0, 1) === "/") {
  75429. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  75430. return null;
  75431. }
  75432. url = rootUrl + sceneFilename;
  75433. name = sceneFilename;
  75434. }
  75435. ;
  75436. return {
  75437. url: url,
  75438. rootUrl: rootUrl,
  75439. name: name
  75440. };
  75441. };
  75442. // Public functions
  75443. SceneLoader.GetPluginForExtension = function (extension) {
  75444. return SceneLoader._getPluginForExtension(extension).plugin;
  75445. };
  75446. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  75447. return !!SceneLoader._registeredPlugins[extension];
  75448. };
  75449. SceneLoader.RegisterPlugin = function (plugin) {
  75450. if (typeof plugin.extensions === "string") {
  75451. var extension = plugin.extensions;
  75452. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  75453. plugin: plugin,
  75454. isBinary: false
  75455. };
  75456. }
  75457. else {
  75458. var extensions = plugin.extensions;
  75459. Object.keys(extensions).forEach(function (extension) {
  75460. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  75461. plugin: plugin,
  75462. isBinary: extensions[extension].isBinary
  75463. };
  75464. });
  75465. }
  75466. };
  75467. /**
  75468. * Import meshes into a scene
  75469. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  75470. * @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)
  75471. * @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)
  75472. * @param scene the instance of BABYLON.Scene to append to
  75473. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  75474. * @param onProgress a callback with a progress event for each file being loaded
  75475. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  75476. * @param pluginExtension the extension used to determine the plugin
  75477. * @returns The loaded plugin
  75478. */
  75479. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  75480. if (sceneFilename === void 0) { sceneFilename = ""; }
  75481. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75482. if (onSuccess === void 0) { onSuccess = null; }
  75483. if (onProgress === void 0) { onProgress = null; }
  75484. if (onError === void 0) { onError = null; }
  75485. if (pluginExtension === void 0) { pluginExtension = null; }
  75486. if (!scene) {
  75487. BABYLON.Tools.Error("No scene available to import mesh to");
  75488. return null;
  75489. }
  75490. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  75491. if (!fileInfo) {
  75492. return null;
  75493. }
  75494. var loadingToken = {};
  75495. scene._addPendingData(loadingToken);
  75496. var disposeHandler = function () {
  75497. scene._removePendingData(loadingToken);
  75498. };
  75499. var errorHandler = function (message, exception) {
  75500. var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  75501. if (onError) {
  75502. onError(scene, errorMessage, exception);
  75503. }
  75504. else {
  75505. BABYLON.Tools.Error(errorMessage);
  75506. // should the exception be thrown?
  75507. }
  75508. disposeHandler();
  75509. };
  75510. var progressHandler = onProgress ? function (event) {
  75511. try {
  75512. onProgress(event);
  75513. }
  75514. catch (e) {
  75515. errorHandler("Error in onProgress callback", e);
  75516. }
  75517. } : undefined;
  75518. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  75519. scene.importedMeshesFiles.push(fileInfo.url);
  75520. if (onSuccess) {
  75521. try {
  75522. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  75523. }
  75524. catch (e) {
  75525. errorHandler("Error in onSuccess callback", e);
  75526. }
  75527. }
  75528. scene._removePendingData(loadingToken);
  75529. };
  75530. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  75531. if (plugin.rewriteRootURL) {
  75532. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  75533. }
  75534. if (plugin.importMesh) {
  75535. var syncedPlugin = plugin;
  75536. var meshes = new Array();
  75537. var particleSystems = new Array();
  75538. var skeletons = new Array();
  75539. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  75540. return;
  75541. }
  75542. scene.loadingPluginName = plugin.name;
  75543. successHandler(meshes, particleSystems, skeletons, []);
  75544. }
  75545. else {
  75546. var asyncedPlugin = plugin;
  75547. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
  75548. scene.loadingPluginName = plugin.name;
  75549. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  75550. }).catch(function (error) {
  75551. errorHandler(error.message, error);
  75552. });
  75553. }
  75554. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  75555. };
  75556. /**
  75557. * Import meshes into a scene
  75558. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  75559. * @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)
  75560. * @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)
  75561. * @param scene the instance of BABYLON.Scene to append to
  75562. * @param onProgress a callback with a progress event for each file being loaded
  75563. * @param pluginExtension the extension used to determine the plugin
  75564. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  75565. */
  75566. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  75567. if (sceneFilename === void 0) { sceneFilename = ""; }
  75568. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75569. if (onProgress === void 0) { onProgress = null; }
  75570. if (pluginExtension === void 0) { pluginExtension = null; }
  75571. return new Promise(function (resolve, reject) {
  75572. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  75573. resolve({
  75574. meshes: meshes,
  75575. particleSystems: particleSystems,
  75576. skeletons: skeletons,
  75577. animationGroups: animationGroups
  75578. });
  75579. }, onProgress, function (scene, message, exception) {
  75580. reject(exception || new Error(message));
  75581. }, pluginExtension);
  75582. });
  75583. };
  75584. /**
  75585. * Load a scene
  75586. * @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)
  75587. * @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)
  75588. * @param engine is the instance of BABYLON.Engine to use to create the scene
  75589. * @param onSuccess a callback with the scene when import succeeds
  75590. * @param onProgress a callback with a progress event for each file being loaded
  75591. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  75592. * @param pluginExtension the extension used to determine the plugin
  75593. * @returns The loaded plugin
  75594. */
  75595. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  75596. if (onSuccess === void 0) { onSuccess = null; }
  75597. if (onProgress === void 0) { onProgress = null; }
  75598. if (onError === void 0) { onError = null; }
  75599. if (pluginExtension === void 0) { pluginExtension = null; }
  75600. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  75601. };
  75602. /**
  75603. * Load a scene
  75604. * @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)
  75605. * @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)
  75606. * @param engine is the instance of BABYLON.Engine to use to create the scene
  75607. * @param onProgress a callback with a progress event for each file being loaded
  75608. * @param pluginExtension the extension used to determine the plugin
  75609. * @returns The loaded scene
  75610. */
  75611. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  75612. if (onProgress === void 0) { onProgress = null; }
  75613. if (pluginExtension === void 0) { pluginExtension = null; }
  75614. return new Promise(function (resolve, reject) {
  75615. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  75616. resolve(scene);
  75617. }, onProgress, function (scene, message, exception) {
  75618. reject(exception || new Error(message));
  75619. }, pluginExtension);
  75620. });
  75621. };
  75622. /**
  75623. * Append a scene
  75624. * @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)
  75625. * @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)
  75626. * @param scene is the instance of BABYLON.Scene to append to
  75627. * @param onSuccess a callback with the scene when import succeeds
  75628. * @param onProgress a callback with a progress event for each file being loaded
  75629. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  75630. * @param pluginExtension the extension used to determine the plugin
  75631. * @returns The loaded plugin
  75632. */
  75633. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  75634. if (sceneFilename === void 0) { sceneFilename = ""; }
  75635. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75636. if (onSuccess === void 0) { onSuccess = null; }
  75637. if (onProgress === void 0) { onProgress = null; }
  75638. if (onError === void 0) { onError = null; }
  75639. if (pluginExtension === void 0) { pluginExtension = null; }
  75640. if (!scene) {
  75641. BABYLON.Tools.Error("No scene available to append to");
  75642. return null;
  75643. }
  75644. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  75645. if (!fileInfo) {
  75646. return null;
  75647. }
  75648. if (SceneLoader.ShowLoadingScreen) {
  75649. scene.getEngine().displayLoadingUI();
  75650. }
  75651. var loadingToken = {};
  75652. scene._addPendingData(loadingToken);
  75653. var disposeHandler = function () {
  75654. scene._removePendingData(loadingToken);
  75655. scene.getEngine().hideLoadingUI();
  75656. };
  75657. var errorHandler = function (message, exception) {
  75658. var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  75659. if (onError) {
  75660. onError(scene, errorMessage, exception);
  75661. }
  75662. else {
  75663. BABYLON.Tools.Error(errorMessage);
  75664. // should the exception be thrown?
  75665. }
  75666. disposeHandler();
  75667. };
  75668. var progressHandler = onProgress ? function (event) {
  75669. try {
  75670. onProgress(event);
  75671. }
  75672. catch (e) {
  75673. errorHandler("Error in onProgress callback", e);
  75674. }
  75675. } : undefined;
  75676. var successHandler = function () {
  75677. if (onSuccess) {
  75678. try {
  75679. onSuccess(scene);
  75680. }
  75681. catch (e) {
  75682. errorHandler("Error in onSuccess callback", e);
  75683. }
  75684. }
  75685. scene._removePendingData(loadingToken);
  75686. };
  75687. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  75688. if (plugin.load) {
  75689. var syncedPlugin = plugin;
  75690. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  75691. return;
  75692. }
  75693. scene.loadingPluginName = plugin.name;
  75694. successHandler();
  75695. }
  75696. else {
  75697. var asyncedPlugin = plugin;
  75698. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
  75699. scene.loadingPluginName = plugin.name;
  75700. successHandler();
  75701. }).catch(function (error) {
  75702. errorHandler(error.message, error);
  75703. });
  75704. }
  75705. if (SceneLoader.ShowLoadingScreen) {
  75706. scene.executeWhenReady(function () {
  75707. scene.getEngine().hideLoadingUI();
  75708. });
  75709. }
  75710. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  75711. };
  75712. /**
  75713. * Append a scene
  75714. * @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)
  75715. * @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)
  75716. * @param scene is the instance of BABYLON.Scene to append to
  75717. * @param onProgress a callback with a progress event for each file being loaded
  75718. * @param pluginExtension the extension used to determine the plugin
  75719. * @returns The given scene
  75720. */
  75721. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  75722. if (sceneFilename === void 0) { sceneFilename = ""; }
  75723. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75724. if (onProgress === void 0) { onProgress = null; }
  75725. if (pluginExtension === void 0) { pluginExtension = null; }
  75726. return new Promise(function (resolve, reject) {
  75727. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  75728. resolve(scene);
  75729. }, onProgress, function (scene, message, exception) {
  75730. reject(exception || new Error(message));
  75731. }, pluginExtension);
  75732. });
  75733. };
  75734. /**
  75735. * Load a scene into an asset container
  75736. * @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)
  75737. * @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)
  75738. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  75739. * @param onSuccess a callback with the scene when import succeeds
  75740. * @param onProgress a callback with a progress event for each file being loaded
  75741. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  75742. * @param pluginExtension the extension used to determine the plugin
  75743. * @returns The loaded plugin
  75744. */
  75745. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  75746. if (sceneFilename === void 0) { sceneFilename = ""; }
  75747. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75748. if (onSuccess === void 0) { onSuccess = null; }
  75749. if (onProgress === void 0) { onProgress = null; }
  75750. if (onError === void 0) { onError = null; }
  75751. if (pluginExtension === void 0) { pluginExtension = null; }
  75752. if (!scene) {
  75753. BABYLON.Tools.Error("No scene available to load asset container to");
  75754. return null;
  75755. }
  75756. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  75757. if (!fileInfo) {
  75758. return null;
  75759. }
  75760. var loadingToken = {};
  75761. scene._addPendingData(loadingToken);
  75762. var disposeHandler = function () {
  75763. scene._removePendingData(loadingToken);
  75764. };
  75765. var errorHandler = function (message, exception) {
  75766. var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  75767. if (onError) {
  75768. onError(scene, errorMessage, exception);
  75769. }
  75770. else {
  75771. BABYLON.Tools.Error(errorMessage);
  75772. // should the exception be thrown?
  75773. }
  75774. disposeHandler();
  75775. };
  75776. var progressHandler = onProgress ? function (event) {
  75777. try {
  75778. onProgress(event);
  75779. }
  75780. catch (e) {
  75781. errorHandler("Error in onProgress callback", e);
  75782. }
  75783. } : undefined;
  75784. var successHandler = function (assets) {
  75785. if (onSuccess) {
  75786. try {
  75787. onSuccess(assets);
  75788. }
  75789. catch (e) {
  75790. errorHandler("Error in onSuccess callback", e);
  75791. }
  75792. }
  75793. scene._removePendingData(loadingToken);
  75794. };
  75795. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  75796. if (plugin.loadAssetContainer) {
  75797. var syncedPlugin = plugin;
  75798. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  75799. if (!assetContainer) {
  75800. return;
  75801. }
  75802. scene.loadingPluginName = plugin.name;
  75803. successHandler(assetContainer);
  75804. }
  75805. else if (plugin.loadAssetContainerAsync) {
  75806. var asyncedPlugin = plugin;
  75807. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
  75808. scene.loadingPluginName = plugin.name;
  75809. successHandler(assetContainer);
  75810. }).catch(function (error) {
  75811. errorHandler(error.message, error);
  75812. });
  75813. }
  75814. else {
  75815. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  75816. }
  75817. if (SceneLoader.ShowLoadingScreen) {
  75818. scene.executeWhenReady(function () {
  75819. scene.getEngine().hideLoadingUI();
  75820. });
  75821. }
  75822. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  75823. };
  75824. /**
  75825. * Load a scene into an asset container
  75826. * @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)
  75827. * @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)
  75828. * @param scene is the instance of BABYLON.Scene to append to
  75829. * @param onProgress a callback with a progress event for each file being loaded
  75830. * @param pluginExtension the extension used to determine the plugin
  75831. * @returns The loaded asset container
  75832. */
  75833. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  75834. if (sceneFilename === void 0) { sceneFilename = ""; }
  75835. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75836. if (onProgress === void 0) { onProgress = null; }
  75837. if (pluginExtension === void 0) { pluginExtension = null; }
  75838. return new Promise(function (resolve, reject) {
  75839. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  75840. resolve(assetContainer);
  75841. }, onProgress, function (scene, message, exception) {
  75842. reject(exception || new Error(message));
  75843. }, pluginExtension);
  75844. });
  75845. };
  75846. // Flags
  75847. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  75848. SceneLoader._ShowLoadingScreen = true;
  75849. SceneLoader._CleanBoneMatrixWeights = false;
  75850. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  75851. // Members
  75852. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  75853. SceneLoader._registeredPlugins = {};
  75854. return SceneLoader;
  75855. }());
  75856. BABYLON.SceneLoader = SceneLoader;
  75857. ;
  75858. })(BABYLON || (BABYLON = {}));
  75859. //# sourceMappingURL=babylon.sceneLoader.js.map
  75860. var BABYLON;
  75861. (function (BABYLON) {
  75862. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  75863. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  75864. var parsedMaterial = parsedData.materials[index];
  75865. if (parsedMaterial.id === id) {
  75866. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  75867. }
  75868. }
  75869. return null;
  75870. };
  75871. var isDescendantOf = function (mesh, names, hierarchyIds) {
  75872. for (var i in names) {
  75873. if (mesh.name === names[i]) {
  75874. hierarchyIds.push(mesh.id);
  75875. return true;
  75876. }
  75877. }
  75878. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  75879. hierarchyIds.push(mesh.id);
  75880. return true;
  75881. }
  75882. return false;
  75883. };
  75884. var logOperation = function (operation, producer) {
  75885. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  75886. };
  75887. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  75888. if (addToScene === void 0) { addToScene = false; }
  75889. var container = new BABYLON.AssetContainer(scene);
  75890. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  75891. // when SceneLoader.debugLogging = true (default), or exception encountered.
  75892. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  75893. // and avoid problems with multiple concurrent .babylon loads.
  75894. var log = "importScene has failed JSON parse";
  75895. try {
  75896. var parsedData = JSON.parse(data);
  75897. log = "";
  75898. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  75899. var index;
  75900. var cache;
  75901. // Lights
  75902. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  75903. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  75904. var parsedLight = parsedData.lights[index];
  75905. var light = BABYLON.Light.Parse(parsedLight, scene);
  75906. if (light) {
  75907. container.lights.push(light);
  75908. log += (index === 0 ? "\n\tLights:" : "");
  75909. log += "\n\t\t" + light.toString(fullDetails);
  75910. }
  75911. }
  75912. }
  75913. // Animations
  75914. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  75915. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  75916. var parsedAnimation = parsedData.animations[index];
  75917. var animation = BABYLON.Animation.Parse(parsedAnimation);
  75918. scene.animations.push(animation);
  75919. container.animations.push(animation);
  75920. log += (index === 0 ? "\n\tAnimations:" : "");
  75921. log += "\n\t\t" + animation.toString(fullDetails);
  75922. }
  75923. }
  75924. // Materials
  75925. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  75926. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  75927. var parsedMaterial = parsedData.materials[index];
  75928. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  75929. container.materials.push(mat);
  75930. log += (index === 0 ? "\n\tMaterials:" : "");
  75931. log += "\n\t\t" + mat.toString(fullDetails);
  75932. }
  75933. }
  75934. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  75935. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  75936. var parsedMultiMaterial = parsedData.multiMaterials[index];
  75937. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  75938. container.multiMaterials.push(mmat);
  75939. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  75940. log += "\n\t\t" + mmat.toString(fullDetails);
  75941. }
  75942. }
  75943. // Morph targets
  75944. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  75945. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  75946. var managerData = _a[_i];
  75947. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  75948. }
  75949. }
  75950. // Skeletons
  75951. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  75952. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  75953. var parsedSkeleton = parsedData.skeletons[index];
  75954. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  75955. container.skeletons.push(skeleton);
  75956. log += (index === 0 ? "\n\tSkeletons:" : "");
  75957. log += "\n\t\t" + skeleton.toString(fullDetails);
  75958. }
  75959. }
  75960. // Geometries
  75961. var geometries = parsedData.geometries;
  75962. if (geometries !== undefined && geometries !== null) {
  75963. var addedGeometry = new Array();
  75964. // Boxes
  75965. var boxes = geometries.boxes;
  75966. if (boxes !== undefined && boxes !== null) {
  75967. for (index = 0, cache = boxes.length; index < cache; index++) {
  75968. var parsedBox = boxes[index];
  75969. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  75970. }
  75971. }
  75972. // Spheres
  75973. var spheres = geometries.spheres;
  75974. if (spheres !== undefined && spheres !== null) {
  75975. for (index = 0, cache = spheres.length; index < cache; index++) {
  75976. var parsedSphere = spheres[index];
  75977. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  75978. }
  75979. }
  75980. // Cylinders
  75981. var cylinders = geometries.cylinders;
  75982. if (cylinders !== undefined && cylinders !== null) {
  75983. for (index = 0, cache = cylinders.length; index < cache; index++) {
  75984. var parsedCylinder = cylinders[index];
  75985. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  75986. }
  75987. }
  75988. // Toruses
  75989. var toruses = geometries.toruses;
  75990. if (toruses !== undefined && toruses !== null) {
  75991. for (index = 0, cache = toruses.length; index < cache; index++) {
  75992. var parsedTorus = toruses[index];
  75993. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  75994. }
  75995. }
  75996. // Grounds
  75997. var grounds = geometries.grounds;
  75998. if (grounds !== undefined && grounds !== null) {
  75999. for (index = 0, cache = grounds.length; index < cache; index++) {
  76000. var parsedGround = grounds[index];
  76001. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  76002. }
  76003. }
  76004. // Planes
  76005. var planes = geometries.planes;
  76006. if (planes !== undefined && planes !== null) {
  76007. for (index = 0, cache = planes.length; index < cache; index++) {
  76008. var parsedPlane = planes[index];
  76009. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  76010. }
  76011. }
  76012. // TorusKnots
  76013. var torusKnots = geometries.torusKnots;
  76014. if (torusKnots !== undefined && torusKnots !== null) {
  76015. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  76016. var parsedTorusKnot = torusKnots[index];
  76017. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  76018. }
  76019. }
  76020. // VertexData
  76021. var vertexData = geometries.vertexData;
  76022. if (vertexData !== undefined && vertexData !== null) {
  76023. for (index = 0, cache = vertexData.length; index < cache; index++) {
  76024. var parsedVertexData = vertexData[index];
  76025. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  76026. }
  76027. }
  76028. addedGeometry.forEach(function (g) {
  76029. if (g) {
  76030. container.geometries.push(g);
  76031. }
  76032. });
  76033. }
  76034. // Transform nodes
  76035. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  76036. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  76037. var parsedTransformNode = parsedData.transformNodes[index];
  76038. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  76039. container.transformNodes.push(node);
  76040. }
  76041. }
  76042. // Meshes
  76043. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  76044. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  76045. var parsedMesh = parsedData.meshes[index];
  76046. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  76047. container.meshes.push(mesh);
  76048. log += (index === 0 ? "\n\tMeshes:" : "");
  76049. log += "\n\t\t" + mesh.toString(fullDetails);
  76050. }
  76051. }
  76052. // Cameras
  76053. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  76054. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  76055. var parsedCamera = parsedData.cameras[index];
  76056. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  76057. container.cameras.push(camera);
  76058. log += (index === 0 ? "\n\tCameras:" : "");
  76059. log += "\n\t\t" + camera.toString(fullDetails);
  76060. }
  76061. }
  76062. // Animation Groups
  76063. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  76064. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  76065. var parsedAnimationGroup = parsedData.animationGroups[index];
  76066. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  76067. container.animationGroups.push(animationGroup);
  76068. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  76069. log += "\n\t\t" + animationGroup.toString(fullDetails);
  76070. }
  76071. }
  76072. // Browsing all the graph to connect the dots
  76073. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  76074. var camera = scene.cameras[index];
  76075. if (camera._waitingParentId) {
  76076. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  76077. camera._waitingParentId = null;
  76078. }
  76079. }
  76080. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  76081. var light_1 = scene.lights[index];
  76082. if (light_1 && light_1._waitingParentId) {
  76083. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  76084. light_1._waitingParentId = null;
  76085. }
  76086. }
  76087. // Connect parents & children and parse actions
  76088. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  76089. var transformNode = scene.transformNodes[index];
  76090. if (transformNode._waitingParentId) {
  76091. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  76092. transformNode._waitingParentId = null;
  76093. }
  76094. }
  76095. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  76096. var mesh = scene.meshes[index];
  76097. if (mesh._waitingParentId) {
  76098. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  76099. mesh._waitingParentId = null;
  76100. }
  76101. }
  76102. // freeze world matrix application
  76103. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  76104. var currentMesh = scene.meshes[index];
  76105. if (currentMesh._waitingFreezeWorldMatrix) {
  76106. currentMesh.freezeWorldMatrix();
  76107. currentMesh._waitingFreezeWorldMatrix = null;
  76108. }
  76109. else {
  76110. currentMesh.computeWorldMatrix(true);
  76111. }
  76112. }
  76113. // Lights exclusions / inclusions
  76114. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  76115. var light_2 = scene.lights[index];
  76116. // Excluded check
  76117. if (light_2._excludedMeshesIds.length > 0) {
  76118. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  76119. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  76120. if (excludedMesh) {
  76121. light_2.excludedMeshes.push(excludedMesh);
  76122. }
  76123. }
  76124. light_2._excludedMeshesIds = [];
  76125. }
  76126. // Included check
  76127. if (light_2._includedOnlyMeshesIds.length > 0) {
  76128. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  76129. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  76130. if (includedOnlyMesh) {
  76131. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  76132. }
  76133. }
  76134. light_2._includedOnlyMeshesIds = [];
  76135. }
  76136. }
  76137. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  76138. // Actions (scene) Done last as it can access other objects.
  76139. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  76140. var mesh = scene.meshes[index];
  76141. if (mesh._waitingActions) {
  76142. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  76143. mesh._waitingActions = null;
  76144. }
  76145. }
  76146. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  76147. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  76148. }
  76149. if (!addToScene) {
  76150. container.removeAllFromScene();
  76151. }
  76152. }
  76153. catch (err) {
  76154. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  76155. if (onError) {
  76156. onError(msg, err);
  76157. }
  76158. else {
  76159. BABYLON.Tools.Log(msg);
  76160. throw err;
  76161. }
  76162. }
  76163. finally {
  76164. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  76165. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  76166. }
  76167. }
  76168. return container;
  76169. };
  76170. BABYLON.SceneLoader.RegisterPlugin({
  76171. name: "babylon.js",
  76172. extensions: ".babylon",
  76173. canDirectLoad: function (data) {
  76174. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  76175. return true;
  76176. }
  76177. return false;
  76178. },
  76179. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  76180. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  76181. // when SceneLoader.debugLogging = true (default), or exception encountered.
  76182. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  76183. // and avoid problems with multiple concurrent .babylon loads.
  76184. var log = "importMesh has failed JSON parse";
  76185. try {
  76186. var parsedData = JSON.parse(data);
  76187. log = "";
  76188. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  76189. if (!meshesNames) {
  76190. meshesNames = null;
  76191. }
  76192. else if (!Array.isArray(meshesNames)) {
  76193. meshesNames = [meshesNames];
  76194. }
  76195. var hierarchyIds = new Array();
  76196. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  76197. var loadedSkeletonsIds = [];
  76198. var loadedMaterialsIds = [];
  76199. var index;
  76200. var cache;
  76201. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  76202. var parsedMesh = parsedData.meshes[index];
  76203. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  76204. if (meshesNames !== null) {
  76205. // Remove found mesh name from list.
  76206. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  76207. }
  76208. //Geometry?
  76209. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  76210. //does the file contain geometries?
  76211. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  76212. //find the correct geometry and add it to the scene
  76213. var found = false;
  76214. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  76215. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  76216. return;
  76217. }
  76218. else {
  76219. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  76220. if (parsedGeometryData.id === parsedMesh.geometryId) {
  76221. switch (geometryType) {
  76222. case "boxes":
  76223. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  76224. break;
  76225. case "spheres":
  76226. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  76227. break;
  76228. case "cylinders":
  76229. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  76230. break;
  76231. case "toruses":
  76232. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  76233. break;
  76234. case "grounds":
  76235. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  76236. break;
  76237. case "planes":
  76238. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  76239. break;
  76240. case "torusKnots":
  76241. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  76242. break;
  76243. case "vertexData":
  76244. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  76245. break;
  76246. }
  76247. found = true;
  76248. }
  76249. });
  76250. }
  76251. });
  76252. if (found === false) {
  76253. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  76254. }
  76255. }
  76256. }
  76257. // Material ?
  76258. if (parsedMesh.materialId) {
  76259. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  76260. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  76261. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  76262. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  76263. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  76264. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  76265. var subMatId = parsedMultiMaterial.materials[matIndex];
  76266. loadedMaterialsIds.push(subMatId);
  76267. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  76268. if (mat) {
  76269. log += "\n\tMaterial " + mat.toString(fullDetails);
  76270. }
  76271. }
  76272. loadedMaterialsIds.push(parsedMultiMaterial.id);
  76273. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  76274. if (mmat) {
  76275. materialFound = true;
  76276. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  76277. }
  76278. break;
  76279. }
  76280. }
  76281. }
  76282. if (materialFound === false) {
  76283. loadedMaterialsIds.push(parsedMesh.materialId);
  76284. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  76285. if (!mat) {
  76286. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  76287. }
  76288. else {
  76289. log += "\n\tMaterial " + mat.toString(fullDetails);
  76290. }
  76291. }
  76292. }
  76293. // Skeleton ?
  76294. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  76295. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  76296. if (skeletonAlreadyLoaded === false) {
  76297. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  76298. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  76299. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  76300. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  76301. skeletons.push(skeleton);
  76302. loadedSkeletonsIds.push(parsedSkeleton.id);
  76303. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  76304. }
  76305. }
  76306. }
  76307. }
  76308. // Morph targets ?
  76309. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  76310. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  76311. var managerData = _a[_i];
  76312. BABYLON.MorphTargetManager.Parse(managerData, scene);
  76313. }
  76314. }
  76315. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  76316. meshes.push(mesh);
  76317. log += "\n\tMesh " + mesh.toString(fullDetails);
  76318. }
  76319. }
  76320. // Connecting parents
  76321. var currentMesh;
  76322. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  76323. currentMesh = scene.meshes[index];
  76324. if (currentMesh._waitingParentId) {
  76325. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  76326. currentMesh._waitingParentId = null;
  76327. }
  76328. }
  76329. // freeze and compute world matrix application
  76330. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  76331. currentMesh = scene.meshes[index];
  76332. if (currentMesh._waitingFreezeWorldMatrix) {
  76333. currentMesh.freezeWorldMatrix();
  76334. currentMesh._waitingFreezeWorldMatrix = null;
  76335. }
  76336. else {
  76337. currentMesh.computeWorldMatrix(true);
  76338. }
  76339. }
  76340. }
  76341. // Particles
  76342. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  76343. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  76344. if (parser) {
  76345. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  76346. var parsedParticleSystem = parsedData.particleSystems[index];
  76347. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  76348. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  76349. }
  76350. }
  76351. }
  76352. }
  76353. return true;
  76354. }
  76355. catch (err) {
  76356. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  76357. if (onError) {
  76358. onError(msg, err);
  76359. }
  76360. else {
  76361. BABYLON.Tools.Log(msg);
  76362. throw err;
  76363. }
  76364. }
  76365. finally {
  76366. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  76367. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  76368. }
  76369. }
  76370. return false;
  76371. },
  76372. load: function (scene, data, rootUrl, onError) {
  76373. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  76374. // when SceneLoader.debugLogging = true (default), or exception encountered.
  76375. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  76376. // and avoid problems with multiple concurrent .babylon loads.
  76377. var log = "importScene has failed JSON parse";
  76378. try {
  76379. var parsedData = JSON.parse(data);
  76380. log = "";
  76381. // Scene
  76382. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  76383. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  76384. }
  76385. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  76386. scene.autoClear = parsedData.autoClear;
  76387. }
  76388. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  76389. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  76390. }
  76391. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  76392. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  76393. }
  76394. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  76395. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  76396. }
  76397. // Fog
  76398. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  76399. scene.fogMode = parsedData.fogMode;
  76400. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  76401. scene.fogStart = parsedData.fogStart;
  76402. scene.fogEnd = parsedData.fogEnd;
  76403. scene.fogDensity = parsedData.fogDensity;
  76404. log += "\tFog mode for scene: ";
  76405. switch (scene.fogMode) {
  76406. // getters not compiling, so using hardcoded
  76407. case 1:
  76408. log += "exp\n";
  76409. break;
  76410. case 2:
  76411. log += "exp2\n";
  76412. break;
  76413. case 3:
  76414. log += "linear\n";
  76415. break;
  76416. }
  76417. }
  76418. //Physics
  76419. if (parsedData.physicsEnabled) {
  76420. var physicsPlugin;
  76421. if (parsedData.physicsEngine === "cannon") {
  76422. physicsPlugin = new BABYLON.CannonJSPlugin();
  76423. }
  76424. else if (parsedData.physicsEngine === "oimo") {
  76425. physicsPlugin = new BABYLON.OimoJSPlugin();
  76426. }
  76427. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  76428. //else - default engine, which is currently oimo
  76429. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  76430. scene.enablePhysics(physicsGravity, physicsPlugin);
  76431. }
  76432. // Metadata
  76433. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  76434. scene.metadata = parsedData.metadata;
  76435. }
  76436. //collisions, if defined. otherwise, default is true
  76437. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  76438. scene.collisionsEnabled = parsedData.collisionsEnabled;
  76439. }
  76440. scene.workerCollisions = !!parsedData.workerCollisions;
  76441. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  76442. if (!container) {
  76443. return false;
  76444. }
  76445. if (parsedData.autoAnimate) {
  76446. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  76447. }
  76448. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  76449. scene.setActiveCameraByID(parsedData.activeCameraID);
  76450. }
  76451. // Environment texture
  76452. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  76453. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  76454. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  76455. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  76456. if (parsedData.environmentTextureRotationY) {
  76457. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  76458. }
  76459. scene.environmentTexture = hdrTexture;
  76460. }
  76461. else {
  76462. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  76463. if (parsedData.environmentTextureRotationY) {
  76464. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  76465. }
  76466. scene.environmentTexture = cubeTexture;
  76467. }
  76468. if (parsedData.createDefaultSkybox === true) {
  76469. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  76470. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  76471. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  76472. }
  76473. }
  76474. // Finish
  76475. return true;
  76476. }
  76477. catch (err) {
  76478. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  76479. if (onError) {
  76480. onError(msg, err);
  76481. }
  76482. else {
  76483. BABYLON.Tools.Log(msg);
  76484. throw err;
  76485. }
  76486. }
  76487. finally {
  76488. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  76489. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  76490. }
  76491. }
  76492. return false;
  76493. },
  76494. loadAssetContainer: function (scene, data, rootUrl, onError) {
  76495. var container = loadAssetContainer(scene, data, rootUrl, onError);
  76496. return container;
  76497. }
  76498. });
  76499. })(BABYLON || (BABYLON = {}));
  76500. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  76501. var BABYLON;
  76502. (function (BABYLON) {
  76503. /**
  76504. * Class used to help managing file picking and drag'n'drop
  76505. */
  76506. var FilesInput = /** @class */ (function () {
  76507. /**
  76508. * Creates a new FilesInput
  76509. * @param engine defines the rendering engine
  76510. * @param scene defines the hosting scene
  76511. * @param sceneLoadedCallback callback called when scene is loaded
  76512. * @param progressCallback callback called to track progress
  76513. * @param additionalRenderLoopLogicCallback callback called to add user logic to the rendering loop
  76514. * @param textureLoadingCallback callback called when a texture is loading
  76515. * @param startingProcessingFilesCallback callback called when the system is about to process all files
  76516. * @param onReloadCallback callback called when a reload is requested
  76517. * @param errorCallback callback call if an error occurs
  76518. */
  76519. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  76520. /**
  76521. * Callback called when a file is processed
  76522. */
  76523. this.onProcessFileCallback = function () { return true; };
  76524. this._engine = engine;
  76525. this._currentScene = scene;
  76526. this._sceneLoadedCallback = sceneLoadedCallback;
  76527. this._progressCallback = progressCallback;
  76528. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  76529. this._textureLoadingCallback = textureLoadingCallback;
  76530. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  76531. this._onReloadCallback = onReloadCallback;
  76532. this._errorCallback = errorCallback;
  76533. }
  76534. /**
  76535. * Calls this function to listen to drag'n'drop events on a specific DOM element
  76536. * @param elementToMonitor defines the DOM element to track
  76537. */
  76538. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  76539. var _this = this;
  76540. if (elementToMonitor) {
  76541. this._elementToMonitor = elementToMonitor;
  76542. this._dragEnterHandler = function (e) { _this.drag(e); };
  76543. this._dragOverHandler = function (e) { _this.drag(e); };
  76544. this._dropHandler = function (e) { _this.drop(e); };
  76545. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  76546. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  76547. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  76548. }
  76549. };
  76550. /**
  76551. * Release all associated resources
  76552. */
  76553. FilesInput.prototype.dispose = function () {
  76554. if (!this._elementToMonitor) {
  76555. return;
  76556. }
  76557. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  76558. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  76559. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  76560. };
  76561. FilesInput.prototype.renderFunction = function () {
  76562. if (this._additionalRenderLoopLogicCallback) {
  76563. this._additionalRenderLoopLogicCallback();
  76564. }
  76565. if (this._currentScene) {
  76566. if (this._textureLoadingCallback) {
  76567. var remaining = this._currentScene.getWaitingItemsCount();
  76568. if (remaining > 0) {
  76569. this._textureLoadingCallback(remaining);
  76570. }
  76571. }
  76572. this._currentScene.render();
  76573. }
  76574. };
  76575. FilesInput.prototype.drag = function (e) {
  76576. e.stopPropagation();
  76577. e.preventDefault();
  76578. };
  76579. FilesInput.prototype.drop = function (eventDrop) {
  76580. eventDrop.stopPropagation();
  76581. eventDrop.preventDefault();
  76582. this.loadFiles(eventDrop);
  76583. };
  76584. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  76585. var _this = this;
  76586. var reader = folder.createReader();
  76587. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  76588. reader.readEntries(function (entries) {
  76589. remaining.count += entries.length;
  76590. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  76591. var entry = entries_1[_i];
  76592. if (entry.isFile) {
  76593. entry.file(function (file) {
  76594. file.correctName = relativePath + file.name;
  76595. files.push(file);
  76596. if (--remaining.count === 0) {
  76597. callback();
  76598. }
  76599. });
  76600. }
  76601. else if (entry.isDirectory) {
  76602. _this._traverseFolder(entry, files, remaining, callback);
  76603. }
  76604. }
  76605. if (--remaining.count) {
  76606. callback();
  76607. }
  76608. });
  76609. };
  76610. FilesInput.prototype._processFiles = function (files) {
  76611. for (var i = 0; i < files.length; i++) {
  76612. var name = files[i].correctName.toLowerCase();
  76613. var extension = name.split('.').pop();
  76614. if (!this.onProcessFileCallback(files[i], name, extension)) {
  76615. continue;
  76616. }
  76617. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  76618. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  76619. this._sceneFileToLoad = files[i];
  76620. }
  76621. FilesInput.FilesToLoad[name] = files[i];
  76622. }
  76623. };
  76624. /**
  76625. * Load files from a drop event
  76626. * @param event defines the drop event to use as source
  76627. */
  76628. FilesInput.prototype.loadFiles = function (event) {
  76629. var _this = this;
  76630. // Handling data transfer via drag'n'drop
  76631. if (event && event.dataTransfer && event.dataTransfer.files) {
  76632. this._filesToLoad = event.dataTransfer.files;
  76633. }
  76634. // Handling files from input files
  76635. if (event && event.target && event.target.files) {
  76636. this._filesToLoad = event.target.files;
  76637. }
  76638. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  76639. return;
  76640. }
  76641. if (this._startingProcessingFilesCallback) {
  76642. this._startingProcessingFilesCallback(this._filesToLoad);
  76643. }
  76644. if (this._filesToLoad && this._filesToLoad.length > 0) {
  76645. var files_1 = new Array();
  76646. var folders = [];
  76647. var items = event.dataTransfer ? event.dataTransfer.items : null;
  76648. for (var i = 0; i < this._filesToLoad.length; i++) {
  76649. var fileToLoad = this._filesToLoad[i];
  76650. var name_1 = fileToLoad.name.toLowerCase();
  76651. var entry = void 0;
  76652. fileToLoad.correctName = name_1;
  76653. if (items) {
  76654. var item = items[i];
  76655. if (item.getAsEntry) {
  76656. entry = item.getAsEntry();
  76657. }
  76658. else if (item.webkitGetAsEntry) {
  76659. entry = item.webkitGetAsEntry();
  76660. }
  76661. }
  76662. if (!entry) {
  76663. files_1.push(fileToLoad);
  76664. }
  76665. else {
  76666. if (entry.isDirectory) {
  76667. folders.push(entry);
  76668. }
  76669. else {
  76670. files_1.push(fileToLoad);
  76671. }
  76672. }
  76673. }
  76674. if (folders.length === 0) {
  76675. this._processFiles(files_1);
  76676. this._processReload();
  76677. }
  76678. else {
  76679. var remaining = { count: folders.length };
  76680. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  76681. var folder = folders_1[_i];
  76682. this._traverseFolder(folder, files_1, remaining, function () {
  76683. _this._processFiles(files_1);
  76684. if (remaining.count === 0) {
  76685. _this._processReload();
  76686. }
  76687. });
  76688. }
  76689. }
  76690. }
  76691. };
  76692. FilesInput.prototype._processReload = function () {
  76693. if (this._onReloadCallback) {
  76694. this._onReloadCallback(this._sceneFileToLoad);
  76695. }
  76696. else {
  76697. this.reload();
  76698. }
  76699. };
  76700. /**
  76701. * Reload the current scene from the loaded files
  76702. */
  76703. FilesInput.prototype.reload = function () {
  76704. var _this = this;
  76705. // If a scene file has been provided
  76706. if (this._sceneFileToLoad) {
  76707. if (this._currentScene) {
  76708. if (BABYLON.Tools.errorsCount > 0) {
  76709. BABYLON.Tools.ClearLogCache();
  76710. }
  76711. this._engine.stopRenderLoop();
  76712. }
  76713. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function (progress) {
  76714. if (_this._progressCallback) {
  76715. _this._progressCallback(progress);
  76716. }
  76717. }).then(function (scene) {
  76718. if (_this._currentScene) {
  76719. _this._currentScene.dispose();
  76720. }
  76721. _this._currentScene = scene;
  76722. if (_this._sceneLoadedCallback) {
  76723. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  76724. }
  76725. // Wait for textures and shaders to be ready
  76726. _this._currentScene.executeWhenReady(function () {
  76727. _this._engine.runRenderLoop(function () {
  76728. _this.renderFunction();
  76729. });
  76730. });
  76731. }).catch(function (error) {
  76732. if (_this._errorCallback) {
  76733. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  76734. }
  76735. });
  76736. }
  76737. else {
  76738. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  76739. }
  76740. };
  76741. /**
  76742. * List of files ready to be loaded
  76743. */
  76744. FilesInput.FilesToLoad = {};
  76745. return FilesInput;
  76746. }());
  76747. BABYLON.FilesInput = FilesInput;
  76748. })(BABYLON || (BABYLON = {}));
  76749. //# sourceMappingURL=babylon.filesInput.js.map
  76750. var BABYLON;
  76751. (function (BABYLON) {
  76752. /**
  76753. * Class used to store custom tags
  76754. */
  76755. var Tags = /** @class */ (function () {
  76756. function Tags() {
  76757. }
  76758. /**
  76759. * Adds support for tags on the given object
  76760. * @param obj defines the object to use
  76761. */
  76762. Tags.EnableFor = function (obj) {
  76763. obj._tags = obj._tags || {};
  76764. obj.hasTags = function () {
  76765. return Tags.HasTags(obj);
  76766. };
  76767. obj.addTags = function (tagsString) {
  76768. return Tags.AddTagsTo(obj, tagsString);
  76769. };
  76770. obj.removeTags = function (tagsString) {
  76771. return Tags.RemoveTagsFrom(obj, tagsString);
  76772. };
  76773. obj.matchesTagsQuery = function (tagsQuery) {
  76774. return Tags.MatchesQuery(obj, tagsQuery);
  76775. };
  76776. };
  76777. /**
  76778. * Removes tags support
  76779. * @param obj defines the object to use
  76780. */
  76781. Tags.DisableFor = function (obj) {
  76782. delete obj._tags;
  76783. delete obj.hasTags;
  76784. delete obj.addTags;
  76785. delete obj.removeTags;
  76786. delete obj.matchesTagsQuery;
  76787. };
  76788. /**
  76789. * Gets a boolean indicating if the given object has tags
  76790. * @param obj defines the object to use
  76791. * @returns a boolean
  76792. */
  76793. Tags.HasTags = function (obj) {
  76794. if (!obj._tags) {
  76795. return false;
  76796. }
  76797. return !BABYLON.Tools.IsEmpty(obj._tags);
  76798. };
  76799. /**
  76800. * Gets the tags available on a given object
  76801. * @param obj defines the object to use
  76802. * @param asString defines if the tags must be returned as a string instead of an array of strings
  76803. * @returns the tags
  76804. */
  76805. Tags.GetTags = function (obj, asString) {
  76806. if (asString === void 0) { asString = true; }
  76807. if (!obj._tags) {
  76808. return null;
  76809. }
  76810. if (asString) {
  76811. var tagsArray = [];
  76812. for (var tag in obj._tags) {
  76813. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  76814. tagsArray.push(tag);
  76815. }
  76816. }
  76817. return tagsArray.join(" ");
  76818. }
  76819. else {
  76820. return obj._tags;
  76821. }
  76822. };
  76823. /**
  76824. * Adds tags to an object
  76825. * @param obj defines the object to use
  76826. * @param tagsString defines the tag string. The tags 'true' and 'false' are reserved and cannot be used as tags.
  76827. * A tag cannot start with '||', '&&', and '!'. It cannot contain whitespaces
  76828. */
  76829. Tags.AddTagsTo = function (obj, tagsString) {
  76830. if (!tagsString) {
  76831. return;
  76832. }
  76833. if (typeof tagsString !== "string") {
  76834. return;
  76835. }
  76836. var tags = tagsString.split(" ");
  76837. tags.forEach(function (tag, index, array) {
  76838. Tags._AddTagTo(obj, tag);
  76839. });
  76840. };
  76841. /**
  76842. * @hidden
  76843. */
  76844. Tags._AddTagTo = function (obj, tag) {
  76845. tag = tag.trim();
  76846. if (tag === "" || tag === "true" || tag === "false") {
  76847. return;
  76848. }
  76849. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  76850. return;
  76851. }
  76852. Tags.EnableFor(obj);
  76853. obj._tags[tag] = true;
  76854. };
  76855. /**
  76856. * Removes specific tags from a specific object
  76857. * @param obj defines the object to use
  76858. * @param tagsString defines the tags to remove
  76859. */
  76860. Tags.RemoveTagsFrom = function (obj, tagsString) {
  76861. if (!Tags.HasTags(obj)) {
  76862. return;
  76863. }
  76864. var tags = tagsString.split(" ");
  76865. for (var t in tags) {
  76866. Tags._RemoveTagFrom(obj, tags[t]);
  76867. }
  76868. };
  76869. /**
  76870. * @hidden
  76871. */
  76872. Tags._RemoveTagFrom = function (obj, tag) {
  76873. delete obj._tags[tag];
  76874. };
  76875. /**
  76876. * Defines if tags hosted on an object match a given query
  76877. * @param obj defines the object to use
  76878. * @param tagsQuery defines the tag query
  76879. * @returns a boolean
  76880. */
  76881. Tags.MatchesQuery = function (obj, tagsQuery) {
  76882. if (tagsQuery === undefined) {
  76883. return true;
  76884. }
  76885. if (tagsQuery === "") {
  76886. return Tags.HasTags(obj);
  76887. }
  76888. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  76889. };
  76890. return Tags;
  76891. }());
  76892. BABYLON.Tags = Tags;
  76893. })(BABYLON || (BABYLON = {}));
  76894. //# sourceMappingURL=babylon.tags.js.map
  76895. var BABYLON;
  76896. (function (BABYLON) {
  76897. /**
  76898. * Class used to evalaute queries containing `and` and `or` operators
  76899. */
  76900. var AndOrNotEvaluator = /** @class */ (function () {
  76901. function AndOrNotEvaluator() {
  76902. }
  76903. /**
  76904. * Evaluate a query
  76905. * @param query defines the query to evaluate
  76906. * @param evaluateCallback defines the callback used to filter result
  76907. * @returns true if the query matches
  76908. */
  76909. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  76910. if (!query.match(/\([^\(\)]*\)/g)) {
  76911. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  76912. }
  76913. else {
  76914. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  76915. // remove parenthesis
  76916. r = r.slice(1, r.length - 1);
  76917. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  76918. });
  76919. }
  76920. if (query === "true") {
  76921. return true;
  76922. }
  76923. if (query === "false") {
  76924. return false;
  76925. }
  76926. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  76927. };
  76928. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  76929. evaluateCallback = evaluateCallback || (function (r) {
  76930. return r === "true" ? true : false;
  76931. });
  76932. var result;
  76933. var or = parenthesisContent.split("||");
  76934. for (var i in or) {
  76935. if (or.hasOwnProperty(i)) {
  76936. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  76937. var and = ori.split("&&");
  76938. if (and.length > 1) {
  76939. for (var j = 0; j < and.length; ++j) {
  76940. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  76941. if (andj !== "true" && andj !== "false") {
  76942. if (andj[0] === "!") {
  76943. result = !evaluateCallback(andj.substring(1));
  76944. }
  76945. else {
  76946. result = evaluateCallback(andj);
  76947. }
  76948. }
  76949. else {
  76950. result = andj === "true" ? true : false;
  76951. }
  76952. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  76953. ori = "false";
  76954. break;
  76955. }
  76956. }
  76957. }
  76958. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  76959. result = true;
  76960. break;
  76961. }
  76962. // result equals false (or undefined)
  76963. if (ori !== "true" && ori !== "false") {
  76964. if (ori[0] === "!") {
  76965. result = !evaluateCallback(ori.substring(1));
  76966. }
  76967. else {
  76968. result = evaluateCallback(ori);
  76969. }
  76970. }
  76971. else {
  76972. result = ori === "true" ? true : false;
  76973. }
  76974. }
  76975. }
  76976. // the whole parenthesis scope is replaced by 'true' or 'false'
  76977. return result ? "true" : "false";
  76978. };
  76979. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  76980. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  76981. // remove whitespaces
  76982. r = r.replace(/[\s]/g, function () { return ""; });
  76983. return r.length % 2 ? "!" : "";
  76984. });
  76985. booleanString = booleanString.trim();
  76986. if (booleanString === "!true") {
  76987. booleanString = "false";
  76988. }
  76989. else if (booleanString === "!false") {
  76990. booleanString = "true";
  76991. }
  76992. return booleanString;
  76993. };
  76994. return AndOrNotEvaluator;
  76995. }());
  76996. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  76997. })(BABYLON || (BABYLON = {}));
  76998. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  76999. var BABYLON;
  77000. (function (BABYLON) {
  77001. /**
  77002. * Class used to enable access to IndexedDB
  77003. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  77004. */
  77005. var Database = /** @class */ (function () {
  77006. /**
  77007. * Creates a new Database
  77008. * @param urlToScene defines the url to load the scene
  77009. * @param callbackManifestChecked defines the callback to use when manifest is checked
  77010. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  77011. */
  77012. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  77013. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  77014. var _this = this;
  77015. // Handling various flavors of prefixed version of IndexedDB
  77016. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  77017. this.callbackManifestChecked = callbackManifestChecked;
  77018. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  77019. this.db = null;
  77020. this._enableSceneOffline = false;
  77021. this._enableTexturesOffline = false;
  77022. this.manifestVersionFound = 0;
  77023. this.mustUpdateRessources = false;
  77024. this.hasReachedQuota = false;
  77025. if (!Database.IDBStorageEnabled) {
  77026. this.callbackManifestChecked(true);
  77027. }
  77028. else {
  77029. if (disableManifestCheck) {
  77030. this._enableSceneOffline = true;
  77031. this._enableTexturesOffline = true;
  77032. this.manifestVersionFound = 1;
  77033. BABYLON.Tools.SetImmediate(function () {
  77034. _this.callbackManifestChecked(true);
  77035. });
  77036. }
  77037. else {
  77038. this._checkManifestFile();
  77039. }
  77040. }
  77041. }
  77042. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  77043. /**
  77044. * Gets a boolean indicating if scene must be saved in the database
  77045. */
  77046. get: function () {
  77047. return this._enableSceneOffline;
  77048. },
  77049. enumerable: true,
  77050. configurable: true
  77051. });
  77052. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  77053. /**
  77054. * Gets a boolean indicating if textures must be saved in the database
  77055. */
  77056. get: function () {
  77057. return this._enableTexturesOffline;
  77058. },
  77059. enumerable: true,
  77060. configurable: true
  77061. });
  77062. Database.prototype._checkManifestFile = function () {
  77063. var _this = this;
  77064. var noManifestFile = function () {
  77065. _this._enableSceneOffline = false;
  77066. _this._enableTexturesOffline = false;
  77067. _this.callbackManifestChecked(false);
  77068. };
  77069. var timeStampUsed = false;
  77070. var manifestURL = this.currentSceneUrl + ".manifest";
  77071. var xhr = new XMLHttpRequest();
  77072. if (navigator.onLine) {
  77073. // Adding a timestamp to by-pass browsers' cache
  77074. timeStampUsed = true;
  77075. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  77076. }
  77077. xhr.open("GET", manifestURL, true);
  77078. xhr.addEventListener("load", function () {
  77079. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  77080. try {
  77081. var manifestFile = JSON.parse(xhr.response);
  77082. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  77083. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  77084. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  77085. _this.manifestVersionFound = manifestFile.version;
  77086. }
  77087. if (_this.callbackManifestChecked) {
  77088. _this.callbackManifestChecked(true);
  77089. }
  77090. }
  77091. catch (ex) {
  77092. noManifestFile();
  77093. }
  77094. }
  77095. else {
  77096. noManifestFile();
  77097. }
  77098. }, false);
  77099. xhr.addEventListener("error", function (event) {
  77100. if (timeStampUsed) {
  77101. timeStampUsed = false;
  77102. // Let's retry without the timeStamp
  77103. // It could fail when coupled with HTML5 Offline API
  77104. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  77105. xhr.open("GET", retryManifestURL, true);
  77106. xhr.send();
  77107. }
  77108. else {
  77109. noManifestFile();
  77110. }
  77111. }, false);
  77112. try {
  77113. xhr.send();
  77114. }
  77115. catch (ex) {
  77116. BABYLON.Tools.Error("Error on XHR send request.");
  77117. this.callbackManifestChecked(false);
  77118. }
  77119. };
  77120. /**
  77121. * Open the database and make it available
  77122. * @param successCallback defines the callback to call on success
  77123. * @param errorCallback defines the callback to call on error
  77124. */
  77125. Database.prototype.openAsync = function (successCallback, errorCallback) {
  77126. var _this = this;
  77127. var handleError = function () {
  77128. _this.isSupported = false;
  77129. if (errorCallback)
  77130. errorCallback();
  77131. };
  77132. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  77133. // Your browser doesn't support IndexedDB
  77134. this.isSupported = false;
  77135. if (errorCallback)
  77136. errorCallback();
  77137. }
  77138. else {
  77139. // If the DB hasn't been opened or created yet
  77140. if (!this.db) {
  77141. this.hasReachedQuota = false;
  77142. this.isSupported = true;
  77143. var request = this.idbFactory.open("babylonjs", 1);
  77144. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  77145. request.onerror = function (event) {
  77146. handleError();
  77147. };
  77148. // executes when a version change transaction cannot complete due to other active transactions
  77149. request.onblocked = function (event) {
  77150. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  77151. handleError();
  77152. };
  77153. // DB has been opened successfully
  77154. request.onsuccess = function (event) {
  77155. _this.db = request.result;
  77156. successCallback();
  77157. };
  77158. // Initialization of the DB. Creating Scenes & Textures stores
  77159. request.onupgradeneeded = function (event) {
  77160. _this.db = (event.target).result;
  77161. if (_this.db) {
  77162. try {
  77163. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  77164. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  77165. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  77166. }
  77167. catch (ex) {
  77168. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  77169. handleError();
  77170. }
  77171. }
  77172. };
  77173. }
  77174. // DB has already been created and opened
  77175. else {
  77176. if (successCallback)
  77177. successCallback();
  77178. }
  77179. }
  77180. };
  77181. /**
  77182. * Loads an image from the database
  77183. * @param url defines the url to load from
  77184. * @param image defines the target DOM image
  77185. */
  77186. Database.prototype.loadImageFromDB = function (url, image) {
  77187. var _this = this;
  77188. var completeURL = Database._ReturnFullUrlLocation(url);
  77189. var saveAndLoadImage = function () {
  77190. if (!_this.hasReachedQuota && _this.db !== null) {
  77191. // the texture is not yet in the DB, let's try to save it
  77192. _this._saveImageIntoDBAsync(completeURL, image);
  77193. }
  77194. // If the texture is not in the DB and we've reached the DB quota limit
  77195. // let's load it directly from the web
  77196. else {
  77197. image.src = url;
  77198. }
  77199. };
  77200. if (!this.mustUpdateRessources) {
  77201. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  77202. }
  77203. // First time we're download the images or update requested in the manifest file by a version change
  77204. else {
  77205. saveAndLoadImage();
  77206. }
  77207. };
  77208. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  77209. if (this.isSupported && this.db !== null) {
  77210. var texture;
  77211. var transaction = this.db.transaction(["textures"]);
  77212. transaction.onabort = function (event) {
  77213. image.src = url;
  77214. };
  77215. transaction.oncomplete = function (event) {
  77216. var blobTextureURL;
  77217. if (texture) {
  77218. var URL = window.URL || window.webkitURL;
  77219. blobTextureURL = URL.createObjectURL(texture.data);
  77220. image.onerror = function () {
  77221. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  77222. image.src = url;
  77223. };
  77224. image.src = blobTextureURL;
  77225. }
  77226. else {
  77227. notInDBCallback();
  77228. }
  77229. };
  77230. var getRequest = transaction.objectStore("textures").get(url);
  77231. getRequest.onsuccess = function (event) {
  77232. texture = (event.target).result;
  77233. };
  77234. getRequest.onerror = function (event) {
  77235. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  77236. image.src = url;
  77237. };
  77238. }
  77239. else {
  77240. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  77241. image.src = url;
  77242. }
  77243. };
  77244. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  77245. var _this = this;
  77246. if (this.isSupported) {
  77247. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  77248. var generateBlobUrl = function () {
  77249. var blobTextureURL;
  77250. if (blob) {
  77251. var URL = window.URL || window.webkitURL;
  77252. try {
  77253. blobTextureURL = URL.createObjectURL(blob);
  77254. }
  77255. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  77256. catch (ex) {
  77257. blobTextureURL = URL.createObjectURL(blob);
  77258. }
  77259. }
  77260. if (blobTextureURL) {
  77261. image.src = blobTextureURL;
  77262. }
  77263. };
  77264. if (Database.IsUASupportingBlobStorage) { // Create XHR
  77265. var xhr = new XMLHttpRequest(), blob;
  77266. xhr.open("GET", url, true);
  77267. xhr.responseType = "blob";
  77268. xhr.addEventListener("load", function () {
  77269. if (xhr.status === 200 && _this.db) {
  77270. // Blob as response (XHR2)
  77271. blob = xhr.response;
  77272. var transaction = _this.db.transaction(["textures"], "readwrite");
  77273. // the transaction could abort because of a QuotaExceededError error
  77274. transaction.onabort = function (event) {
  77275. try {
  77276. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  77277. var srcElement = (event.srcElement || event.target);
  77278. var error = srcElement.error;
  77279. if (error && error.name === "QuotaExceededError") {
  77280. _this.hasReachedQuota = true;
  77281. }
  77282. }
  77283. catch (ex) { }
  77284. generateBlobUrl();
  77285. };
  77286. transaction.oncomplete = function (event) {
  77287. generateBlobUrl();
  77288. };
  77289. var newTexture = { textureUrl: url, data: blob };
  77290. try {
  77291. // Put the blob into the dabase
  77292. var addRequest = transaction.objectStore("textures").put(newTexture);
  77293. addRequest.onsuccess = function (event) {
  77294. };
  77295. addRequest.onerror = function (event) {
  77296. generateBlobUrl();
  77297. };
  77298. }
  77299. catch (ex) {
  77300. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  77301. if (ex.code === 25) {
  77302. Database.IsUASupportingBlobStorage = false;
  77303. }
  77304. image.src = url;
  77305. }
  77306. }
  77307. else {
  77308. image.src = url;
  77309. }
  77310. }, false);
  77311. xhr.addEventListener("error", function (event) {
  77312. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  77313. image.src = url;
  77314. }, false);
  77315. xhr.send();
  77316. }
  77317. else {
  77318. image.src = url;
  77319. }
  77320. }
  77321. else {
  77322. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  77323. image.src = url;
  77324. }
  77325. };
  77326. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  77327. var _this = this;
  77328. var updateVersion = function () {
  77329. // the version is not yet in the DB or we need to update it
  77330. _this._saveVersionIntoDBAsync(url, versionLoaded);
  77331. };
  77332. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  77333. };
  77334. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  77335. var _this = this;
  77336. if (this.isSupported && this.db) {
  77337. var version;
  77338. try {
  77339. var transaction = this.db.transaction(["versions"]);
  77340. transaction.oncomplete = function (event) {
  77341. if (version) {
  77342. // If the version in the JSON file is different from the version in DB
  77343. if (_this.manifestVersionFound !== version.data) {
  77344. _this.mustUpdateRessources = true;
  77345. updateInDBCallback();
  77346. }
  77347. else {
  77348. callback(version.data);
  77349. }
  77350. }
  77351. // version was not found in DB
  77352. else {
  77353. _this.mustUpdateRessources = true;
  77354. updateInDBCallback();
  77355. }
  77356. };
  77357. transaction.onabort = function (event) {
  77358. callback(-1);
  77359. };
  77360. var getRequest = transaction.objectStore("versions").get(url);
  77361. getRequest.onsuccess = function (event) {
  77362. version = (event.target).result;
  77363. };
  77364. getRequest.onerror = function (event) {
  77365. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  77366. callback(-1);
  77367. };
  77368. }
  77369. catch (ex) {
  77370. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  77371. callback(-1);
  77372. }
  77373. }
  77374. else {
  77375. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  77376. callback(-1);
  77377. }
  77378. };
  77379. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  77380. var _this = this;
  77381. if (this.isSupported && !this.hasReachedQuota && this.db) {
  77382. try {
  77383. // Open a transaction to the database
  77384. var transaction = this.db.transaction(["versions"], "readwrite");
  77385. // the transaction could abort because of a QuotaExceededError error
  77386. transaction.onabort = function (event) {
  77387. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  77388. var error = event.srcElement['error'];
  77389. if (error && error.name === "QuotaExceededError") {
  77390. _this.hasReachedQuota = true;
  77391. }
  77392. }
  77393. catch (ex) { }
  77394. callback(-1);
  77395. };
  77396. transaction.oncomplete = function (event) {
  77397. callback(_this.manifestVersionFound);
  77398. };
  77399. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  77400. // Put the scene into the database
  77401. var addRequest = transaction.objectStore("versions").put(newVersion);
  77402. addRequest.onsuccess = function (event) {
  77403. };
  77404. addRequest.onerror = function (event) {
  77405. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  77406. };
  77407. }
  77408. catch (ex) {
  77409. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  77410. callback(-1);
  77411. }
  77412. }
  77413. else {
  77414. callback(-1);
  77415. }
  77416. };
  77417. /**
  77418. * Loads a file from database
  77419. * @param url defines the URL to load from
  77420. * @param sceneLoaded defines a callback to call on success
  77421. * @param progressCallBack defines a callback to call when progress changed
  77422. * @param errorCallback defines a callback to call on error
  77423. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  77424. */
  77425. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  77426. var _this = this;
  77427. var completeUrl = Database._ReturnFullUrlLocation(url);
  77428. var saveAndLoadFile = function () {
  77429. // the scene is not yet in the DB, let's try to save it
  77430. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  77431. };
  77432. this._checkVersionFromDB(completeUrl, function (version) {
  77433. if (version !== -1) {
  77434. if (!_this.mustUpdateRessources) {
  77435. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  77436. }
  77437. else {
  77438. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  77439. }
  77440. }
  77441. else {
  77442. if (errorCallback) {
  77443. errorCallback();
  77444. }
  77445. }
  77446. });
  77447. };
  77448. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  77449. if (this.isSupported && this.db) {
  77450. var targetStore;
  77451. if (url.indexOf(".babylon") !== -1) {
  77452. targetStore = "scenes";
  77453. }
  77454. else {
  77455. targetStore = "textures";
  77456. }
  77457. var file;
  77458. var transaction = this.db.transaction([targetStore]);
  77459. transaction.oncomplete = function (event) {
  77460. if (file) {
  77461. callback(file.data);
  77462. }
  77463. // file was not found in DB
  77464. else {
  77465. notInDBCallback();
  77466. }
  77467. };
  77468. transaction.onabort = function (event) {
  77469. notInDBCallback();
  77470. };
  77471. var getRequest = transaction.objectStore(targetStore).get(url);
  77472. getRequest.onsuccess = function (event) {
  77473. file = (event.target).result;
  77474. };
  77475. getRequest.onerror = function (event) {
  77476. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  77477. notInDBCallback();
  77478. };
  77479. }
  77480. else {
  77481. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  77482. callback();
  77483. }
  77484. };
  77485. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  77486. var _this = this;
  77487. if (this.isSupported) {
  77488. var targetStore;
  77489. if (url.indexOf(".babylon") !== -1) {
  77490. targetStore = "scenes";
  77491. }
  77492. else {
  77493. targetStore = "textures";
  77494. }
  77495. // Create XHR
  77496. var xhr = new XMLHttpRequest();
  77497. var fileData;
  77498. xhr.open("GET", url + "?" + Date.now(), true);
  77499. if (useArrayBuffer) {
  77500. xhr.responseType = "arraybuffer";
  77501. }
  77502. if (progressCallback) {
  77503. xhr.onprogress = progressCallback;
  77504. }
  77505. xhr.addEventListener("load", function () {
  77506. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  77507. // Blob as response (XHR2)
  77508. //fileData = xhr.responseText;
  77509. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  77510. if (!_this.hasReachedQuota && _this.db) {
  77511. // Open a transaction to the database
  77512. var transaction = _this.db.transaction([targetStore], "readwrite");
  77513. // the transaction could abort because of a QuotaExceededError error
  77514. transaction.onabort = function (event) {
  77515. try {
  77516. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  77517. var error = event.srcElement['error'];
  77518. if (error && error.name === "QuotaExceededError") {
  77519. _this.hasReachedQuota = true;
  77520. }
  77521. }
  77522. catch (ex) { }
  77523. callback(fileData);
  77524. };
  77525. transaction.oncomplete = function (event) {
  77526. callback(fileData);
  77527. };
  77528. var newFile;
  77529. if (targetStore === "scenes") {
  77530. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  77531. }
  77532. else {
  77533. newFile = { textureUrl: url, data: fileData };
  77534. }
  77535. try {
  77536. // Put the scene into the database
  77537. var addRequest = transaction.objectStore(targetStore).put(newFile);
  77538. addRequest.onsuccess = function (event) {
  77539. };
  77540. addRequest.onerror = function (event) {
  77541. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  77542. };
  77543. }
  77544. catch (ex) {
  77545. callback(fileData);
  77546. }
  77547. }
  77548. else {
  77549. callback(fileData);
  77550. }
  77551. }
  77552. else {
  77553. if (xhr.status >= 400 && errorCallback) {
  77554. errorCallback(xhr);
  77555. }
  77556. else {
  77557. callback();
  77558. }
  77559. }
  77560. }, false);
  77561. xhr.addEventListener("error", function (event) {
  77562. BABYLON.Tools.Error("error on XHR request.");
  77563. callback();
  77564. }, false);
  77565. xhr.send();
  77566. }
  77567. else {
  77568. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  77569. callback();
  77570. }
  77571. };
  77572. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  77573. Database.IsUASupportingBlobStorage = true;
  77574. /** Gets a boolean indicating if Database storate is enabled */
  77575. Database.IDBStorageEnabled = true;
  77576. Database._ParseURL = function (url) {
  77577. var a = document.createElement('a');
  77578. a.href = url;
  77579. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  77580. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  77581. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  77582. return absLocation;
  77583. };
  77584. Database._ReturnFullUrlLocation = function (url) {
  77585. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  77586. return (Database._ParseURL(window.location.href) + url);
  77587. }
  77588. else {
  77589. return url;
  77590. }
  77591. };
  77592. return Database;
  77593. }());
  77594. BABYLON.Database = Database;
  77595. })(BABYLON || (BABYLON = {}));
  77596. //# sourceMappingURL=babylon.database.js.map
  77597. var BABYLON;
  77598. (function (BABYLON) {
  77599. /**
  77600. * This represents all the required information to add a fresnel effect on a material:
  77601. * @see http://doc.babylonjs.com/how_to/how_to_use_fresnelparameters
  77602. */
  77603. var FresnelParameters = /** @class */ (function () {
  77604. function FresnelParameters() {
  77605. this._isEnabled = true;
  77606. /**
  77607. * Define the color used on edges (grazing angle)
  77608. */
  77609. this.leftColor = BABYLON.Color3.White();
  77610. /**
  77611. * Define the color used on center
  77612. */
  77613. this.rightColor = BABYLON.Color3.Black();
  77614. /**
  77615. * Define bias applied to computed fresnel term
  77616. */
  77617. this.bias = 0;
  77618. /**
  77619. * Defined the power exponent applied to fresnel term
  77620. */
  77621. this.power = 1;
  77622. }
  77623. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  77624. /**
  77625. * Define if the fresnel effect is enable or not.
  77626. */
  77627. get: function () {
  77628. return this._isEnabled;
  77629. },
  77630. set: function (value) {
  77631. if (this._isEnabled === value) {
  77632. return;
  77633. }
  77634. this._isEnabled = value;
  77635. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  77636. },
  77637. enumerable: true,
  77638. configurable: true
  77639. });
  77640. /**
  77641. * Clones the current fresnel and its valuues
  77642. * @returns a clone fresnel configuration
  77643. */
  77644. FresnelParameters.prototype.clone = function () {
  77645. var newFresnelParameters = new FresnelParameters();
  77646. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  77647. return newFresnelParameters;
  77648. };
  77649. /**
  77650. * Serializes the current fresnel parameters to a JSON representation.
  77651. * @return the JSON serialization
  77652. */
  77653. FresnelParameters.prototype.serialize = function () {
  77654. var serializationObject = {};
  77655. serializationObject.isEnabled = this.isEnabled;
  77656. serializationObject.leftColor = this.leftColor.asArray();
  77657. serializationObject.rightColor = this.rightColor.asArray();
  77658. serializationObject.bias = this.bias;
  77659. serializationObject.power = this.power;
  77660. return serializationObject;
  77661. };
  77662. /**
  77663. * Parse a JSON object and deserialize it to a new Fresnel parameter object.
  77664. * @param parsedFresnelParameters Define the JSON representation
  77665. * @returns the parsed parameters
  77666. */
  77667. FresnelParameters.Parse = function (parsedFresnelParameters) {
  77668. var fresnelParameters = new FresnelParameters();
  77669. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  77670. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  77671. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  77672. fresnelParameters.bias = parsedFresnelParameters.bias;
  77673. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  77674. return fresnelParameters;
  77675. };
  77676. return FresnelParameters;
  77677. }());
  77678. BABYLON.FresnelParameters = FresnelParameters;
  77679. })(BABYLON || (BABYLON = {}));
  77680. //# sourceMappingURL=babylon.fresnelParameters.js.map
  77681. var BABYLON;
  77682. (function (BABYLON) {
  77683. /**
  77684. * A multi-material is used to apply different materials to different parts of the same object without the need of
  77685. * separate meshes. This can be use to improve performances.
  77686. * @see http://doc.babylonjs.com/how_to/multi_materials
  77687. */
  77688. var MultiMaterial = /** @class */ (function (_super) {
  77689. __extends(MultiMaterial, _super);
  77690. /**
  77691. * Instantiates a new Multi Material
  77692. * A multi-material is used to apply different materials to different parts of the same object without the need of
  77693. * separate meshes. This can be use to improve performances.
  77694. * @see http://doc.babylonjs.com/how_to/multi_materials
  77695. * @param name Define the name in the scene
  77696. * @param scene Define the scene the material belongs to
  77697. */
  77698. function MultiMaterial(name, scene) {
  77699. var _this = _super.call(this, name, scene, true) || this;
  77700. scene.multiMaterials.push(_this);
  77701. _this.subMaterials = new Array();
  77702. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  77703. return _this;
  77704. }
  77705. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  77706. /**
  77707. * Gets or Sets the list of Materials used within the multi material.
  77708. * They need to be ordered according to the submeshes order in the associated mesh
  77709. */
  77710. get: function () {
  77711. return this._subMaterials;
  77712. },
  77713. set: function (value) {
  77714. this._subMaterials = value;
  77715. this._hookArray(value);
  77716. },
  77717. enumerable: true,
  77718. configurable: true
  77719. });
  77720. MultiMaterial.prototype._hookArray = function (array) {
  77721. var _this = this;
  77722. var oldPush = array.push;
  77723. array.push = function () {
  77724. var items = [];
  77725. for (var _i = 0; _i < arguments.length; _i++) {
  77726. items[_i] = arguments[_i];
  77727. }
  77728. var result = oldPush.apply(array, items);
  77729. _this._markAllSubMeshesAsTexturesDirty();
  77730. return result;
  77731. };
  77732. var oldSplice = array.splice;
  77733. array.splice = function (index, deleteCount) {
  77734. var deleted = oldSplice.apply(array, [index, deleteCount]);
  77735. _this._markAllSubMeshesAsTexturesDirty();
  77736. return deleted;
  77737. };
  77738. };
  77739. /**
  77740. * Get one of the submaterial by its index in the submaterials array
  77741. * @param index The index to look the sub material at
  77742. * @returns The Material if the index has been defined
  77743. */
  77744. MultiMaterial.prototype.getSubMaterial = function (index) {
  77745. if (index < 0 || index >= this.subMaterials.length) {
  77746. return this.getScene().defaultMaterial;
  77747. }
  77748. return this.subMaterials[index];
  77749. };
  77750. /**
  77751. * Get the list of active textures for the whole sub materials list.
  77752. * @returns All the textures that will be used during the rendering
  77753. */
  77754. MultiMaterial.prototype.getActiveTextures = function () {
  77755. var _a;
  77756. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  77757. if (subMaterial) {
  77758. return subMaterial.getActiveTextures();
  77759. }
  77760. else {
  77761. return [];
  77762. }
  77763. }));
  77764. };
  77765. /**
  77766. * Gets the current class name of the material e.g. "MultiMaterial"
  77767. * Mainly use in serialization.
  77768. * @returns the class name
  77769. */
  77770. MultiMaterial.prototype.getClassName = function () {
  77771. return "MultiMaterial";
  77772. };
  77773. /**
  77774. * Checks if the material is ready to render the requested sub mesh
  77775. * @param mesh Define the mesh the submesh belongs to
  77776. * @param subMesh Define the sub mesh to look readyness for
  77777. * @param useInstances Define whether or not the material is used with instances
  77778. * @returns true if ready, otherwise false
  77779. */
  77780. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  77781. for (var index = 0; index < this.subMaterials.length; index++) {
  77782. var subMaterial = this.subMaterials[index];
  77783. if (subMaterial) {
  77784. if (subMaterial.storeEffectOnSubMeshes) {
  77785. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  77786. return false;
  77787. }
  77788. continue;
  77789. }
  77790. if (!subMaterial.isReady(mesh)) {
  77791. return false;
  77792. }
  77793. }
  77794. }
  77795. return true;
  77796. };
  77797. /**
  77798. * Clones the current material and its related sub materials
  77799. * @param name Define the name of the newly cloned material
  77800. * @param cloneChildren Define if submaterial will be cloned or shared with the parent instance
  77801. * @returns the cloned material
  77802. */
  77803. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  77804. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  77805. for (var index = 0; index < this.subMaterials.length; index++) {
  77806. var subMaterial = null;
  77807. var current = this.subMaterials[index];
  77808. if (cloneChildren && current) {
  77809. subMaterial = current.clone(name + "-" + current.name);
  77810. }
  77811. else {
  77812. subMaterial = this.subMaterials[index];
  77813. }
  77814. newMultiMaterial.subMaterials.push(subMaterial);
  77815. }
  77816. return newMultiMaterial;
  77817. };
  77818. /**
  77819. * Serializes the materials into a JSON representation.
  77820. * @returns the JSON representation
  77821. */
  77822. MultiMaterial.prototype.serialize = function () {
  77823. var serializationObject = {};
  77824. serializationObject.name = this.name;
  77825. serializationObject.id = this.id;
  77826. if (BABYLON.Tags) {
  77827. serializationObject.tags = BABYLON.Tags.GetTags(this);
  77828. }
  77829. serializationObject.materials = [];
  77830. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  77831. var subMat = this.subMaterials[matIndex];
  77832. if (subMat) {
  77833. serializationObject.materials.push(subMat.id);
  77834. }
  77835. else {
  77836. serializationObject.materials.push(null);
  77837. }
  77838. }
  77839. return serializationObject;
  77840. };
  77841. /**
  77842. * Dispose the material and release its associated resources
  77843. * @param forceDisposeEffect Define if we want to force disposing the associated effect (if false the shader is not released and could be reuse later on)
  77844. * @param forceDisposeTextures Define if we want to force disposing the associated textures (if false, they will not be disposed and can still be use elsewhere in the app)
  77845. */
  77846. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  77847. var scene = this.getScene();
  77848. if (!scene) {
  77849. return;
  77850. }
  77851. var index = scene.multiMaterials.indexOf(this);
  77852. if (index >= 0) {
  77853. scene.multiMaterials.splice(index, 1);
  77854. }
  77855. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  77856. };
  77857. return MultiMaterial;
  77858. }(BABYLON.Material));
  77859. BABYLON.MultiMaterial = MultiMaterial;
  77860. })(BABYLON || (BABYLON = {}));
  77861. //# sourceMappingURL=babylon.multiMaterial.js.map
  77862. var BABYLON;
  77863. (function (BABYLON) {
  77864. /**
  77865. * Manage the touch inputs to control the movement of a free camera.
  77866. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  77867. */
  77868. var FreeCameraTouchInput = /** @class */ (function () {
  77869. function FreeCameraTouchInput() {
  77870. /**
  77871. * Defines the touch sensibility for rotation.
  77872. * The higher the faster.
  77873. */
  77874. this.touchAngularSensibility = 200000.0;
  77875. /**
  77876. * Defines the touch sensibility for move.
  77877. * The higher the faster.
  77878. */
  77879. this.touchMoveSensibility = 250.0;
  77880. this._offsetX = null;
  77881. this._offsetY = null;
  77882. this._pointerPressed = new Array();
  77883. }
  77884. /**
  77885. * Attach the input controls to a specific dom element to get the input from.
  77886. * @param element Defines the element the controls should be listened from
  77887. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  77888. */
  77889. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  77890. var _this = this;
  77891. var previousPosition = null;
  77892. if (this._pointerInput === undefined) {
  77893. this._onLostFocus = function (evt) {
  77894. _this._offsetX = null;
  77895. _this._offsetY = null;
  77896. };
  77897. this._pointerInput = function (p, s) {
  77898. var evt = p.event;
  77899. if (evt.pointerType === "mouse") {
  77900. return;
  77901. }
  77902. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  77903. if (!noPreventDefault) {
  77904. evt.preventDefault();
  77905. }
  77906. _this._pointerPressed.push(evt.pointerId);
  77907. if (_this._pointerPressed.length !== 1) {
  77908. return;
  77909. }
  77910. previousPosition = {
  77911. x: evt.clientX,
  77912. y: evt.clientY
  77913. };
  77914. }
  77915. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  77916. if (!noPreventDefault) {
  77917. evt.preventDefault();
  77918. }
  77919. var index = _this._pointerPressed.indexOf(evt.pointerId);
  77920. if (index === -1) {
  77921. return;
  77922. }
  77923. _this._pointerPressed.splice(index, 1);
  77924. if (index != 0) {
  77925. return;
  77926. }
  77927. previousPosition = null;
  77928. _this._offsetX = null;
  77929. _this._offsetY = null;
  77930. }
  77931. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  77932. if (!noPreventDefault) {
  77933. evt.preventDefault();
  77934. }
  77935. if (!previousPosition) {
  77936. return;
  77937. }
  77938. var index = _this._pointerPressed.indexOf(evt.pointerId);
  77939. if (index != 0) {
  77940. return;
  77941. }
  77942. _this._offsetX = evt.clientX - previousPosition.x;
  77943. _this._offsetY = -(evt.clientY - previousPosition.y);
  77944. }
  77945. };
  77946. }
  77947. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  77948. if (this._onLostFocus) {
  77949. element.addEventListener("blur", this._onLostFocus);
  77950. }
  77951. };
  77952. /**
  77953. * Detach the current controls from the specified dom element.
  77954. * @param element Defines the element to stop listening the inputs from
  77955. */
  77956. FreeCameraTouchInput.prototype.detachControl = function (element) {
  77957. if (this._pointerInput && element) {
  77958. if (this._observer) {
  77959. this.camera.getScene().onPointerObservable.remove(this._observer);
  77960. this._observer = null;
  77961. }
  77962. if (this._onLostFocus) {
  77963. element.removeEventListener("blur", this._onLostFocus);
  77964. this._onLostFocus = null;
  77965. }
  77966. this._pointerPressed = [];
  77967. this._offsetX = null;
  77968. this._offsetY = null;
  77969. }
  77970. };
  77971. /**
  77972. * Update the current camera state depending on the inputs that have been used this frame.
  77973. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  77974. */
  77975. FreeCameraTouchInput.prototype.checkInputs = function () {
  77976. if (this._offsetX && this._offsetY) {
  77977. var camera = this.camera;
  77978. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  77979. if (this._pointerPressed.length > 1) {
  77980. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  77981. }
  77982. else {
  77983. var speed = camera._computeLocalCameraSpeed();
  77984. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  77985. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  77986. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  77987. }
  77988. }
  77989. };
  77990. /**
  77991. * Gets the class name of the current intput.
  77992. * @returns the class name
  77993. */
  77994. FreeCameraTouchInput.prototype.getClassName = function () {
  77995. return "FreeCameraTouchInput";
  77996. };
  77997. /**
  77998. * Get the friendly name associated with the input class.
  77999. * @returns the input friendly name
  78000. */
  78001. FreeCameraTouchInput.prototype.getSimpleName = function () {
  78002. return "touch";
  78003. };
  78004. __decorate([
  78005. BABYLON.serialize()
  78006. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  78007. __decorate([
  78008. BABYLON.serialize()
  78009. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  78010. return FreeCameraTouchInput;
  78011. }());
  78012. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  78013. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  78014. })(BABYLON || (BABYLON = {}));
  78015. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  78016. var BABYLON;
  78017. (function (BABYLON) {
  78018. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  78019. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  78020. });
  78021. /**
  78022. * This represents a FPS type of camera controlled by touch.
  78023. * This is like a universal camera minus the Gamepad controls.
  78024. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  78025. */
  78026. var TouchCamera = /** @class */ (function (_super) {
  78027. __extends(TouchCamera, _super);
  78028. /**
  78029. * Instantiates a new touch camera.
  78030. * This represents a FPS type of camera controlled by touch.
  78031. * This is like a universal camera minus the Gamepad controls.
  78032. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  78033. * @param name Define the name of the camera in the scene
  78034. * @param position Define the start position of the camera in the scene
  78035. * @param scene Define the scene the camera belongs to
  78036. */
  78037. function TouchCamera(name, position, scene) {
  78038. var _this = _super.call(this, name, position, scene) || this;
  78039. _this.inputs.addTouch();
  78040. _this._setupInputs();
  78041. return _this;
  78042. }
  78043. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  78044. /**
  78045. * Defines the touch sensibility for rotation.
  78046. * The higher the faster.
  78047. */
  78048. get: function () {
  78049. var touch = this.inputs.attached["touch"];
  78050. if (touch)
  78051. return touch.touchAngularSensibility;
  78052. return 0;
  78053. },
  78054. set: function (value) {
  78055. var touch = this.inputs.attached["touch"];
  78056. if (touch)
  78057. touch.touchAngularSensibility = value;
  78058. },
  78059. enumerable: true,
  78060. configurable: true
  78061. });
  78062. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  78063. /**
  78064. * Defines the touch sensibility for move.
  78065. * The higher the faster.
  78066. */
  78067. get: function () {
  78068. var touch = this.inputs.attached["touch"];
  78069. if (touch)
  78070. return touch.touchMoveSensibility;
  78071. return 0;
  78072. },
  78073. set: function (value) {
  78074. var touch = this.inputs.attached["touch"];
  78075. if (touch)
  78076. touch.touchMoveSensibility = value;
  78077. },
  78078. enumerable: true,
  78079. configurable: true
  78080. });
  78081. /**
  78082. * Gets the current object class name.
  78083. * @return the class name
  78084. */
  78085. TouchCamera.prototype.getClassName = function () {
  78086. return "TouchCamera";
  78087. };
  78088. /** @hidden */
  78089. TouchCamera.prototype._setupInputs = function () {
  78090. var mouse = this.inputs.attached["mouse"];
  78091. if (mouse) {
  78092. mouse.touchEnabled = false;
  78093. }
  78094. };
  78095. return TouchCamera;
  78096. }(BABYLON.FreeCamera));
  78097. BABYLON.TouchCamera = TouchCamera;
  78098. })(BABYLON || (BABYLON = {}));
  78099. //# sourceMappingURL=babylon.touchCamera.js.map
  78100. var BABYLON;
  78101. (function (BABYLON) {
  78102. /**
  78103. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  78104. * This is the base class of any Procedural texture and contains most of the shareable code.
  78105. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  78106. */
  78107. var ProceduralTexture = /** @class */ (function (_super) {
  78108. __extends(ProceduralTexture, _super);
  78109. /**
  78110. * Instantiates a new procedural texture.
  78111. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  78112. * This is the base class of any Procedural texture and contains most of the shareable code.
  78113. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  78114. * @param name Define the name of the texture
  78115. * @param size Define the size of the texture to create
  78116. * @param fragment Define the fragment shader to use to generate the texture or null if it is defined later
  78117. * @param scene Define the scene the texture belongs to
  78118. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  78119. * @param generateMipMaps Define if the texture should creates mip maps or not
  78120. * @param isCube Define if the texture is a cube texture or not (this will render each faces of the cube)
  78121. */
  78122. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  78123. if (fallbackTexture === void 0) { fallbackTexture = null; }
  78124. if (generateMipMaps === void 0) { generateMipMaps = true; }
  78125. if (isCube === void 0) { isCube = false; }
  78126. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  78127. _this.isCube = isCube;
  78128. /**
  78129. * Define if the texture is enabled or not (disabled texture will not render)
  78130. */
  78131. _this.isEnabled = true;
  78132. /**
  78133. * Event raised when the texture is generated
  78134. */
  78135. _this.onGeneratedObservable = new BABYLON.Observable();
  78136. /** @hidden */
  78137. _this._textures = {};
  78138. _this._currentRefreshId = -1;
  78139. _this._refreshRate = 1;
  78140. _this._vertexBuffers = {};
  78141. _this._uniforms = new Array();
  78142. _this._samplers = new Array();
  78143. _this._floats = {};
  78144. _this._ints = {};
  78145. _this._floatsArrays = {};
  78146. _this._colors3 = {};
  78147. _this._colors4 = {};
  78148. _this._vectors2 = {};
  78149. _this._vectors3 = {};
  78150. _this._matrices = {};
  78151. _this._fallbackTextureUsed = false;
  78152. _this._cachedDefines = "";
  78153. _this._contentUpdateId = -1;
  78154. scene = _this.getScene();
  78155. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  78156. if (!component) {
  78157. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  78158. scene._addComponent(component);
  78159. }
  78160. scene.proceduralTextures.push(_this);
  78161. _this._engine = scene.getEngine();
  78162. _this.name = name;
  78163. _this.isRenderTarget = true;
  78164. _this._size = size;
  78165. _this._generateMipMaps = generateMipMaps;
  78166. _this.setFragment(fragment);
  78167. _this._fallbackTexture = fallbackTexture;
  78168. if (isCube) {
  78169. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  78170. _this.setFloat("face", 0);
  78171. }
  78172. else {
  78173. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  78174. }
  78175. // VBO
  78176. var vertices = [];
  78177. vertices.push(1, 1);
  78178. vertices.push(-1, 1);
  78179. vertices.push(-1, -1);
  78180. vertices.push(1, -1);
  78181. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  78182. _this._createIndexBuffer();
  78183. return _this;
  78184. }
  78185. /**
  78186. * Gets texture content (Use this function wisely as reading from a texture can be slow)
  78187. * @returns an ArrayBufferView (Uint8Array or Float32Array)
  78188. */
  78189. ProceduralTexture.prototype.getContent = function () {
  78190. if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
  78191. return this._contentData;
  78192. }
  78193. this._contentData = this.readPixels(0, 0, this._contentData);
  78194. this._contentUpdateId = this._currentRefreshId;
  78195. return this._contentData;
  78196. };
  78197. ProceduralTexture.prototype._createIndexBuffer = function () {
  78198. var engine = this._engine;
  78199. // Indices
  78200. var indices = [];
  78201. indices.push(0);
  78202. indices.push(1);
  78203. indices.push(2);
  78204. indices.push(0);
  78205. indices.push(2);
  78206. indices.push(3);
  78207. this._indexBuffer = engine.createIndexBuffer(indices);
  78208. };
  78209. /** @hidden */
  78210. ProceduralTexture.prototype._rebuild = function () {
  78211. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78212. if (vb) {
  78213. vb._rebuild();
  78214. }
  78215. this._createIndexBuffer();
  78216. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  78217. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  78218. }
  78219. };
  78220. /**
  78221. * Resets the texture in order to recreate its associated resources.
  78222. * This can be called in case of context loss
  78223. */
  78224. ProceduralTexture.prototype.reset = function () {
  78225. if (this._effect === undefined) {
  78226. return;
  78227. }
  78228. var engine = this._engine;
  78229. engine._releaseEffect(this._effect);
  78230. };
  78231. ProceduralTexture.prototype._getDefines = function () {
  78232. return "";
  78233. };
  78234. /**
  78235. * Is the texture ready to be used ? (rendered at least once)
  78236. * @returns true if ready, otherwise, false.
  78237. */
  78238. ProceduralTexture.prototype.isReady = function () {
  78239. var _this = this;
  78240. var engine = this._engine;
  78241. var shaders;
  78242. if (!this._fragment) {
  78243. return false;
  78244. }
  78245. if (this._fallbackTextureUsed) {
  78246. return true;
  78247. }
  78248. var defines = this._getDefines();
  78249. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  78250. return true;
  78251. }
  78252. if (this._fragment.fragmentElement !== undefined) {
  78253. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  78254. }
  78255. else {
  78256. shaders = { vertex: "procedural", fragment: this._fragment };
  78257. }
  78258. this._cachedDefines = defines;
  78259. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  78260. _this.releaseInternalTexture();
  78261. if (_this._fallbackTexture) {
  78262. _this._texture = _this._fallbackTexture._texture;
  78263. if (_this._texture) {
  78264. _this._texture.incrementReferences();
  78265. }
  78266. }
  78267. _this._fallbackTextureUsed = true;
  78268. });
  78269. return this._effect.isReady();
  78270. };
  78271. /**
  78272. * Resets the refresh counter of the texture and start bak from scratch.
  78273. * Could be usefull to regenerate the texture if it is setup to render only once.
  78274. */
  78275. ProceduralTexture.prototype.resetRefreshCounter = function () {
  78276. this._currentRefreshId = -1;
  78277. };
  78278. /**
  78279. * Set the fragment shader to use in order to render the texture.
  78280. * @param fragment This can be set to a path (into the shader store) or to a json object containing a fragmentElement property.
  78281. */
  78282. ProceduralTexture.prototype.setFragment = function (fragment) {
  78283. this._fragment = fragment;
  78284. };
  78285. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  78286. /**
  78287. * Define the refresh rate of the texture or the rendering frequency.
  78288. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  78289. */
  78290. get: function () {
  78291. return this._refreshRate;
  78292. },
  78293. set: function (value) {
  78294. this._refreshRate = value;
  78295. this.resetRefreshCounter();
  78296. },
  78297. enumerable: true,
  78298. configurable: true
  78299. });
  78300. /** @hidden */
  78301. ProceduralTexture.prototype._shouldRender = function () {
  78302. if (!this.isEnabled || !this.isReady() || !this._texture) {
  78303. if (this._texture) {
  78304. this._texture.isReady = false;
  78305. }
  78306. return false;
  78307. }
  78308. if (this._fallbackTextureUsed) {
  78309. return false;
  78310. }
  78311. if (this._currentRefreshId === -1) { // At least render once
  78312. this._currentRefreshId = 1;
  78313. return true;
  78314. }
  78315. if (this.refreshRate === this._currentRefreshId) {
  78316. this._currentRefreshId = 1;
  78317. return true;
  78318. }
  78319. this._currentRefreshId++;
  78320. return false;
  78321. };
  78322. /**
  78323. * Get the size the texture is rendering at.
  78324. * @returns the size (texture is always squared)
  78325. */
  78326. ProceduralTexture.prototype.getRenderSize = function () {
  78327. return this._size;
  78328. };
  78329. /**
  78330. * Resize the texture to new value.
  78331. * @param size Define the new size the texture should have
  78332. * @param generateMipMaps Define whether the new texture should create mip maps
  78333. */
  78334. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  78335. if (this._fallbackTextureUsed) {
  78336. return;
  78337. }
  78338. this.releaseInternalTexture();
  78339. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  78340. // Update properties
  78341. this._size = size;
  78342. this._generateMipMaps = generateMipMaps;
  78343. };
  78344. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  78345. if (this._uniforms.indexOf(uniformName) === -1) {
  78346. this._uniforms.push(uniformName);
  78347. }
  78348. };
  78349. /**
  78350. * Set a texture in the shader program used to render.
  78351. * @param name Define the name of the uniform samplers as defined in the shader
  78352. * @param texture Define the texture to bind to this sampler
  78353. * @return the texture itself allowing "fluent" like uniform updates
  78354. */
  78355. ProceduralTexture.prototype.setTexture = function (name, texture) {
  78356. if (this._samplers.indexOf(name) === -1) {
  78357. this._samplers.push(name);
  78358. }
  78359. this._textures[name] = texture;
  78360. return this;
  78361. };
  78362. /**
  78363. * Set a float in the shader.
  78364. * @param name Define the name of the uniform as defined in the shader
  78365. * @param value Define the value to give to the uniform
  78366. * @return the texture itself allowing "fluent" like uniform updates
  78367. */
  78368. ProceduralTexture.prototype.setFloat = function (name, value) {
  78369. this._checkUniform(name);
  78370. this._floats[name] = value;
  78371. return this;
  78372. };
  78373. /**
  78374. * Set a int in the shader.
  78375. * @param name Define the name of the uniform as defined in the shader
  78376. * @param value Define the value to give to the uniform
  78377. * @return the texture itself allowing "fluent" like uniform updates
  78378. */
  78379. ProceduralTexture.prototype.setInt = function (name, value) {
  78380. this._checkUniform(name);
  78381. this._ints[name] = value;
  78382. return this;
  78383. };
  78384. /**
  78385. * Set an array of floats in the shader.
  78386. * @param name Define the name of the uniform as defined in the shader
  78387. * @param value Define the value to give to the uniform
  78388. * @return the texture itself allowing "fluent" like uniform updates
  78389. */
  78390. ProceduralTexture.prototype.setFloats = function (name, value) {
  78391. this._checkUniform(name);
  78392. this._floatsArrays[name] = value;
  78393. return this;
  78394. };
  78395. /**
  78396. * Set a vec3 in the shader from a Color3.
  78397. * @param name Define the name of the uniform as defined in the shader
  78398. * @param value Define the value to give to the uniform
  78399. * @return the texture itself allowing "fluent" like uniform updates
  78400. */
  78401. ProceduralTexture.prototype.setColor3 = function (name, value) {
  78402. this._checkUniform(name);
  78403. this._colors3[name] = value;
  78404. return this;
  78405. };
  78406. /**
  78407. * Set a vec4 in the shader from a Color4.
  78408. * @param name Define the name of the uniform as defined in the shader
  78409. * @param value Define the value to give to the uniform
  78410. * @return the texture itself allowing "fluent" like uniform updates
  78411. */
  78412. ProceduralTexture.prototype.setColor4 = function (name, value) {
  78413. this._checkUniform(name);
  78414. this._colors4[name] = value;
  78415. return this;
  78416. };
  78417. /**
  78418. * Set a vec2 in the shader from a Vector2.
  78419. * @param name Define the name of the uniform as defined in the shader
  78420. * @param value Define the value to give to the uniform
  78421. * @return the texture itself allowing "fluent" like uniform updates
  78422. */
  78423. ProceduralTexture.prototype.setVector2 = function (name, value) {
  78424. this._checkUniform(name);
  78425. this._vectors2[name] = value;
  78426. return this;
  78427. };
  78428. /**
  78429. * Set a vec3 in the shader from a Vector3.
  78430. * @param name Define the name of the uniform as defined in the shader
  78431. * @param value Define the value to give to the uniform
  78432. * @return the texture itself allowing "fluent" like uniform updates
  78433. */
  78434. ProceduralTexture.prototype.setVector3 = function (name, value) {
  78435. this._checkUniform(name);
  78436. this._vectors3[name] = value;
  78437. return this;
  78438. };
  78439. /**
  78440. * Set a mat4 in the shader from a MAtrix.
  78441. * @param name Define the name of the uniform as defined in the shader
  78442. * @param value Define the value to give to the uniform
  78443. * @return the texture itself allowing "fluent" like uniform updates
  78444. */
  78445. ProceduralTexture.prototype.setMatrix = function (name, value) {
  78446. this._checkUniform(name);
  78447. this._matrices[name] = value;
  78448. return this;
  78449. };
  78450. /**
  78451. * Render the texture to its associated render target.
  78452. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  78453. */
  78454. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  78455. var scene = this.getScene();
  78456. if (!scene) {
  78457. return;
  78458. }
  78459. var engine = this._engine;
  78460. // Render
  78461. engine.enableEffect(this._effect);
  78462. engine.setState(false);
  78463. // Texture
  78464. for (var name in this._textures) {
  78465. this._effect.setTexture(name, this._textures[name]);
  78466. }
  78467. // Float
  78468. for (name in this._ints) {
  78469. this._effect.setInt(name, this._ints[name]);
  78470. }
  78471. // Float
  78472. for (name in this._floats) {
  78473. this._effect.setFloat(name, this._floats[name]);
  78474. }
  78475. // Floats
  78476. for (name in this._floatsArrays) {
  78477. this._effect.setArray(name, this._floatsArrays[name]);
  78478. }
  78479. // Color3
  78480. for (name in this._colors3) {
  78481. this._effect.setColor3(name, this._colors3[name]);
  78482. }
  78483. // Color4
  78484. for (name in this._colors4) {
  78485. var color = this._colors4[name];
  78486. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  78487. }
  78488. // Vector2
  78489. for (name in this._vectors2) {
  78490. this._effect.setVector2(name, this._vectors2[name]);
  78491. }
  78492. // Vector3
  78493. for (name in this._vectors3) {
  78494. this._effect.setVector3(name, this._vectors3[name]);
  78495. }
  78496. // Matrix
  78497. for (name in this._matrices) {
  78498. this._effect.setMatrix(name, this._matrices[name]);
  78499. }
  78500. if (!this._texture) {
  78501. return;
  78502. }
  78503. if (this.isCube) {
  78504. for (var face = 0; face < 6; face++) {
  78505. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  78506. // VBOs
  78507. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  78508. this._effect.setFloat("face", face);
  78509. // Clear
  78510. engine.clear(scene.clearColor, true, true, true);
  78511. // Draw order
  78512. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  78513. // Mipmaps
  78514. if (face === 5) {
  78515. engine.generateMipMapsForCubemap(this._texture);
  78516. }
  78517. }
  78518. }
  78519. else {
  78520. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  78521. // VBOs
  78522. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  78523. // Clear
  78524. engine.clear(scene.clearColor, true, true, true);
  78525. // Draw order
  78526. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  78527. }
  78528. // Unbind
  78529. engine.unBindFramebuffer(this._texture, this.isCube);
  78530. if (this.onGenerated) {
  78531. this.onGenerated();
  78532. }
  78533. this.onGeneratedObservable.notifyObservers(this);
  78534. };
  78535. /**
  78536. * Clone the texture.
  78537. * @returns the cloned texture
  78538. */
  78539. ProceduralTexture.prototype.clone = function () {
  78540. var textureSize = this.getSize();
  78541. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  78542. // Base texture
  78543. newTexture.hasAlpha = this.hasAlpha;
  78544. newTexture.level = this.level;
  78545. // RenderTarget Texture
  78546. newTexture.coordinatesMode = this.coordinatesMode;
  78547. return newTexture;
  78548. };
  78549. /**
  78550. * Dispose the texture and release its asoociated resources.
  78551. */
  78552. ProceduralTexture.prototype.dispose = function () {
  78553. var scene = this.getScene();
  78554. if (!scene) {
  78555. return;
  78556. }
  78557. var index = scene.proceduralTextures.indexOf(this);
  78558. if (index >= 0) {
  78559. scene.proceduralTextures.splice(index, 1);
  78560. }
  78561. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78562. if (vertexBuffer) {
  78563. vertexBuffer.dispose();
  78564. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  78565. }
  78566. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  78567. this._indexBuffer = null;
  78568. }
  78569. _super.prototype.dispose.call(this);
  78570. };
  78571. __decorate([
  78572. BABYLON.serialize()
  78573. ], ProceduralTexture.prototype, "isEnabled", void 0);
  78574. __decorate([
  78575. BABYLON.serialize()
  78576. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  78577. __decorate([
  78578. BABYLON.serialize()
  78579. ], ProceduralTexture.prototype, "_size", void 0);
  78580. __decorate([
  78581. BABYLON.serialize()
  78582. ], ProceduralTexture.prototype, "refreshRate", null);
  78583. return ProceduralTexture;
  78584. }(BABYLON.Texture));
  78585. BABYLON.ProceduralTexture = ProceduralTexture;
  78586. })(BABYLON || (BABYLON = {}));
  78587. //# sourceMappingURL=babylon.proceduralTexture.js.map
  78588. var BABYLON;
  78589. (function (BABYLON) {
  78590. /**
  78591. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  78592. * in a given scene.
  78593. */
  78594. var ProceduralTextureSceneComponent = /** @class */ (function () {
  78595. /**
  78596. * Creates a new instance of the component for the given scene
  78597. * @param scene Defines the scene to register the component in
  78598. */
  78599. function ProceduralTextureSceneComponent(scene) {
  78600. /**
  78601. * The component name helpfull to identify the component in the list of scene components.
  78602. */
  78603. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  78604. this.scene = scene;
  78605. this.scene.proceduralTextures = new Array();
  78606. scene.layers = new Array();
  78607. }
  78608. /**
  78609. * Registers the component in a given scene
  78610. */
  78611. ProceduralTextureSceneComponent.prototype.register = function () {
  78612. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  78613. };
  78614. /**
  78615. * Rebuilds the elements related to this component in case of
  78616. * context lost for instance.
  78617. */
  78618. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  78619. // Nothing to do here.
  78620. };
  78621. /**
  78622. * Disposes the component and the associated ressources.
  78623. */
  78624. ProceduralTextureSceneComponent.prototype.dispose = function () {
  78625. // Nothing to do here.
  78626. };
  78627. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  78628. if (this.scene.proceduralTexturesEnabled) {
  78629. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  78630. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  78631. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  78632. if (proceduralTexture._shouldRender()) {
  78633. proceduralTexture.render();
  78634. }
  78635. }
  78636. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  78637. }
  78638. };
  78639. return ProceduralTextureSceneComponent;
  78640. }());
  78641. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  78642. })(BABYLON || (BABYLON = {}));
  78643. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  78644. var BABYLON;
  78645. (function (BABYLON) {
  78646. /**
  78647. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  78648. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  78649. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  78650. */
  78651. var CustomProceduralTexture = /** @class */ (function (_super) {
  78652. __extends(CustomProceduralTexture, _super);
  78653. /**
  78654. * Instantiates a new Custom Procedural Texture.
  78655. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  78656. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  78657. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  78658. * @param name Define the name of the texture
  78659. * @param texturePath Define the folder path containing all the cutom texture related files (config, shaders...)
  78660. * @param size Define the size of the texture to create
  78661. * @param scene Define the scene the texture belongs to
  78662. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  78663. * @param generateMipMaps Define if the texture should creates mip maps or not
  78664. */
  78665. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  78666. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  78667. _this._animate = true;
  78668. _this._time = 0;
  78669. _this._texturePath = texturePath;
  78670. //Try to load json
  78671. _this._loadJson(texturePath);
  78672. _this.refreshRate = 1;
  78673. return _this;
  78674. }
  78675. CustomProceduralTexture.prototype._loadJson = function (jsonUrl) {
  78676. var _this = this;
  78677. var noConfigFile = function () {
  78678. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  78679. try {
  78680. _this.setFragment(_this._texturePath);
  78681. }
  78682. catch (ex) {
  78683. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  78684. }
  78685. };
  78686. var configFileUrl = jsonUrl + "/config.json";
  78687. var xhr = new XMLHttpRequest();
  78688. xhr.open("GET", configFileUrl, true);
  78689. xhr.addEventListener("load", function () {
  78690. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  78691. try {
  78692. _this._config = JSON.parse(xhr.response);
  78693. _this.updateShaderUniforms();
  78694. _this.updateTextures();
  78695. _this.setFragment(_this._texturePath + "/custom");
  78696. _this._animate = _this._config.animate;
  78697. _this.refreshRate = _this._config.refreshrate;
  78698. }
  78699. catch (ex) {
  78700. noConfigFile();
  78701. }
  78702. }
  78703. else {
  78704. noConfigFile();
  78705. }
  78706. }, false);
  78707. xhr.addEventListener("error", function () {
  78708. noConfigFile();
  78709. }, false);
  78710. try {
  78711. xhr.send();
  78712. }
  78713. catch (ex) {
  78714. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  78715. }
  78716. };
  78717. /**
  78718. * Is the texture ready to be used ? (rendered at least once)
  78719. * @returns true if ready, otherwise, false.
  78720. */
  78721. CustomProceduralTexture.prototype.isReady = function () {
  78722. if (!_super.prototype.isReady.call(this)) {
  78723. return false;
  78724. }
  78725. for (var name in this._textures) {
  78726. var texture = this._textures[name];
  78727. if (!texture.isReady()) {
  78728. return false;
  78729. }
  78730. }
  78731. return true;
  78732. };
  78733. /**
  78734. * Render the texture to its associated render target.
  78735. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  78736. */
  78737. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  78738. var scene = this.getScene();
  78739. if (this._animate && scene) {
  78740. this._time += scene.getAnimationRatio() * 0.03;
  78741. this.updateShaderUniforms();
  78742. }
  78743. _super.prototype.render.call(this, useCameraPostProcess);
  78744. };
  78745. /**
  78746. * Update the list of dependant textures samplers in the shader.
  78747. */
  78748. CustomProceduralTexture.prototype.updateTextures = function () {
  78749. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  78750. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  78751. }
  78752. };
  78753. /**
  78754. * Update the uniform values of the procedural texture in the shader.
  78755. */
  78756. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  78757. if (this._config) {
  78758. for (var j = 0; j < this._config.uniforms.length; j++) {
  78759. var uniform = this._config.uniforms[j];
  78760. switch (uniform.type) {
  78761. case "float":
  78762. this.setFloat(uniform.name, uniform.value);
  78763. break;
  78764. case "color3":
  78765. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  78766. break;
  78767. case "color4":
  78768. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  78769. break;
  78770. case "vector2":
  78771. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  78772. break;
  78773. case "vector3":
  78774. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  78775. break;
  78776. }
  78777. }
  78778. }
  78779. this.setFloat("time", this._time);
  78780. };
  78781. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  78782. /**
  78783. * Define if the texture animates or not.
  78784. */
  78785. get: function () {
  78786. return this._animate;
  78787. },
  78788. set: function (value) {
  78789. this._animate = value;
  78790. },
  78791. enumerable: true,
  78792. configurable: true
  78793. });
  78794. return CustomProceduralTexture;
  78795. }(BABYLON.ProceduralTexture));
  78796. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  78797. })(BABYLON || (BABYLON = {}));
  78798. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  78799. var BABYLON;
  78800. (function (BABYLON) {
  78801. /**
  78802. * Manage the gamepad inputs to control a free camera.
  78803. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  78804. */
  78805. var FreeCameraGamepadInput = /** @class */ (function () {
  78806. function FreeCameraGamepadInput() {
  78807. /**
  78808. * Defines the gamepad rotation sensiblity.
  78809. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  78810. */
  78811. this.gamepadAngularSensibility = 200;
  78812. /**
  78813. * Defines the gamepad move sensiblity.
  78814. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  78815. */
  78816. this.gamepadMoveSensibility = 40;
  78817. this._cameraTransform = BABYLON.Matrix.Identity();
  78818. this._deltaTransform = BABYLON.Vector3.Zero();
  78819. this._vector3 = BABYLON.Vector3.Zero();
  78820. this._vector2 = BABYLON.Vector2.Zero();
  78821. }
  78822. /**
  78823. * Attach the input controls to a specific dom element to get the input from.
  78824. * @param element Defines the element the controls should be listened from
  78825. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  78826. */
  78827. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  78828. var _this = this;
  78829. var manager = this.camera.getScene().gamepadManager;
  78830. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  78831. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  78832. // prioritize XBOX gamepads.
  78833. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  78834. _this.gamepad = gamepad;
  78835. }
  78836. }
  78837. });
  78838. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  78839. if (_this.gamepad === gamepad) {
  78840. _this.gamepad = null;
  78841. }
  78842. });
  78843. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  78844. };
  78845. /**
  78846. * Detach the current controls from the specified dom element.
  78847. * @param element Defines the element to stop listening the inputs from
  78848. */
  78849. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  78850. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  78851. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  78852. this.gamepad = null;
  78853. };
  78854. /**
  78855. * Update the current camera state depending on the inputs that have been used this frame.
  78856. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  78857. */
  78858. FreeCameraGamepadInput.prototype.checkInputs = function () {
  78859. if (this.gamepad && this.gamepad.leftStick) {
  78860. var camera = this.camera;
  78861. var LSValues = this.gamepad.leftStick;
  78862. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  78863. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  78864. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  78865. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  78866. var RSValues = this.gamepad.rightStick;
  78867. if (RSValues) {
  78868. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  78869. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  78870. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  78871. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  78872. }
  78873. else {
  78874. RSValues = { x: 0, y: 0 };
  78875. }
  78876. if (!camera.rotationQuaternion) {
  78877. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  78878. }
  78879. else {
  78880. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  78881. }
  78882. var speed = camera._computeLocalCameraSpeed() * 50.0;
  78883. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  78884. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  78885. camera.cameraDirection.addInPlace(this._deltaTransform);
  78886. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  78887. camera.cameraRotation.addInPlace(this._vector2);
  78888. }
  78889. };
  78890. /**
  78891. * Gets the class name of the current intput.
  78892. * @returns the class name
  78893. */
  78894. FreeCameraGamepadInput.prototype.getClassName = function () {
  78895. return "FreeCameraGamepadInput";
  78896. };
  78897. /**
  78898. * Get the friendly name associated with the input class.
  78899. * @returns the input friendly name
  78900. */
  78901. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  78902. return "gamepad";
  78903. };
  78904. __decorate([
  78905. BABYLON.serialize()
  78906. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  78907. __decorate([
  78908. BABYLON.serialize()
  78909. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  78910. return FreeCameraGamepadInput;
  78911. }());
  78912. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  78913. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  78914. })(BABYLON || (BABYLON = {}));
  78915. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  78916. var BABYLON;
  78917. (function (BABYLON) {
  78918. /**
  78919. * Manage the gamepad inputs to control an arc rotate camera.
  78920. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  78921. */
  78922. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  78923. function ArcRotateCameraGamepadInput() {
  78924. /**
  78925. * Defines the gamepad rotation sensiblity.
  78926. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  78927. */
  78928. this.gamepadRotationSensibility = 80;
  78929. /**
  78930. * Defines the gamepad move sensiblity.
  78931. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  78932. */
  78933. this.gamepadMoveSensibility = 40;
  78934. }
  78935. /**
  78936. * Attach the input controls to a specific dom element to get the input from.
  78937. * @param element Defines the element the controls should be listened from
  78938. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  78939. */
  78940. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  78941. var _this = this;
  78942. var manager = this.camera.getScene().gamepadManager;
  78943. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  78944. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  78945. // prioritize XBOX gamepads.
  78946. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  78947. _this.gamepad = gamepad;
  78948. }
  78949. }
  78950. });
  78951. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  78952. if (_this.gamepad === gamepad) {
  78953. _this.gamepad = null;
  78954. }
  78955. });
  78956. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  78957. };
  78958. /**
  78959. * Detach the current controls from the specified dom element.
  78960. * @param element Defines the element to stop listening the inputs from
  78961. */
  78962. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  78963. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  78964. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  78965. this.gamepad = null;
  78966. };
  78967. /**
  78968. * Update the current camera state depending on the inputs that have been used this frame.
  78969. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  78970. */
  78971. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  78972. if (this.gamepad) {
  78973. var camera = this.camera;
  78974. var RSValues = this.gamepad.rightStick;
  78975. if (RSValues) {
  78976. if (RSValues.x != 0) {
  78977. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  78978. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  78979. camera.inertialAlphaOffset += normalizedRX;
  78980. }
  78981. }
  78982. if (RSValues.y != 0) {
  78983. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  78984. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  78985. camera.inertialBetaOffset += normalizedRY;
  78986. }
  78987. }
  78988. }
  78989. var LSValues = this.gamepad.leftStick;
  78990. if (LSValues && LSValues.y != 0) {
  78991. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  78992. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  78993. this.camera.inertialRadiusOffset -= normalizedLY;
  78994. }
  78995. }
  78996. }
  78997. };
  78998. /**
  78999. * Gets the class name of the current intput.
  79000. * @returns the class name
  79001. */
  79002. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  79003. return "ArcRotateCameraGamepadInput";
  79004. };
  79005. /**
  79006. * Get the friendly name associated with the input class.
  79007. * @returns the input friendly name
  79008. */
  79009. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  79010. return "gamepad";
  79011. };
  79012. __decorate([
  79013. BABYLON.serialize()
  79014. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  79015. __decorate([
  79016. BABYLON.serialize()
  79017. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  79018. return ArcRotateCameraGamepadInput;
  79019. }());
  79020. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  79021. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  79022. })(BABYLON || (BABYLON = {}));
  79023. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  79024. var BABYLON;
  79025. (function (BABYLON) {
  79026. /**
  79027. * Manager for handling gamepads
  79028. */
  79029. var GamepadManager = /** @class */ (function () {
  79030. /**
  79031. * Initializes the gamepad manager
  79032. * @param _scene BabylonJS scene
  79033. */
  79034. function GamepadManager(_scene) {
  79035. var _this = this;
  79036. this._scene = _scene;
  79037. this._babylonGamepads = [];
  79038. this._oneGamepadConnected = false;
  79039. /** @hidden */
  79040. this._isMonitoring = false;
  79041. /**
  79042. * observable to be triggered when the gamepad controller has been disconnected
  79043. */
  79044. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  79045. if (!BABYLON.Tools.IsWindowObjectExist()) {
  79046. this._gamepadEventSupported = false;
  79047. }
  79048. else {
  79049. this._gamepadEventSupported = 'GamepadEvent' in window;
  79050. this._gamepadSupport = (navigator.getGamepads ||
  79051. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  79052. }
  79053. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  79054. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  79055. for (var i in _this._babylonGamepads) {
  79056. var gamepad = _this._babylonGamepads[i];
  79057. if (gamepad && gamepad._isConnected) {
  79058. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  79059. }
  79060. }
  79061. });
  79062. this._onGamepadConnectedEvent = function (evt) {
  79063. var gamepad = evt.gamepad;
  79064. if (gamepad.index in _this._babylonGamepads) {
  79065. if (_this._babylonGamepads[gamepad.index].isConnected) {
  79066. return;
  79067. }
  79068. }
  79069. var newGamepad;
  79070. if (_this._babylonGamepads[gamepad.index]) {
  79071. newGamepad = _this._babylonGamepads[gamepad.index];
  79072. newGamepad.browserGamepad = gamepad;
  79073. newGamepad._isConnected = true;
  79074. }
  79075. else {
  79076. newGamepad = _this._addNewGamepad(gamepad);
  79077. }
  79078. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  79079. _this._startMonitoringGamepads();
  79080. };
  79081. this._onGamepadDisconnectedEvent = function (evt) {
  79082. var gamepad = evt.gamepad;
  79083. // Remove the gamepad from the list of gamepads to monitor.
  79084. for (var i in _this._babylonGamepads) {
  79085. if (_this._babylonGamepads[i].index === gamepad.index) {
  79086. var disconnectedGamepad = _this._babylonGamepads[i];
  79087. disconnectedGamepad._isConnected = false;
  79088. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  79089. break;
  79090. }
  79091. }
  79092. };
  79093. if (this._gamepadSupport) {
  79094. //first add already-connected gamepads
  79095. this._updateGamepadObjects();
  79096. if (this._babylonGamepads.length) {
  79097. this._startMonitoringGamepads();
  79098. }
  79099. // Checking if the gamepad connected event is supported (like in Firefox)
  79100. if (this._gamepadEventSupported) {
  79101. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  79102. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  79103. }
  79104. else {
  79105. this._startMonitoringGamepads();
  79106. }
  79107. }
  79108. }
  79109. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  79110. /**
  79111. * The gamepads in the game pad manager
  79112. */
  79113. get: function () {
  79114. return this._babylonGamepads;
  79115. },
  79116. enumerable: true,
  79117. configurable: true
  79118. });
  79119. /**
  79120. * Get the gamepad controllers based on type
  79121. * @param type The type of gamepad controller
  79122. * @returns Nullable gamepad
  79123. */
  79124. GamepadManager.prototype.getGamepadByType = function (type) {
  79125. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  79126. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  79127. var gamepad = _a[_i];
  79128. if (gamepad && gamepad.type === type) {
  79129. return gamepad;
  79130. }
  79131. }
  79132. return null;
  79133. };
  79134. /**
  79135. * Disposes the gamepad manager
  79136. */
  79137. GamepadManager.prototype.dispose = function () {
  79138. if (this._gamepadEventSupported) {
  79139. if (this._onGamepadConnectedEvent) {
  79140. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  79141. }
  79142. if (this._onGamepadDisconnectedEvent) {
  79143. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  79144. }
  79145. this._onGamepadConnectedEvent = null;
  79146. this._onGamepadDisconnectedEvent = null;
  79147. }
  79148. this._babylonGamepads.forEach(function (gamepad) {
  79149. gamepad.dispose();
  79150. });
  79151. this.onGamepadConnectedObservable.clear();
  79152. this.onGamepadDisconnectedObservable.clear();
  79153. this._oneGamepadConnected = false;
  79154. this._stopMonitoringGamepads();
  79155. this._babylonGamepads = [];
  79156. };
  79157. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  79158. if (!this._oneGamepadConnected) {
  79159. this._oneGamepadConnected = true;
  79160. }
  79161. var newGamepad;
  79162. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  79163. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  79164. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  79165. }
  79166. // if pose is supported, use the (WebVR) pose enabled controller
  79167. else if (gamepad.pose) {
  79168. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  79169. }
  79170. else {
  79171. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  79172. }
  79173. this._babylonGamepads[newGamepad.index] = newGamepad;
  79174. return newGamepad;
  79175. };
  79176. GamepadManager.prototype._startMonitoringGamepads = function () {
  79177. if (!this._isMonitoring) {
  79178. this._isMonitoring = true;
  79179. //back-comp
  79180. if (!this._scene) {
  79181. this._checkGamepadsStatus();
  79182. }
  79183. }
  79184. };
  79185. GamepadManager.prototype._stopMonitoringGamepads = function () {
  79186. this._isMonitoring = false;
  79187. };
  79188. /** @hidden */
  79189. GamepadManager.prototype._checkGamepadsStatus = function () {
  79190. var _this = this;
  79191. // Hack to be compatible Chrome
  79192. this._updateGamepadObjects();
  79193. for (var i in this._babylonGamepads) {
  79194. var gamepad = this._babylonGamepads[i];
  79195. if (!gamepad || !gamepad.isConnected) {
  79196. continue;
  79197. }
  79198. gamepad.update();
  79199. }
  79200. if (this._isMonitoring && !this._scene) {
  79201. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  79202. }
  79203. };
  79204. // This function is called only on Chrome, which does not properly support
  79205. // connection/disconnection events and forces you to recopy again the gamepad object
  79206. GamepadManager.prototype._updateGamepadObjects = function () {
  79207. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  79208. for (var i = 0; i < gamepads.length; i++) {
  79209. var gamepad = gamepads[i];
  79210. if (gamepad) {
  79211. if (!this._babylonGamepads[gamepad.index]) {
  79212. var newGamepad = this._addNewGamepad(gamepad);
  79213. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  79214. }
  79215. else {
  79216. // Forced to copy again this object for Chrome for unknown reason
  79217. this._babylonGamepads[i].browserGamepad = gamepad;
  79218. if (!this._babylonGamepads[i].isConnected) {
  79219. this._babylonGamepads[i]._isConnected = true;
  79220. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  79221. }
  79222. }
  79223. }
  79224. }
  79225. };
  79226. return GamepadManager;
  79227. }());
  79228. BABYLON.GamepadManager = GamepadManager;
  79229. })(BABYLON || (BABYLON = {}));
  79230. //# sourceMappingURL=babylon.gamepadManager.js.map
  79231. var BABYLON;
  79232. (function (BABYLON) {
  79233. /**
  79234. * Represents a gamepad control stick position
  79235. */
  79236. var StickValues = /** @class */ (function () {
  79237. /**
  79238. * Initializes the gamepad x and y control stick values
  79239. * @param x The x component of the gamepad control stick value
  79240. * @param y The y component of the gamepad control stick value
  79241. */
  79242. function StickValues(
  79243. /**
  79244. * The x component of the control stick
  79245. */
  79246. x,
  79247. /**
  79248. * The y component of the control stick
  79249. */
  79250. y) {
  79251. this.x = x;
  79252. this.y = y;
  79253. }
  79254. return StickValues;
  79255. }());
  79256. BABYLON.StickValues = StickValues;
  79257. /**
  79258. * Represents a gamepad
  79259. */
  79260. var Gamepad = /** @class */ (function () {
  79261. /**
  79262. * Initializes the gamepad
  79263. * @param id The id of the gamepad
  79264. * @param index The index of the gamepad
  79265. * @param browserGamepad The browser gamepad
  79266. * @param leftStickX The x component of the left joystick
  79267. * @param leftStickY The y component of the left joystick
  79268. * @param rightStickX The x component of the right joystick
  79269. * @param rightStickY The y component of the right joystick
  79270. */
  79271. function Gamepad(
  79272. /**
  79273. * The id of the gamepad
  79274. */
  79275. id,
  79276. /**
  79277. * The index of the gamepad
  79278. */
  79279. index,
  79280. /**
  79281. * The browser gamepad
  79282. */
  79283. browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  79284. if (leftStickX === void 0) { leftStickX = 0; }
  79285. if (leftStickY === void 0) { leftStickY = 1; }
  79286. if (rightStickX === void 0) { rightStickX = 2; }
  79287. if (rightStickY === void 0) { rightStickY = 3; }
  79288. this.id = id;
  79289. this.index = index;
  79290. this.browserGamepad = browserGamepad;
  79291. this._leftStick = { x: 0, y: 0 };
  79292. this._rightStick = { x: 0, y: 0 };
  79293. /** @hidden */
  79294. this._isConnected = true;
  79295. /**
  79296. * Specifies whether the left control stick should be Y-inverted
  79297. */
  79298. this._invertLeftStickY = false;
  79299. this.type = Gamepad.GAMEPAD;
  79300. this._leftStickAxisX = leftStickX;
  79301. this._leftStickAxisY = leftStickY;
  79302. this._rightStickAxisX = rightStickX;
  79303. this._rightStickAxisY = rightStickY;
  79304. if (this.browserGamepad.axes.length >= 2) {
  79305. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  79306. }
  79307. if (this.browserGamepad.axes.length >= 4) {
  79308. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  79309. }
  79310. }
  79311. Object.defineProperty(Gamepad.prototype, "isConnected", {
  79312. /**
  79313. * Specifies if the gamepad has been connected
  79314. */
  79315. get: function () {
  79316. return this._isConnected;
  79317. },
  79318. enumerable: true,
  79319. configurable: true
  79320. });
  79321. /**
  79322. * Callback triggered when the left joystick has changed
  79323. * @param callback
  79324. */
  79325. Gamepad.prototype.onleftstickchanged = function (callback) {
  79326. this._onleftstickchanged = callback;
  79327. };
  79328. /**
  79329. * Callback triggered when the right joystick has changed
  79330. * @param callback
  79331. */
  79332. Gamepad.prototype.onrightstickchanged = function (callback) {
  79333. this._onrightstickchanged = callback;
  79334. };
  79335. Object.defineProperty(Gamepad.prototype, "leftStick", {
  79336. /**
  79337. * Gets the left joystick
  79338. */
  79339. get: function () {
  79340. return this._leftStick;
  79341. },
  79342. /**
  79343. * Sets the left joystick values
  79344. */
  79345. set: function (newValues) {
  79346. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  79347. this._onleftstickchanged(newValues);
  79348. }
  79349. this._leftStick = newValues;
  79350. },
  79351. enumerable: true,
  79352. configurable: true
  79353. });
  79354. Object.defineProperty(Gamepad.prototype, "rightStick", {
  79355. /**
  79356. * Gets the right joystick
  79357. */
  79358. get: function () {
  79359. return this._rightStick;
  79360. },
  79361. /**
  79362. * Sets the right joystick value
  79363. */
  79364. set: function (newValues) {
  79365. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  79366. this._onrightstickchanged(newValues);
  79367. }
  79368. this._rightStick = newValues;
  79369. },
  79370. enumerable: true,
  79371. configurable: true
  79372. });
  79373. /**
  79374. * Updates the gamepad joystick positions
  79375. */
  79376. Gamepad.prototype.update = function () {
  79377. if (this._leftStick) {
  79378. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  79379. if (this._invertLeftStickY) {
  79380. this.leftStick.y *= -1;
  79381. }
  79382. }
  79383. if (this._rightStick) {
  79384. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  79385. }
  79386. };
  79387. /**
  79388. * Disposes the gamepad
  79389. */
  79390. Gamepad.prototype.dispose = function () {
  79391. };
  79392. /**
  79393. * Represents a gamepad controller
  79394. */
  79395. Gamepad.GAMEPAD = 0;
  79396. /**
  79397. * Represents a generic controller
  79398. */
  79399. Gamepad.GENERIC = 1;
  79400. /**
  79401. * Represents an XBox controller
  79402. */
  79403. Gamepad.XBOX = 2;
  79404. /**
  79405. * Represents a pose-enabled controller
  79406. */
  79407. Gamepad.POSE_ENABLED = 3;
  79408. return Gamepad;
  79409. }());
  79410. BABYLON.Gamepad = Gamepad;
  79411. /**
  79412. * Represents a generic gamepad
  79413. */
  79414. var GenericPad = /** @class */ (function (_super) {
  79415. __extends(GenericPad, _super);
  79416. /**
  79417. * Initializes the generic gamepad
  79418. * @param id The id of the generic gamepad
  79419. * @param index The index of the generic gamepad
  79420. * @param browserGamepad The browser gamepad
  79421. */
  79422. function GenericPad(id, index, browserGamepad) {
  79423. var _this = _super.call(this, id, index, browserGamepad) || this;
  79424. /**
  79425. * Observable triggered when a button has been pressed
  79426. */
  79427. _this.onButtonDownObservable = new BABYLON.Observable();
  79428. /**
  79429. * Observable triggered when a button has been released
  79430. */
  79431. _this.onButtonUpObservable = new BABYLON.Observable();
  79432. _this.type = Gamepad.GENERIC;
  79433. _this._buttons = new Array(browserGamepad.buttons.length);
  79434. return _this;
  79435. }
  79436. /**
  79437. * Callback triggered when a button has been pressed
  79438. * @param callback Called when a button has been pressed
  79439. */
  79440. GenericPad.prototype.onbuttondown = function (callback) {
  79441. this._onbuttondown = callback;
  79442. };
  79443. /**
  79444. * Callback triggered when a button has been released
  79445. * @param callback Called when a button has been released
  79446. */
  79447. GenericPad.prototype.onbuttonup = function (callback) {
  79448. this._onbuttonup = callback;
  79449. };
  79450. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  79451. if (newValue !== currentValue) {
  79452. if (newValue === 1) {
  79453. if (this._onbuttondown) {
  79454. this._onbuttondown(buttonIndex);
  79455. }
  79456. this.onButtonDownObservable.notifyObservers(buttonIndex);
  79457. }
  79458. if (newValue === 0) {
  79459. if (this._onbuttonup) {
  79460. this._onbuttonup(buttonIndex);
  79461. }
  79462. this.onButtonUpObservable.notifyObservers(buttonIndex);
  79463. }
  79464. }
  79465. return newValue;
  79466. };
  79467. /**
  79468. * Updates the generic gamepad
  79469. */
  79470. GenericPad.prototype.update = function () {
  79471. _super.prototype.update.call(this);
  79472. for (var index = 0; index < this._buttons.length; index++) {
  79473. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  79474. }
  79475. };
  79476. /**
  79477. * Disposes the generic gamepad
  79478. */
  79479. GenericPad.prototype.dispose = function () {
  79480. _super.prototype.dispose.call(this);
  79481. this.onButtonDownObservable.clear();
  79482. this.onButtonUpObservable.clear();
  79483. };
  79484. return GenericPad;
  79485. }(Gamepad));
  79486. BABYLON.GenericPad = GenericPad;
  79487. })(BABYLON || (BABYLON = {}));
  79488. //# sourceMappingURL=babylon.gamepad.js.map
  79489. var BABYLON;
  79490. (function (BABYLON) {
  79491. /**
  79492. * Defines supported buttons for XBox360 compatible gamepads
  79493. */
  79494. var Xbox360Button;
  79495. (function (Xbox360Button) {
  79496. /** A */
  79497. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  79498. /** B */
  79499. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  79500. /** X */
  79501. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  79502. /** Y */
  79503. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  79504. /** Start */
  79505. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  79506. /** Back */
  79507. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  79508. /** Left button */
  79509. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  79510. /** Right button */
  79511. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  79512. /** Left stick */
  79513. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  79514. /** Right stick */
  79515. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  79516. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  79517. /** Defines values for XBox360 DPad */
  79518. var Xbox360Dpad;
  79519. (function (Xbox360Dpad) {
  79520. /** Up */
  79521. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  79522. /** Down */
  79523. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  79524. /** Left */
  79525. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  79526. /** Right */
  79527. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  79528. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  79529. /**
  79530. * Defines a XBox360 gamepad
  79531. */
  79532. var Xbox360Pad = /** @class */ (function (_super) {
  79533. __extends(Xbox360Pad, _super);
  79534. /**
  79535. * Creates a new XBox360 gamepad object
  79536. * @param id defines the id of this gamepad
  79537. * @param index defines its index
  79538. * @param gamepad defines the internal HTML gamepad object
  79539. * @param xboxOne defines if it is a XBox One gamepad
  79540. */
  79541. function Xbox360Pad(id, index, gamepad, xboxOne) {
  79542. if (xboxOne === void 0) { xboxOne = false; }
  79543. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  79544. _this._leftTrigger = 0;
  79545. _this._rightTrigger = 0;
  79546. /** Observable raised when a button is pressed */
  79547. _this.onButtonDownObservable = new BABYLON.Observable();
  79548. /** Observable raised when a button is released */
  79549. _this.onButtonUpObservable = new BABYLON.Observable();
  79550. /** Observable raised when a pad is pressed */
  79551. _this.onPadDownObservable = new BABYLON.Observable();
  79552. /** Observable raised when a pad is released */
  79553. _this.onPadUpObservable = new BABYLON.Observable();
  79554. _this._buttonA = 0;
  79555. _this._buttonB = 0;
  79556. _this._buttonX = 0;
  79557. _this._buttonY = 0;
  79558. _this._buttonBack = 0;
  79559. _this._buttonStart = 0;
  79560. _this._buttonLB = 0;
  79561. _this._buttonRB = 0;
  79562. _this._buttonLeftStick = 0;
  79563. _this._buttonRightStick = 0;
  79564. _this._dPadUp = 0;
  79565. _this._dPadDown = 0;
  79566. _this._dPadLeft = 0;
  79567. _this._dPadRight = 0;
  79568. _this._isXboxOnePad = false;
  79569. _this.type = BABYLON.Gamepad.XBOX;
  79570. _this._isXboxOnePad = xboxOne;
  79571. return _this;
  79572. }
  79573. /**
  79574. * Defines the callback to call when left trigger is pressed
  79575. * @param callback defines the callback to use
  79576. */
  79577. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  79578. this._onlefttriggerchanged = callback;
  79579. };
  79580. /**
  79581. * Defines the callback to call when right trigger is pressed
  79582. * @param callback defines the callback to use
  79583. */
  79584. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  79585. this._onrighttriggerchanged = callback;
  79586. };
  79587. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  79588. /**
  79589. * Gets the left trigger value
  79590. */
  79591. get: function () {
  79592. return this._leftTrigger;
  79593. },
  79594. /**
  79595. * Sets the left trigger value
  79596. */
  79597. set: function (newValue) {
  79598. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  79599. this._onlefttriggerchanged(newValue);
  79600. }
  79601. this._leftTrigger = newValue;
  79602. },
  79603. enumerable: true,
  79604. configurable: true
  79605. });
  79606. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  79607. /**
  79608. * Gets the right trigger value
  79609. */
  79610. get: function () {
  79611. return this._rightTrigger;
  79612. },
  79613. /**
  79614. * Sets the right trigger value
  79615. */
  79616. set: function (newValue) {
  79617. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  79618. this._onrighttriggerchanged(newValue);
  79619. }
  79620. this._rightTrigger = newValue;
  79621. },
  79622. enumerable: true,
  79623. configurable: true
  79624. });
  79625. /**
  79626. * Defines the callback to call when a button is pressed
  79627. * @param callback defines the callback to use
  79628. */
  79629. Xbox360Pad.prototype.onbuttondown = function (callback) {
  79630. this._onbuttondown = callback;
  79631. };
  79632. /**
  79633. * Defines the callback to call when a button is released
  79634. * @param callback defines the callback to use
  79635. */
  79636. Xbox360Pad.prototype.onbuttonup = function (callback) {
  79637. this._onbuttonup = callback;
  79638. };
  79639. /**
  79640. * Defines the callback to call when a pad is pressed
  79641. * @param callback defines the callback to use
  79642. */
  79643. Xbox360Pad.prototype.ondpaddown = function (callback) {
  79644. this._ondpaddown = callback;
  79645. };
  79646. /**
  79647. * Defines the callback to call when a pad is released
  79648. * @param callback defines the callback to use
  79649. */
  79650. Xbox360Pad.prototype.ondpadup = function (callback) {
  79651. this._ondpadup = callback;
  79652. };
  79653. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  79654. if (newValue !== currentValue) {
  79655. if (newValue === 1) {
  79656. if (this._onbuttondown) {
  79657. this._onbuttondown(buttonType);
  79658. }
  79659. this.onButtonDownObservable.notifyObservers(buttonType);
  79660. }
  79661. if (newValue === 0) {
  79662. if (this._onbuttonup) {
  79663. this._onbuttonup(buttonType);
  79664. }
  79665. this.onButtonUpObservable.notifyObservers(buttonType);
  79666. }
  79667. }
  79668. return newValue;
  79669. };
  79670. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  79671. if (newValue !== currentValue) {
  79672. if (newValue === 1) {
  79673. if (this._ondpaddown) {
  79674. this._ondpaddown(buttonType);
  79675. }
  79676. this.onPadDownObservable.notifyObservers(buttonType);
  79677. }
  79678. if (newValue === 0) {
  79679. if (this._ondpadup) {
  79680. this._ondpadup(buttonType);
  79681. }
  79682. this.onPadUpObservable.notifyObservers(buttonType);
  79683. }
  79684. }
  79685. return newValue;
  79686. };
  79687. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  79688. /**
  79689. * Gets the value of the `A` button
  79690. */
  79691. get: function () {
  79692. return this._buttonA;
  79693. },
  79694. /**
  79695. * Sets the value of the `A` button
  79696. */
  79697. set: function (value) {
  79698. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  79699. },
  79700. enumerable: true,
  79701. configurable: true
  79702. });
  79703. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  79704. /**
  79705. * Gets the value of the `B` button
  79706. */
  79707. get: function () {
  79708. return this._buttonB;
  79709. },
  79710. /**
  79711. * Sets the value of the `B` button
  79712. */
  79713. set: function (value) {
  79714. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  79715. },
  79716. enumerable: true,
  79717. configurable: true
  79718. });
  79719. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  79720. /**
  79721. * Gets the value of the `X` button
  79722. */
  79723. get: function () {
  79724. return this._buttonX;
  79725. },
  79726. /**
  79727. * Sets the value of the `X` button
  79728. */
  79729. set: function (value) {
  79730. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  79731. },
  79732. enumerable: true,
  79733. configurable: true
  79734. });
  79735. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  79736. /**
  79737. * Gets the value of the `Y` button
  79738. */
  79739. get: function () {
  79740. return this._buttonY;
  79741. },
  79742. /**
  79743. * Sets the value of the `Y` button
  79744. */
  79745. set: function (value) {
  79746. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  79747. },
  79748. enumerable: true,
  79749. configurable: true
  79750. });
  79751. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  79752. /**
  79753. * Gets the value of the `Start` button
  79754. */
  79755. get: function () {
  79756. return this._buttonStart;
  79757. },
  79758. /**
  79759. * Sets the value of the `Start` button
  79760. */
  79761. set: function (value) {
  79762. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  79763. },
  79764. enumerable: true,
  79765. configurable: true
  79766. });
  79767. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  79768. /**
  79769. * Gets the value of the `Back` button
  79770. */
  79771. get: function () {
  79772. return this._buttonBack;
  79773. },
  79774. /**
  79775. * Sets the value of the `Back` button
  79776. */
  79777. set: function (value) {
  79778. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  79779. },
  79780. enumerable: true,
  79781. configurable: true
  79782. });
  79783. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  79784. /**
  79785. * Gets the value of the `Left` button
  79786. */
  79787. get: function () {
  79788. return this._buttonLB;
  79789. },
  79790. /**
  79791. * Sets the value of the `Left` button
  79792. */
  79793. set: function (value) {
  79794. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  79795. },
  79796. enumerable: true,
  79797. configurable: true
  79798. });
  79799. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  79800. /**
  79801. * Gets the value of the `Right` button
  79802. */
  79803. get: function () {
  79804. return this._buttonRB;
  79805. },
  79806. /**
  79807. * Sets the value of the `Right` button
  79808. */
  79809. set: function (value) {
  79810. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  79811. },
  79812. enumerable: true,
  79813. configurable: true
  79814. });
  79815. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  79816. /**
  79817. * Gets the value of the Left joystick
  79818. */
  79819. get: function () {
  79820. return this._buttonLeftStick;
  79821. },
  79822. /**
  79823. * Sets the value of the Left joystick
  79824. */
  79825. set: function (value) {
  79826. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  79827. },
  79828. enumerable: true,
  79829. configurable: true
  79830. });
  79831. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  79832. /**
  79833. * Gets the value of the Right joystick
  79834. */
  79835. get: function () {
  79836. return this._buttonRightStick;
  79837. },
  79838. /**
  79839. * Sets the value of the Right joystick
  79840. */
  79841. set: function (value) {
  79842. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  79843. },
  79844. enumerable: true,
  79845. configurable: true
  79846. });
  79847. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  79848. /**
  79849. * Gets the value of D-pad up
  79850. */
  79851. get: function () {
  79852. return this._dPadUp;
  79853. },
  79854. /**
  79855. * Sets the value of D-pad up
  79856. */
  79857. set: function (value) {
  79858. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  79859. },
  79860. enumerable: true,
  79861. configurable: true
  79862. });
  79863. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  79864. /**
  79865. * Gets the value of D-pad down
  79866. */
  79867. get: function () {
  79868. return this._dPadDown;
  79869. },
  79870. /**
  79871. * Sets the value of D-pad down
  79872. */
  79873. set: function (value) {
  79874. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  79875. },
  79876. enumerable: true,
  79877. configurable: true
  79878. });
  79879. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  79880. /**
  79881. * Gets the value of D-pad left
  79882. */
  79883. get: function () {
  79884. return this._dPadLeft;
  79885. },
  79886. /**
  79887. * Sets the value of D-pad left
  79888. */
  79889. set: function (value) {
  79890. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  79891. },
  79892. enumerable: true,
  79893. configurable: true
  79894. });
  79895. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  79896. /**
  79897. * Gets the value of D-pad right
  79898. */
  79899. get: function () {
  79900. return this._dPadRight;
  79901. },
  79902. /**
  79903. * Sets the value of D-pad right
  79904. */
  79905. set: function (value) {
  79906. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  79907. },
  79908. enumerable: true,
  79909. configurable: true
  79910. });
  79911. /**
  79912. * Force the gamepad to synchronize with device values
  79913. */
  79914. Xbox360Pad.prototype.update = function () {
  79915. _super.prototype.update.call(this);
  79916. if (this._isXboxOnePad) {
  79917. this.buttonA = this.browserGamepad.buttons[0].value;
  79918. this.buttonB = this.browserGamepad.buttons[1].value;
  79919. this.buttonX = this.browserGamepad.buttons[2].value;
  79920. this.buttonY = this.browserGamepad.buttons[3].value;
  79921. this.buttonLB = this.browserGamepad.buttons[4].value;
  79922. this.buttonRB = this.browserGamepad.buttons[5].value;
  79923. this.leftTrigger = this.browserGamepad.axes[2];
  79924. this.rightTrigger = this.browserGamepad.axes[5];
  79925. this.buttonBack = this.browserGamepad.buttons[9].value;
  79926. this.buttonStart = this.browserGamepad.buttons[8].value;
  79927. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  79928. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  79929. this.dPadUp = this.browserGamepad.buttons[11].value;
  79930. this.dPadDown = this.browserGamepad.buttons[12].value;
  79931. this.dPadLeft = this.browserGamepad.buttons[13].value;
  79932. this.dPadRight = this.browserGamepad.buttons[14].value;
  79933. }
  79934. else {
  79935. this.buttonA = this.browserGamepad.buttons[0].value;
  79936. this.buttonB = this.browserGamepad.buttons[1].value;
  79937. this.buttonX = this.browserGamepad.buttons[2].value;
  79938. this.buttonY = this.browserGamepad.buttons[3].value;
  79939. this.buttonLB = this.browserGamepad.buttons[4].value;
  79940. this.buttonRB = this.browserGamepad.buttons[5].value;
  79941. this.leftTrigger = this.browserGamepad.buttons[6].value;
  79942. this.rightTrigger = this.browserGamepad.buttons[7].value;
  79943. this.buttonBack = this.browserGamepad.buttons[8].value;
  79944. this.buttonStart = this.browserGamepad.buttons[9].value;
  79945. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  79946. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  79947. this.dPadUp = this.browserGamepad.buttons[12].value;
  79948. this.dPadDown = this.browserGamepad.buttons[13].value;
  79949. this.dPadLeft = this.browserGamepad.buttons[14].value;
  79950. this.dPadRight = this.browserGamepad.buttons[15].value;
  79951. }
  79952. };
  79953. /**
  79954. * Disposes the gamepad
  79955. */
  79956. Xbox360Pad.prototype.dispose = function () {
  79957. _super.prototype.dispose.call(this);
  79958. this.onButtonDownObservable.clear();
  79959. this.onButtonUpObservable.clear();
  79960. this.onPadDownObservable.clear();
  79961. this.onPadUpObservable.clear();
  79962. };
  79963. return Xbox360Pad;
  79964. }(BABYLON.Gamepad));
  79965. BABYLON.Xbox360Pad = Xbox360Pad;
  79966. })(BABYLON || (BABYLON = {}));
  79967. //# sourceMappingURL=babylon.xboxGamepad.js.map
  79968. var BABYLON;
  79969. (function (BABYLON) {
  79970. /**
  79971. * Defines the types of pose enabled controllers that are supported
  79972. */
  79973. var PoseEnabledControllerType;
  79974. (function (PoseEnabledControllerType) {
  79975. /**
  79976. * HTC Vive
  79977. */
  79978. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  79979. /**
  79980. * Oculus Rift
  79981. */
  79982. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  79983. /**
  79984. * Windows mixed reality
  79985. */
  79986. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  79987. /**
  79988. * Samsung gear VR
  79989. */
  79990. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  79991. /**
  79992. * Google Daydream
  79993. */
  79994. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  79995. /**
  79996. * Generic
  79997. */
  79998. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  79999. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  80000. /**
  80001. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  80002. */
  80003. var PoseEnabledControllerHelper = /** @class */ (function () {
  80004. function PoseEnabledControllerHelper() {
  80005. }
  80006. /**
  80007. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  80008. * @param vrGamepad the gamepad to initialized
  80009. * @returns a vr controller of the type the gamepad identified as
  80010. */
  80011. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  80012. // Oculus Touch
  80013. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  80014. return new BABYLON.OculusTouchController(vrGamepad);
  80015. }
  80016. // Windows Mixed Reality controllers
  80017. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  80018. return new BABYLON.WindowsMotionController(vrGamepad);
  80019. }
  80020. // HTC Vive
  80021. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  80022. return new BABYLON.ViveController(vrGamepad);
  80023. }
  80024. // Samsung/Oculus Gear VR or Oculus Go
  80025. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  80026. return new BABYLON.GearVRController(vrGamepad);
  80027. }
  80028. // Google Daydream
  80029. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  80030. return new BABYLON.DaydreamController(vrGamepad);
  80031. }
  80032. // Generic
  80033. else {
  80034. return new BABYLON.GenericController(vrGamepad);
  80035. }
  80036. };
  80037. return PoseEnabledControllerHelper;
  80038. }());
  80039. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  80040. /**
  80041. * Defines the PoseEnabledController object that contains state of a vr capable controller
  80042. */
  80043. var PoseEnabledController = /** @class */ (function (_super) {
  80044. __extends(PoseEnabledController, _super);
  80045. /**
  80046. * Creates a new PoseEnabledController from a gamepad
  80047. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  80048. */
  80049. function PoseEnabledController(browserGamepad) {
  80050. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  80051. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  80052. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  80053. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  80054. /**
  80055. * The device position in babylon space
  80056. */
  80057. _this.devicePosition = BABYLON.Vector3.Zero();
  80058. /**
  80059. * The device rotation in babylon space
  80060. */
  80061. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  80062. /**
  80063. * The scale factor of the device in babylon space
  80064. */
  80065. _this.deviceScaleFactor = 1;
  80066. // Used to convert 6dof controllers to 3dof
  80067. _this._trackPosition = true;
  80068. _this._maxRotationDistFromHeadset = Math.PI / 5;
  80069. _this._draggedRoomRotation = 0;
  80070. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  80071. /**
  80072. * Internal, matrix used to convert room space to babylon space
  80073. * @hidden
  80074. */
  80075. _this._deviceToWorld = BABYLON.Matrix.Identity();
  80076. /**
  80077. * Node to be used when casting a ray from the controller
  80078. * @hidden
  80079. */
  80080. _this._pointingPoseNode = null;
  80081. _this._workingMatrix = BABYLON.Matrix.Identity();
  80082. /**
  80083. * @hidden
  80084. */
  80085. _this._meshAttachedObservable = new BABYLON.Observable();
  80086. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  80087. _this.controllerType = PoseEnabledControllerType.GENERIC;
  80088. _this.position = BABYLON.Vector3.Zero();
  80089. _this.rotationQuaternion = new BABYLON.Quaternion();
  80090. _this._calculatedPosition = BABYLON.Vector3.Zero();
  80091. _this._calculatedRotation = new BABYLON.Quaternion();
  80092. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  80093. return _this;
  80094. }
  80095. /**
  80096. * @hidden
  80097. */
  80098. PoseEnabledController.prototype._disableTrackPosition = function (fixedPosition) {
  80099. if (this._trackPosition) {
  80100. this._calculatedPosition.copyFrom(fixedPosition);
  80101. this._trackPosition = false;
  80102. }
  80103. };
  80104. /**
  80105. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  80106. */
  80107. PoseEnabledController.prototype.update = function () {
  80108. _super.prototype.update.call(this);
  80109. this._updatePoseAndMesh();
  80110. };
  80111. /**
  80112. * Updates only the pose device and mesh without doing any button event checking
  80113. */
  80114. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  80115. var pose = this.browserGamepad.pose;
  80116. this.updateFromDevice(pose);
  80117. if (!this._trackPosition && BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera && BABYLON.Engine.LastCreatedScene.activeCamera.devicePosition) {
  80118. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  80119. camera._computeDevicePosition();
  80120. this._deviceToWorld.setTranslation(camera.devicePosition);
  80121. if (camera.deviceRotationQuaternion) {
  80122. var camera = camera;
  80123. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(BABYLON.Tmp.Vector3[0]);
  80124. // Find the radian distance away that the headset is from the controllers rotation
  80125. var distanceAway = Math.atan2(Math.sin(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation), Math.cos(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation));
  80126. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  80127. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  80128. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  80129. this._draggedRoomRotation += rotationAmount;
  80130. // Rotate controller around headset
  80131. var sin = Math.sin(-rotationAmount);
  80132. var cos = Math.cos(-rotationAmount);
  80133. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  80134. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  80135. }
  80136. }
  80137. }
  80138. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  80139. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  80140. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  80141. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  80142. if (this._mesh) {
  80143. this._mesh.position.copyFrom(this.devicePosition);
  80144. if (this._mesh.rotationQuaternion) {
  80145. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  80146. }
  80147. }
  80148. };
  80149. /**
  80150. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  80151. * @param poseData raw pose fromthe device
  80152. */
  80153. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  80154. if (poseData) {
  80155. this.rawPose = poseData;
  80156. if (poseData.position) {
  80157. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  80158. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  80159. this._deviceRoomPosition.z *= -1;
  80160. }
  80161. if (this._trackPosition) {
  80162. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  80163. }
  80164. this._calculatedPosition.addInPlace(this.position);
  80165. }
  80166. var pose = this.rawPose;
  80167. if (poseData.orientation && pose.orientation) {
  80168. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  80169. if (this._mesh) {
  80170. if (this._mesh.getScene().useRightHandedSystem) {
  80171. this._deviceRoomRotationQuaternion.z *= -1;
  80172. this._deviceRoomRotationQuaternion.w *= -1;
  80173. }
  80174. else {
  80175. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  80176. }
  80177. }
  80178. // if the camera is set, rotate to the camera's rotation
  80179. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  80180. }
  80181. }
  80182. };
  80183. /**
  80184. * Attaches a mesh to the controller
  80185. * @param mesh the mesh to be attached
  80186. */
  80187. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  80188. if (this._mesh) {
  80189. this._mesh.parent = null;
  80190. }
  80191. this._mesh = mesh;
  80192. if (this._poseControlledCamera) {
  80193. this._mesh.parent = this._poseControlledCamera;
  80194. }
  80195. if (!this._mesh.rotationQuaternion) {
  80196. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  80197. }
  80198. // 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
  80199. this._updatePoseAndMesh();
  80200. if (this._pointingPoseNode) {
  80201. var parents = [];
  80202. var obj = this._pointingPoseNode;
  80203. while (obj.parent) {
  80204. parents.push(obj.parent);
  80205. obj = obj.parent;
  80206. }
  80207. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  80208. }
  80209. this._meshAttachedObservable.notifyObservers(mesh);
  80210. };
  80211. /**
  80212. * Attaches the controllers mesh to a camera
  80213. * @param camera the camera the mesh should be attached to
  80214. */
  80215. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  80216. this._poseControlledCamera = camera;
  80217. if (this._mesh) {
  80218. this._mesh.parent = this._poseControlledCamera;
  80219. }
  80220. };
  80221. /**
  80222. * Disposes of the controller
  80223. */
  80224. PoseEnabledController.prototype.dispose = function () {
  80225. if (this._mesh) {
  80226. this._mesh.dispose();
  80227. }
  80228. this._mesh = null;
  80229. _super.prototype.dispose.call(this);
  80230. };
  80231. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  80232. /**
  80233. * The mesh that is attached to the controller
  80234. */
  80235. get: function () {
  80236. return this._mesh;
  80237. },
  80238. enumerable: true,
  80239. configurable: true
  80240. });
  80241. /**
  80242. * Gets the ray of the controller in the direction the controller is pointing
  80243. * @param length the length the resulting ray should be
  80244. * @returns a ray in the direction the controller is pointing
  80245. */
  80246. PoseEnabledController.prototype.getForwardRay = function (length) {
  80247. if (length === void 0) { length = 100; }
  80248. if (!this.mesh) {
  80249. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  80250. }
  80251. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  80252. var origin = m.getTranslation();
  80253. var forward = new BABYLON.Vector3(0, 0, -1);
  80254. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  80255. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  80256. return new BABYLON.Ray(origin, direction, length);
  80257. };
  80258. /**
  80259. * Name of the child mesh that can be used to cast a ray from the controller
  80260. */
  80261. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  80262. return PoseEnabledController;
  80263. }(BABYLON.Gamepad));
  80264. BABYLON.PoseEnabledController = PoseEnabledController;
  80265. })(BABYLON || (BABYLON = {}));
  80266. //# sourceMappingURL=babylon.poseEnabledController.js.map
  80267. var BABYLON;
  80268. (function (BABYLON) {
  80269. /**
  80270. * Defines the WebVRController object that represents controllers tracked in 3D space
  80271. */
  80272. var WebVRController = /** @class */ (function (_super) {
  80273. __extends(WebVRController, _super);
  80274. /**
  80275. * Creates a new WebVRController from a gamepad
  80276. * @param vrGamepad the gamepad that the WebVRController should be created from
  80277. */
  80278. function WebVRController(vrGamepad) {
  80279. var _this = _super.call(this, vrGamepad) || this;
  80280. // Observables
  80281. /**
  80282. * Fired when the trigger state has changed
  80283. */
  80284. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  80285. /**
  80286. * Fired when the main button state has changed
  80287. */
  80288. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  80289. /**
  80290. * Fired when the secondary button state has changed
  80291. */
  80292. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  80293. /**
  80294. * Fired when the pad state has changed
  80295. */
  80296. _this.onPadStateChangedObservable = new BABYLON.Observable();
  80297. /**
  80298. * Fired when controllers stick values have changed
  80299. */
  80300. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  80301. /**
  80302. * X and Y axis corrisponding to the controllers joystick
  80303. */
  80304. _this.pad = { x: 0, y: 0 };
  80305. // avoid GC, store state in a tmp object
  80306. _this._changes = {
  80307. pressChanged: false,
  80308. touchChanged: false,
  80309. valueChanged: false,
  80310. changed: false
  80311. };
  80312. _this._buttons = new Array(vrGamepad.buttons.length);
  80313. _this.hand = vrGamepad.hand;
  80314. return _this;
  80315. }
  80316. /**
  80317. * Fired when a controller button's state has changed
  80318. * @param callback the callback containing the button that was modified
  80319. */
  80320. WebVRController.prototype.onButtonStateChange = function (callback) {
  80321. this._onButtonStateChange = callback;
  80322. };
  80323. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  80324. /**
  80325. * The default controller model for the controller
  80326. */
  80327. get: function () {
  80328. return this._defaultModel;
  80329. },
  80330. enumerable: true,
  80331. configurable: true
  80332. });
  80333. /**
  80334. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  80335. */
  80336. WebVRController.prototype.update = function () {
  80337. _super.prototype.update.call(this);
  80338. for (var index = 0; index < this._buttons.length; index++) {
  80339. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  80340. }
  80341. ;
  80342. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  80343. this.pad.x = this.leftStick.x;
  80344. this.pad.y = this.leftStick.y;
  80345. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  80346. }
  80347. };
  80348. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  80349. if (!newState) {
  80350. newState = {
  80351. pressed: false,
  80352. touched: false,
  80353. value: 0
  80354. };
  80355. }
  80356. if (!currentState) {
  80357. this._buttons[buttonIndex] = {
  80358. pressed: newState.pressed,
  80359. touched: newState.touched,
  80360. value: newState.value
  80361. };
  80362. return;
  80363. }
  80364. this._checkChanges(newState, currentState);
  80365. if (this._changes.changed) {
  80366. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  80367. this._handleButtonChange(buttonIndex, newState, this._changes);
  80368. }
  80369. this._buttons[buttonIndex].pressed = newState.pressed;
  80370. this._buttons[buttonIndex].touched = newState.touched;
  80371. // oculus triggers are never 0, thou not touched.
  80372. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  80373. };
  80374. WebVRController.prototype._checkChanges = function (newState, currentState) {
  80375. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  80376. this._changes.touchChanged = newState.touched !== currentState.touched;
  80377. this._changes.valueChanged = newState.value !== currentState.value;
  80378. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  80379. return this._changes;
  80380. };
  80381. /**
  80382. * Disposes of th webVRCOntroller
  80383. */
  80384. WebVRController.prototype.dispose = function () {
  80385. _super.prototype.dispose.call(this);
  80386. this.onTriggerStateChangedObservable.clear();
  80387. this.onMainButtonStateChangedObservable.clear();
  80388. this.onSecondaryButtonStateChangedObservable.clear();
  80389. this.onPadStateChangedObservable.clear();
  80390. this.onPadValuesChangedObservable.clear();
  80391. };
  80392. return WebVRController;
  80393. }(BABYLON.PoseEnabledController));
  80394. BABYLON.WebVRController = WebVRController;
  80395. })(BABYLON || (BABYLON = {}));
  80396. //# sourceMappingURL=babylon.webVRController.js.map
  80397. var BABYLON;
  80398. (function (BABYLON) {
  80399. /**
  80400. * Oculus Touch Controller
  80401. */
  80402. var OculusTouchController = /** @class */ (function (_super) {
  80403. __extends(OculusTouchController, _super);
  80404. /**
  80405. * Creates a new OculusTouchController from a gamepad
  80406. * @param vrGamepad the gamepad that the controller should be created from
  80407. */
  80408. function OculusTouchController(vrGamepad) {
  80409. var _this = _super.call(this, vrGamepad) || this;
  80410. /**
  80411. * Fired when the secondary trigger on this controller is modified
  80412. */
  80413. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  80414. /**
  80415. * Fired when the thumb rest on this controller is modified
  80416. */
  80417. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  80418. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  80419. return _this;
  80420. }
  80421. /**
  80422. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  80423. * @param scene scene in which to add meshes
  80424. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  80425. */
  80426. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  80427. var _this = this;
  80428. var meshName;
  80429. // Hand
  80430. if (this.hand === 'left') {
  80431. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  80432. }
  80433. else { // Right is the default if no hand is specified
  80434. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  80435. }
  80436. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  80437. /*
  80438. Parent Mesh name: oculus_touch_left
  80439. - body
  80440. - trigger
  80441. - thumbstick
  80442. - grip
  80443. - button_y
  80444. - button_x
  80445. - button_enter
  80446. */
  80447. _this._defaultModel = newMeshes[1];
  80448. _this.attachToMesh(_this._defaultModel);
  80449. if (meshLoaded) {
  80450. meshLoaded(_this._defaultModel);
  80451. }
  80452. });
  80453. };
  80454. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  80455. /**
  80456. * Fired when the A button on this controller is modified
  80457. */
  80458. get: function () {
  80459. if (this.hand === 'right') {
  80460. return this.onMainButtonStateChangedObservable;
  80461. }
  80462. else {
  80463. throw new Error('No A button on left hand');
  80464. }
  80465. },
  80466. enumerable: true,
  80467. configurable: true
  80468. });
  80469. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  80470. /**
  80471. * Fired when the B button on this controller is modified
  80472. */
  80473. get: function () {
  80474. if (this.hand === 'right') {
  80475. return this.onSecondaryButtonStateChangedObservable;
  80476. }
  80477. else {
  80478. throw new Error('No B button on left hand');
  80479. }
  80480. },
  80481. enumerable: true,
  80482. configurable: true
  80483. });
  80484. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  80485. /**
  80486. * Fired when the X button on this controller is modified
  80487. */
  80488. get: function () {
  80489. if (this.hand === 'left') {
  80490. return this.onMainButtonStateChangedObservable;
  80491. }
  80492. else {
  80493. throw new Error('No X button on right hand');
  80494. }
  80495. },
  80496. enumerable: true,
  80497. configurable: true
  80498. });
  80499. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  80500. /**
  80501. * Fired when the Y button on this controller is modified
  80502. */
  80503. get: function () {
  80504. if (this.hand === 'left') {
  80505. return this.onSecondaryButtonStateChangedObservable;
  80506. }
  80507. else {
  80508. throw new Error('No Y button on right hand');
  80509. }
  80510. },
  80511. enumerable: true,
  80512. configurable: true
  80513. });
  80514. /**
  80515. * Called once for each button that changed state since the last frame
  80516. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  80517. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  80518. * 2) secondary trigger (same)
  80519. * 3) A (right) X (left), touch, pressed = value
  80520. * 4) B / Y
  80521. * 5) thumb rest
  80522. * @param buttonIdx Which button index changed
  80523. * @param state New state of the button
  80524. * @param changes Which properties on the state changed since last frame
  80525. */
  80526. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  80527. var notifyObject = state; //{ state: state, changes: changes };
  80528. var triggerDirection = this.hand === 'right' ? -1 : 1;
  80529. switch (buttonIdx) {
  80530. case 0:
  80531. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  80532. return;
  80533. case 1: // index trigger
  80534. if (this._defaultModel) {
  80535. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  80536. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  80537. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  80538. }
  80539. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  80540. return;
  80541. case 2: // secondary trigger
  80542. if (this._defaultModel) {
  80543. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  80544. }
  80545. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  80546. return;
  80547. case 3:
  80548. if (this._defaultModel) {
  80549. if (notifyObject.pressed) {
  80550. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  80551. }
  80552. else {
  80553. (this._defaultModel.getChildren()[1]).position.y = 0;
  80554. }
  80555. }
  80556. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  80557. return;
  80558. case 4:
  80559. if (this._defaultModel) {
  80560. if (notifyObject.pressed) {
  80561. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  80562. }
  80563. else {
  80564. (this._defaultModel.getChildren()[2]).position.y = 0;
  80565. }
  80566. }
  80567. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  80568. return;
  80569. case 5:
  80570. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  80571. return;
  80572. }
  80573. };
  80574. /**
  80575. * Base Url for the controller model.
  80576. */
  80577. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  80578. /**
  80579. * File name for the left controller model.
  80580. */
  80581. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  80582. /**
  80583. * File name for the right controller model.
  80584. */
  80585. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  80586. return OculusTouchController;
  80587. }(BABYLON.WebVRController));
  80588. BABYLON.OculusTouchController = OculusTouchController;
  80589. })(BABYLON || (BABYLON = {}));
  80590. //# sourceMappingURL=babylon.oculusTouchController.js.map
  80591. var BABYLON;
  80592. (function (BABYLON) {
  80593. /**
  80594. * Vive Controller
  80595. */
  80596. var ViveController = /** @class */ (function (_super) {
  80597. __extends(ViveController, _super);
  80598. /**
  80599. * Creates a new ViveController from a gamepad
  80600. * @param vrGamepad the gamepad that the controller should be created from
  80601. */
  80602. function ViveController(vrGamepad) {
  80603. var _this = _super.call(this, vrGamepad) || this;
  80604. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  80605. _this._invertLeftStickY = true;
  80606. return _this;
  80607. }
  80608. /**
  80609. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  80610. * @param scene scene in which to add meshes
  80611. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  80612. */
  80613. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  80614. var _this = this;
  80615. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  80616. /*
  80617. Parent Mesh name: ViveWand
  80618. - body
  80619. - r_gripper
  80620. - l_gripper
  80621. - menu_button
  80622. - system_button
  80623. - trackpad
  80624. - trigger
  80625. - LED
  80626. */
  80627. _this._defaultModel = newMeshes[1];
  80628. _this.attachToMesh(_this._defaultModel);
  80629. if (meshLoaded) {
  80630. meshLoaded(_this._defaultModel);
  80631. }
  80632. });
  80633. };
  80634. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  80635. /**
  80636. * Fired when the left button on this controller is modified
  80637. */
  80638. get: function () {
  80639. return this.onMainButtonStateChangedObservable;
  80640. },
  80641. enumerable: true,
  80642. configurable: true
  80643. });
  80644. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  80645. /**
  80646. * Fired when the right button on this controller is modified
  80647. */
  80648. get: function () {
  80649. return this.onMainButtonStateChangedObservable;
  80650. },
  80651. enumerable: true,
  80652. configurable: true
  80653. });
  80654. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  80655. /**
  80656. * Fired when the menu button on this controller is modified
  80657. */
  80658. get: function () {
  80659. return this.onSecondaryButtonStateChangedObservable;
  80660. },
  80661. enumerable: true,
  80662. configurable: true
  80663. });
  80664. /**
  80665. * Called once for each button that changed state since the last frame
  80666. * Vive mapping:
  80667. * 0: touchpad
  80668. * 1: trigger
  80669. * 2: left AND right buttons
  80670. * 3: menu button
  80671. * @param buttonIdx Which button index changed
  80672. * @param state New state of the button
  80673. * @param changes Which properties on the state changed since last frame
  80674. */
  80675. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  80676. var notifyObject = state; //{ state: state, changes: changes };
  80677. switch (buttonIdx) {
  80678. case 0:
  80679. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  80680. return;
  80681. case 1: // index trigger
  80682. if (this._defaultModel) {
  80683. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  80684. }
  80685. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  80686. return;
  80687. case 2: // left AND right button
  80688. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  80689. return;
  80690. case 3:
  80691. if (this._defaultModel) {
  80692. if (notifyObject.pressed) {
  80693. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  80694. }
  80695. else {
  80696. (this._defaultModel.getChildren()[2]).position.y = 0;
  80697. }
  80698. }
  80699. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  80700. return;
  80701. }
  80702. };
  80703. /**
  80704. * Base Url for the controller model.
  80705. */
  80706. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  80707. /**
  80708. * File name for the controller model.
  80709. */
  80710. ViveController.MODEL_FILENAME = 'wand.babylon';
  80711. return ViveController;
  80712. }(BABYLON.WebVRController));
  80713. BABYLON.ViveController = ViveController;
  80714. })(BABYLON || (BABYLON = {}));
  80715. //# sourceMappingURL=babylon.viveController.js.map
  80716. var BABYLON;
  80717. (function (BABYLON) {
  80718. /**
  80719. * Generic Controller
  80720. */
  80721. var GenericController = /** @class */ (function (_super) {
  80722. __extends(GenericController, _super);
  80723. /**
  80724. * Creates a new GenericController from a gamepad
  80725. * @param vrGamepad the gamepad that the controller should be created from
  80726. */
  80727. function GenericController(vrGamepad) {
  80728. return _super.call(this, vrGamepad) || this;
  80729. }
  80730. /**
  80731. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  80732. * @param scene scene in which to add meshes
  80733. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  80734. */
  80735. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  80736. var _this = this;
  80737. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  80738. _this._defaultModel = newMeshes[1];
  80739. _this.attachToMesh(_this._defaultModel);
  80740. if (meshLoaded) {
  80741. meshLoaded(_this._defaultModel);
  80742. }
  80743. });
  80744. };
  80745. /**
  80746. * Called once for each button that changed state since the last frame
  80747. * @param buttonIdx Which button index changed
  80748. * @param state New state of the button
  80749. * @param changes Which properties on the state changed since last frame
  80750. */
  80751. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  80752. console.log("Button id: " + buttonIdx + "state: ");
  80753. console.dir(state);
  80754. };
  80755. /**
  80756. * Base Url for the controller model.
  80757. */
  80758. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  80759. /**
  80760. * File name for the controller model.
  80761. */
  80762. GenericController.MODEL_FILENAME = 'generic.babylon';
  80763. return GenericController;
  80764. }(BABYLON.WebVRController));
  80765. BABYLON.GenericController = GenericController;
  80766. })(BABYLON || (BABYLON = {}));
  80767. //# sourceMappingURL=babylon.genericController.js.map
  80768. var BABYLON;
  80769. (function (BABYLON) {
  80770. /**
  80771. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  80772. */
  80773. var LoadedMeshInfo = /** @class */ (function () {
  80774. function LoadedMeshInfo() {
  80775. /**
  80776. * Map of the button meshes contained in the controller
  80777. */
  80778. this.buttonMeshes = {};
  80779. /**
  80780. * Map of the axis meshes contained in the controller
  80781. */
  80782. this.axisMeshes = {};
  80783. }
  80784. return LoadedMeshInfo;
  80785. }());
  80786. /**
  80787. * Defines the WindowsMotionController object that the state of the windows motion controller
  80788. */
  80789. var WindowsMotionController = /** @class */ (function (_super) {
  80790. __extends(WindowsMotionController, _super);
  80791. /**
  80792. * Creates a new WindowsMotionController from a gamepad
  80793. * @param vrGamepad the gamepad that the controller should be created from
  80794. */
  80795. function WindowsMotionController(vrGamepad) {
  80796. var _this = _super.call(this, vrGamepad) || this;
  80797. _this._mapping = {
  80798. // Semantic button names
  80799. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  80800. // A mapping of the button name to glTF model node name
  80801. // that should be transformed by button value.
  80802. buttonMeshNames: {
  80803. 'trigger': 'SELECT',
  80804. 'menu': 'MENU',
  80805. 'grip': 'GRASP',
  80806. 'thumbstick': 'THUMBSTICK_PRESS',
  80807. 'trackpad': 'TOUCHPAD_PRESS'
  80808. },
  80809. // This mapping is used to translate from the Motion Controller to Babylon semantics
  80810. buttonObservableNames: {
  80811. 'trigger': 'onTriggerStateChangedObservable',
  80812. 'menu': 'onSecondaryButtonStateChangedObservable',
  80813. 'grip': 'onMainButtonStateChangedObservable',
  80814. 'thumbstick': 'onPadStateChangedObservable',
  80815. 'trackpad': 'onTrackpadChangedObservable'
  80816. },
  80817. // A mapping of the axis name to glTF model node name
  80818. // that should be transformed by axis value.
  80819. // This array mirrors the browserGamepad.axes array, such that
  80820. // the mesh corresponding to axis 0 is in this array index 0.
  80821. axisMeshNames: [
  80822. 'THUMBSTICK_X',
  80823. 'THUMBSTICK_Y',
  80824. 'TOUCHPAD_TOUCH_X',
  80825. 'TOUCHPAD_TOUCH_Y'
  80826. ],
  80827. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  80828. };
  80829. /**
  80830. * Fired when the trackpad on this controller is clicked
  80831. */
  80832. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  80833. /**
  80834. * Fired when the trackpad on this controller is modified
  80835. */
  80836. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  80837. /**
  80838. * The current x and y values of this controller's trackpad
  80839. */
  80840. _this.trackpad = { x: 0, y: 0 };
  80841. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  80842. _this._loadedMeshInfo = null;
  80843. return _this;
  80844. }
  80845. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  80846. /**
  80847. * Fired when the trigger on this controller is modified
  80848. */
  80849. get: function () {
  80850. return this.onTriggerStateChangedObservable;
  80851. },
  80852. enumerable: true,
  80853. configurable: true
  80854. });
  80855. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  80856. /**
  80857. * Fired when the menu button on this controller is modified
  80858. */
  80859. get: function () {
  80860. return this.onSecondaryButtonStateChangedObservable;
  80861. },
  80862. enumerable: true,
  80863. configurable: true
  80864. });
  80865. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  80866. /**
  80867. * Fired when the grip button on this controller is modified
  80868. */
  80869. get: function () {
  80870. return this.onMainButtonStateChangedObservable;
  80871. },
  80872. enumerable: true,
  80873. configurable: true
  80874. });
  80875. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  80876. /**
  80877. * Fired when the thumbstick button on this controller is modified
  80878. */
  80879. get: function () {
  80880. return this.onPadStateChangedObservable;
  80881. },
  80882. enumerable: true,
  80883. configurable: true
  80884. });
  80885. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  80886. /**
  80887. * Fired when the touchpad button on this controller is modified
  80888. */
  80889. get: function () {
  80890. return this.onTrackpadChangedObservable;
  80891. },
  80892. enumerable: true,
  80893. configurable: true
  80894. });
  80895. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  80896. /**
  80897. * Fired when the touchpad values on this controller are modified
  80898. */
  80899. get: function () {
  80900. return this.onTrackpadValuesChangedObservable;
  80901. },
  80902. enumerable: true,
  80903. configurable: true
  80904. });
  80905. WindowsMotionController.prototype._updateTrackpad = function () {
  80906. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  80907. this.trackpad.x = this.browserGamepad["axes"][2];
  80908. this.trackpad.y = this.browserGamepad["axes"][3];
  80909. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  80910. }
  80911. };
  80912. /**
  80913. * Called once per frame by the engine.
  80914. */
  80915. WindowsMotionController.prototype.update = function () {
  80916. _super.prototype.update.call(this);
  80917. if (this.browserGamepad.axes) {
  80918. this._updateTrackpad();
  80919. // Only need to animate axes if there is a loaded mesh
  80920. if (this._loadedMeshInfo) {
  80921. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  80922. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  80923. }
  80924. }
  80925. }
  80926. };
  80927. /**
  80928. * Called once for each button that changed state since the last frame
  80929. * @param buttonIdx Which button index changed
  80930. * @param state New state of the button
  80931. * @param changes Which properties on the state changed since last frame
  80932. */
  80933. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  80934. var buttonName = this._mapping.buttons[buttonIdx];
  80935. if (!buttonName) {
  80936. return;
  80937. }
  80938. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  80939. this._updateTrackpad();
  80940. // Only emit events for buttons that we know how to map from index to name
  80941. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  80942. if (observable) {
  80943. observable.notifyObservers(state);
  80944. }
  80945. this._lerpButtonTransform(buttonName, state.value);
  80946. };
  80947. /**
  80948. * Moves the buttons on the controller mesh based on their current state
  80949. * @param buttonName the name of the button to move
  80950. * @param buttonValue the value of the button which determines the buttons new position
  80951. */
  80952. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  80953. // If there is no loaded mesh, there is nothing to transform.
  80954. if (!this._loadedMeshInfo) {
  80955. return;
  80956. }
  80957. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  80958. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  80959. return;
  80960. }
  80961. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  80962. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  80963. };
  80964. /**
  80965. * Moves the axis on the controller mesh based on its current state
  80966. * @param axis the index of the axis
  80967. * @param axisValue the value of the axis which determines the meshes new position
  80968. * @hidden
  80969. */
  80970. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  80971. if (!this._loadedMeshInfo) {
  80972. return;
  80973. }
  80974. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  80975. if (!meshInfo) {
  80976. return;
  80977. }
  80978. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  80979. return;
  80980. }
  80981. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  80982. var lerpValue = axisValue * 0.5 + 0.5;
  80983. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  80984. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  80985. };
  80986. /**
  80987. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  80988. * @param scene scene in which to add meshes
  80989. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  80990. */
  80991. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  80992. var _this = this;
  80993. if (forceDefault === void 0) { forceDefault = false; }
  80994. var path;
  80995. var filename;
  80996. // Checking if GLB loader is present
  80997. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  80998. // Determine the device specific folder based on the ID suffix
  80999. var device = 'default';
  81000. if (this.id && !forceDefault) {
  81001. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  81002. device = ((match && match[0]) || device);
  81003. }
  81004. // Hand
  81005. if (this.hand === 'left') {
  81006. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  81007. }
  81008. else { // Right is the default if no hand is specified
  81009. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  81010. }
  81011. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  81012. }
  81013. else {
  81014. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  81015. path = BABYLON.GenericController.MODEL_BASE_URL;
  81016. filename = BABYLON.GenericController.MODEL_FILENAME;
  81017. }
  81018. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  81019. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  81020. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  81021. if (!_this._loadedMeshInfo) {
  81022. return;
  81023. }
  81024. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  81025. _this.attachToMesh(_this._defaultModel);
  81026. if (meshLoaded) {
  81027. meshLoaded(_this._defaultModel);
  81028. }
  81029. }, null, function (scene, message) {
  81030. BABYLON.Tools.Log(message);
  81031. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  81032. if (!forceDefault) {
  81033. _this.initControllerMesh(scene, meshLoaded, true);
  81034. }
  81035. });
  81036. };
  81037. /**
  81038. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  81039. * can be transformed by button presses and axes values, based on this._mapping.
  81040. *
  81041. * @param scene scene in which the meshes exist
  81042. * @param meshes list of meshes that make up the controller model to process
  81043. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  81044. */
  81045. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  81046. var loadedMeshInfo = null;
  81047. // Create a new mesh to contain the glTF hierarchy
  81048. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  81049. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  81050. var childMesh = null;
  81051. for (var i = 0; i < meshes.length; i++) {
  81052. var mesh = meshes[i];
  81053. if (!mesh.parent) {
  81054. // Exclude controller meshes from picking results
  81055. mesh.isPickable = false;
  81056. // Handle root node, attach to the new parentMesh
  81057. childMesh = mesh;
  81058. break;
  81059. }
  81060. }
  81061. if (childMesh) {
  81062. childMesh.setParent(parentMesh);
  81063. // Create our mesh info. Note that this method will always return non-null.
  81064. loadedMeshInfo = this.createMeshInfo(parentMesh);
  81065. }
  81066. else {
  81067. BABYLON.Tools.Warn('Could not find root node in model file.');
  81068. }
  81069. return loadedMeshInfo;
  81070. };
  81071. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  81072. var loadedMeshInfo = new LoadedMeshInfo();
  81073. var i;
  81074. loadedMeshInfo.rootNode = rootNode;
  81075. // Reset the caches
  81076. loadedMeshInfo.buttonMeshes = {};
  81077. loadedMeshInfo.axisMeshes = {};
  81078. // Button Meshes
  81079. for (i = 0; i < this._mapping.buttons.length; i++) {
  81080. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  81081. if (!buttonMeshName) {
  81082. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  81083. continue;
  81084. }
  81085. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  81086. if (!buttonMesh) {
  81087. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  81088. continue;
  81089. }
  81090. var buttonMeshInfo = {
  81091. index: i,
  81092. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  81093. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  81094. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  81095. };
  81096. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  81097. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  81098. }
  81099. else {
  81100. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  81101. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  81102. '(VALUE: ' + !!buttonMeshInfo.value +
  81103. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  81104. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  81105. ')');
  81106. }
  81107. }
  81108. // Axis Meshes
  81109. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  81110. var axisMeshName = this._mapping.axisMeshNames[i];
  81111. if (!axisMeshName) {
  81112. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  81113. continue;
  81114. }
  81115. var axisMesh = getChildByName(rootNode, axisMeshName);
  81116. if (!axisMesh) {
  81117. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  81118. continue;
  81119. }
  81120. var axisMeshInfo = {
  81121. index: i,
  81122. value: getImmediateChildByName(axisMesh, 'VALUE'),
  81123. min: getImmediateChildByName(axisMesh, 'MIN'),
  81124. max: getImmediateChildByName(axisMesh, 'MAX')
  81125. };
  81126. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  81127. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  81128. }
  81129. else {
  81130. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  81131. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  81132. '(VALUE: ' + !!axisMeshInfo.value +
  81133. ', MIN: ' + !!axisMeshInfo.min +
  81134. ', MAX:' + !!axisMeshInfo.max +
  81135. ')');
  81136. }
  81137. }
  81138. // Pointing Ray
  81139. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  81140. if (!loadedMeshInfo.pointingPoseNode) {
  81141. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  81142. }
  81143. else {
  81144. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  81145. }
  81146. return loadedMeshInfo;
  81147. // Look through all children recursively. This will return null if no mesh exists with the given name.
  81148. function getChildByName(node, name) {
  81149. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  81150. }
  81151. // Look through only immediate children. This will return null if no mesh exists with the given name.
  81152. function getImmediateChildByName(node, name) {
  81153. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  81154. }
  81155. };
  81156. /**
  81157. * Gets the ray of the controller in the direction the controller is pointing
  81158. * @param length the length the resulting ray should be
  81159. * @returns a ray in the direction the controller is pointing
  81160. */
  81161. WindowsMotionController.prototype.getForwardRay = function (length) {
  81162. if (length === void 0) { length = 100; }
  81163. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  81164. return _super.prototype.getForwardRay.call(this, length);
  81165. }
  81166. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  81167. var origin = m.getTranslation();
  81168. var forward = new BABYLON.Vector3(0, 0, -1);
  81169. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  81170. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  81171. return new BABYLON.Ray(origin, direction, length);
  81172. };
  81173. /**
  81174. * Disposes of the controller
  81175. */
  81176. WindowsMotionController.prototype.dispose = function () {
  81177. _super.prototype.dispose.call(this);
  81178. this.onTrackpadChangedObservable.clear();
  81179. };
  81180. /**
  81181. * The base url used to load the left and right controller models
  81182. */
  81183. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  81184. /**
  81185. * The name of the left controller model file
  81186. */
  81187. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  81188. /**
  81189. * The name of the right controller model file
  81190. */
  81191. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  81192. /**
  81193. * The controller name prefix for this controller type
  81194. */
  81195. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  81196. /**
  81197. * The controller id pattern for this controller type
  81198. */
  81199. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  81200. return WindowsMotionController;
  81201. }(BABYLON.WebVRController));
  81202. BABYLON.WindowsMotionController = WindowsMotionController;
  81203. })(BABYLON || (BABYLON = {}));
  81204. //# sourceMappingURL=babylon.windowsMotionController.js.map
  81205. var BABYLON;
  81206. (function (BABYLON) {
  81207. /**
  81208. * Gear VR Controller
  81209. */
  81210. var GearVRController = /** @class */ (function (_super) {
  81211. __extends(GearVRController, _super);
  81212. /**
  81213. * Creates a new GearVRController from a gamepad
  81214. * @param vrGamepad the gamepad that the controller should be created from
  81215. */
  81216. function GearVRController(vrGamepad) {
  81217. var _this = _super.call(this, vrGamepad) || this;
  81218. _this._buttonIndexToObservableNameMap = [
  81219. 'onTrackpadChangedObservable',
  81220. 'onTriggerStateChangedObservable' // Trigger
  81221. ];
  81222. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  81223. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  81224. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  81225. _this._disableTrackPosition(_this._calculatedPosition);
  81226. return _this;
  81227. }
  81228. /**
  81229. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  81230. * @param scene scene in which to add meshes
  81231. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  81232. */
  81233. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  81234. var _this = this;
  81235. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  81236. // Offset the controller so it will rotate around the users wrist
  81237. var mesh = new BABYLON.Mesh("", scene);
  81238. newMeshes[1].parent = mesh;
  81239. newMeshes[1].position.z = -0.15;
  81240. _this._defaultModel = mesh;
  81241. _this.attachToMesh(_this._defaultModel);
  81242. if (meshLoaded) {
  81243. meshLoaded(_this._defaultModel);
  81244. }
  81245. });
  81246. };
  81247. /**
  81248. * Called once for each button that changed state since the last frame
  81249. * @param buttonIdx Which button index changed
  81250. * @param state New state of the button
  81251. * @param changes Which properties on the state changed since last frame
  81252. */
  81253. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  81254. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  81255. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  81256. // Only emit events for buttons that we know how to map from index to observable
  81257. var observable = this[observableName];
  81258. if (observable) {
  81259. observable.notifyObservers(state);
  81260. }
  81261. }
  81262. };
  81263. /**
  81264. * Base Url for the controller model.
  81265. */
  81266. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  81267. /**
  81268. * File name for the controller model.
  81269. */
  81270. GearVRController.MODEL_FILENAME = 'generic.babylon';
  81271. /**
  81272. * Gamepad Id prefix used to identify this controller.
  81273. */
  81274. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  81275. return GearVRController;
  81276. }(BABYLON.WebVRController));
  81277. BABYLON.GearVRController = GearVRController;
  81278. })(BABYLON || (BABYLON = {}));
  81279. //# sourceMappingURL=babylon.gearVRController.js.map
  81280. var BABYLON;
  81281. (function (BABYLON) {
  81282. /**
  81283. * Google Daydream controller
  81284. */
  81285. var DaydreamController = /** @class */ (function (_super) {
  81286. __extends(DaydreamController, _super);
  81287. /**
  81288. * Creates a new DaydreamController from a gamepad
  81289. * @param vrGamepad the gamepad that the controller should be created from
  81290. */
  81291. function DaydreamController(vrGamepad) {
  81292. var _this = _super.call(this, vrGamepad) || this;
  81293. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  81294. return _this;
  81295. }
  81296. /**
  81297. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  81298. * @param scene scene in which to add meshes
  81299. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  81300. */
  81301. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  81302. var _this = this;
  81303. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  81304. _this._defaultModel = newMeshes[1];
  81305. _this.attachToMesh(_this._defaultModel);
  81306. if (meshLoaded) {
  81307. meshLoaded(_this._defaultModel);
  81308. }
  81309. });
  81310. };
  81311. /**
  81312. * Called once for each button that changed state since the last frame
  81313. * @param buttonIdx Which button index changed
  81314. * @param state New state of the button
  81315. * @param changes Which properties on the state changed since last frame
  81316. */
  81317. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  81318. // Daydream controller only has 1 GamepadButton (on the trackpad).
  81319. if (buttonIdx === 0) {
  81320. var observable = this.onTriggerStateChangedObservable;
  81321. if (observable) {
  81322. observable.notifyObservers(state);
  81323. }
  81324. }
  81325. else {
  81326. // If the app or home buttons are ever made available
  81327. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  81328. }
  81329. };
  81330. /**
  81331. * Base Url for the controller model.
  81332. */
  81333. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  81334. /**
  81335. * File name for the controller model.
  81336. */
  81337. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  81338. /**
  81339. * Gamepad Id prefix used to identify Daydream Controller.
  81340. */
  81341. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  81342. return DaydreamController;
  81343. }(BABYLON.WebVRController));
  81344. BABYLON.DaydreamController = DaydreamController;
  81345. })(BABYLON || (BABYLON = {}));
  81346. //# sourceMappingURL=babylon.daydreamController.js.map
  81347. var BABYLON;
  81348. (function (BABYLON) {
  81349. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  81350. get: function () {
  81351. if (!this._gamepadManager) {
  81352. this._gamepadManager = new BABYLON.GamepadManager(this);
  81353. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  81354. if (!component) {
  81355. component = new GamepadSystemSceneComponent(this);
  81356. this._addComponent(component);
  81357. }
  81358. }
  81359. return this._gamepadManager;
  81360. },
  81361. enumerable: true,
  81362. configurable: true
  81363. });
  81364. /**
  81365. * Adds a gamepad to the free camera inputs manager
  81366. */
  81367. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  81368. this.add(new BABYLON.FreeCameraGamepadInput());
  81369. return this;
  81370. };
  81371. /**
  81372. * Adds a gamepad to the arc rotate camera inputs manager
  81373. */
  81374. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  81375. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  81376. return this;
  81377. };
  81378. /**
  81379. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  81380. */
  81381. var GamepadSystemSceneComponent = /** @class */ (function () {
  81382. /**
  81383. * Creates a new instance of the component for the given scene
  81384. * @param scene Defines the scene to register the component in
  81385. */
  81386. function GamepadSystemSceneComponent(scene) {
  81387. /**
  81388. * The component name helpfull to identify the component in the list of scene components.
  81389. */
  81390. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  81391. this.scene = scene;
  81392. }
  81393. /**
  81394. * Registers the component in a given scene
  81395. */
  81396. GamepadSystemSceneComponent.prototype.register = function () {
  81397. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  81398. };
  81399. /**
  81400. * Rebuilds the elements related to this component in case of
  81401. * context lost for instance.
  81402. */
  81403. GamepadSystemSceneComponent.prototype.rebuild = function () {
  81404. // Nothing to do for gamepads
  81405. };
  81406. /**
  81407. * Disposes the component and the associated ressources
  81408. */
  81409. GamepadSystemSceneComponent.prototype.dispose = function () {
  81410. var gamepadManager = this.scene._gamepadManager;
  81411. if (gamepadManager) {
  81412. gamepadManager.dispose();
  81413. this.scene._gamepadManager = null;
  81414. }
  81415. };
  81416. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  81417. var gamepadManager = this.scene._gamepadManager;
  81418. if (gamepadManager && gamepadManager._isMonitoring) {
  81419. gamepadManager._checkGamepadsStatus();
  81420. }
  81421. };
  81422. return GamepadSystemSceneComponent;
  81423. }());
  81424. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  81425. })(BABYLON || (BABYLON = {}));
  81426. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  81427. var BABYLON;
  81428. (function (BABYLON) {
  81429. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  81430. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  81431. });
  81432. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  81433. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  81434. });
  81435. /**
  81436. * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and
  81437. * an arc rotate version arcFollowCamera are available.
  81438. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  81439. */
  81440. var FollowCamera = /** @class */ (function (_super) {
  81441. __extends(FollowCamera, _super);
  81442. /**
  81443. * Instantiates the follow camera.
  81444. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  81445. * @param name Define the name of the camera in the scene
  81446. * @param position Define the position of the camera
  81447. * @param scene Define the scene the camera belong to
  81448. * @param lockedTarget Define the target of the camera
  81449. */
  81450. function FollowCamera(name, position, scene, lockedTarget) {
  81451. if (lockedTarget === void 0) { lockedTarget = null; }
  81452. var _this = _super.call(this, name, position, scene) || this;
  81453. /**
  81454. * Distance the follow camera should follow an object at
  81455. */
  81456. _this.radius = 12;
  81457. /**
  81458. * Define a rotation offset between the camera and the object it follows
  81459. */
  81460. _this.rotationOffset = 0;
  81461. /**
  81462. * Define a height offset between the camera and the object it follows.
  81463. * It can help following an object from the top (like a car chaing a plane)
  81464. */
  81465. _this.heightOffset = 4;
  81466. /**
  81467. * Define how fast the camera can accelerate to follow it s target.
  81468. */
  81469. _this.cameraAcceleration = 0.05;
  81470. /**
  81471. * Define the speed limit of the camera following an object.
  81472. */
  81473. _this.maxCameraSpeed = 20;
  81474. _this.lockedTarget = lockedTarget;
  81475. return _this;
  81476. }
  81477. FollowCamera.prototype._follow = function (cameraTarget) {
  81478. if (!cameraTarget)
  81479. return;
  81480. var yRotation;
  81481. if (cameraTarget.rotationQuaternion) {
  81482. var rotMatrix = new BABYLON.Matrix();
  81483. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  81484. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  81485. }
  81486. else {
  81487. yRotation = cameraTarget.rotation.y;
  81488. }
  81489. var radians = BABYLON.Tools.ToRadians(this.rotationOffset) + yRotation;
  81490. var targetPosition = cameraTarget.getAbsolutePosition();
  81491. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  81492. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  81493. var dx = targetX - this.position.x;
  81494. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  81495. var dz = (targetZ) - this.position.z;
  81496. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  81497. var vy = dy * this.cameraAcceleration;
  81498. var vz = dz * this.cameraAcceleration * 2;
  81499. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  81500. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  81501. }
  81502. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  81503. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  81504. }
  81505. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  81506. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  81507. }
  81508. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  81509. this.setTarget(targetPosition);
  81510. };
  81511. /** @hidden */
  81512. FollowCamera.prototype._checkInputs = function () {
  81513. _super.prototype._checkInputs.call(this);
  81514. if (this.lockedTarget) {
  81515. this._follow(this.lockedTarget);
  81516. }
  81517. };
  81518. /**
  81519. * Gets the camera class name.
  81520. * @returns the class name
  81521. */
  81522. FollowCamera.prototype.getClassName = function () {
  81523. return "FollowCamera";
  81524. };
  81525. __decorate([
  81526. BABYLON.serialize()
  81527. ], FollowCamera.prototype, "radius", void 0);
  81528. __decorate([
  81529. BABYLON.serialize()
  81530. ], FollowCamera.prototype, "rotationOffset", void 0);
  81531. __decorate([
  81532. BABYLON.serialize()
  81533. ], FollowCamera.prototype, "heightOffset", void 0);
  81534. __decorate([
  81535. BABYLON.serialize()
  81536. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  81537. __decorate([
  81538. BABYLON.serialize()
  81539. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  81540. __decorate([
  81541. BABYLON.serializeAsMeshReference("lockedTargetId")
  81542. ], FollowCamera.prototype, "lockedTarget", void 0);
  81543. return FollowCamera;
  81544. }(BABYLON.TargetCamera));
  81545. BABYLON.FollowCamera = FollowCamera;
  81546. /**
  81547. * Arc Rotate version of the follow camera.
  81548. * It still follows a Defined mesh but in an Arc Rotate Camera fashion.
  81549. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  81550. */
  81551. var ArcFollowCamera = /** @class */ (function (_super) {
  81552. __extends(ArcFollowCamera, _super);
  81553. /**
  81554. * Instantiates a new ArcFollowCamera
  81555. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  81556. * @param name Define the name of the camera
  81557. * @param alpha Define the rotation angle of the camera around the logitudinal axis
  81558. * @param beta Define the rotation angle of the camera around the elevation axis
  81559. * @param radius Define the radius of the camera from its target point
  81560. * @param target Define the target of the camera
  81561. * @param scene Define the scene the camera belongs to
  81562. */
  81563. function ArcFollowCamera(name,
  81564. /** The longitudinal angle of the camera */
  81565. alpha,
  81566. /** The latitudinal angle of the camera */
  81567. beta,
  81568. /** The radius of the camera from its target */
  81569. radius,
  81570. /** Define the camera target (the messh it should follow) */
  81571. target, scene) {
  81572. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  81573. _this.alpha = alpha;
  81574. _this.beta = beta;
  81575. _this.radius = radius;
  81576. _this.target = target;
  81577. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  81578. _this._follow();
  81579. return _this;
  81580. }
  81581. ArcFollowCamera.prototype._follow = function () {
  81582. if (!this.target) {
  81583. return;
  81584. }
  81585. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  81586. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  81587. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  81588. var targetPosition = this.target.getAbsolutePosition();
  81589. this.position = targetPosition.add(this._cartesianCoordinates);
  81590. this.setTarget(targetPosition);
  81591. };
  81592. /** @hidden */
  81593. ArcFollowCamera.prototype._checkInputs = function () {
  81594. _super.prototype._checkInputs.call(this);
  81595. this._follow();
  81596. };
  81597. /**
  81598. * Returns the class name of the object.
  81599. * It is mostly used internally for serialization purposes.
  81600. */
  81601. ArcFollowCamera.prototype.getClassName = function () {
  81602. return "ArcFollowCamera";
  81603. };
  81604. return ArcFollowCamera;
  81605. }(BABYLON.TargetCamera));
  81606. BABYLON.ArcFollowCamera = ArcFollowCamera;
  81607. })(BABYLON || (BABYLON = {}));
  81608. //# sourceMappingURL=babylon.followCamera.js.map
  81609. var BABYLON;
  81610. (function (BABYLON) {
  81611. /**
  81612. * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera,
  81613. * which still works and will still be found in many Playgrounds.
  81614. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  81615. */
  81616. var UniversalCamera = /** @class */ (function (_super) {
  81617. __extends(UniversalCamera, _super);
  81618. /**
  81619. * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera,
  81620. * which still works and will still be found in many Playgrounds.
  81621. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  81622. * @param name Define the name of the camera in the scene
  81623. * @param position Define the start position of the camera in the scene
  81624. * @param scene Define the scene the camera belongs to
  81625. */
  81626. function UniversalCamera(name, position, scene) {
  81627. var _this = _super.call(this, name, position, scene) || this;
  81628. _this.inputs.addGamepad();
  81629. return _this;
  81630. }
  81631. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  81632. /**
  81633. * Defines the gamepad rotation sensiblity.
  81634. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  81635. */
  81636. get: function () {
  81637. var gamepad = this.inputs.attached["gamepad"];
  81638. if (gamepad)
  81639. return gamepad.gamepadAngularSensibility;
  81640. return 0;
  81641. },
  81642. set: function (value) {
  81643. var gamepad = this.inputs.attached["gamepad"];
  81644. if (gamepad)
  81645. gamepad.gamepadAngularSensibility = value;
  81646. },
  81647. enumerable: true,
  81648. configurable: true
  81649. });
  81650. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  81651. /**
  81652. * Defines the gamepad move sensiblity.
  81653. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  81654. */
  81655. get: function () {
  81656. var gamepad = this.inputs.attached["gamepad"];
  81657. if (gamepad)
  81658. return gamepad.gamepadMoveSensibility;
  81659. return 0;
  81660. },
  81661. set: function (value) {
  81662. var gamepad = this.inputs.attached["gamepad"];
  81663. if (gamepad)
  81664. gamepad.gamepadMoveSensibility = value;
  81665. },
  81666. enumerable: true,
  81667. configurable: true
  81668. });
  81669. /**
  81670. * Gets the current object class name.
  81671. * @return the class name
  81672. */
  81673. UniversalCamera.prototype.getClassName = function () {
  81674. return "UniversalCamera";
  81675. };
  81676. return UniversalCamera;
  81677. }(BABYLON.TouchCamera));
  81678. BABYLON.UniversalCamera = UniversalCamera;
  81679. })(BABYLON || (BABYLON = {}));
  81680. //# sourceMappingURL=babylon.universalCamera.js.map
  81681. var BABYLON;
  81682. (function (BABYLON) {
  81683. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  81684. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  81685. });
  81686. /**
  81687. * This represents a FPS type of camera. This is only here for back compat purpose.
  81688. * Please use the UniversalCamera instead as both are identical.
  81689. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  81690. */
  81691. var GamepadCamera = /** @class */ (function (_super) {
  81692. __extends(GamepadCamera, _super);
  81693. /**
  81694. * Instantiates a new Gamepad Camera
  81695. * This represents a FPS type of camera. This is only here for back compat purpose.
  81696. * Please use the UniversalCamera instead as both are identical.
  81697. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  81698. * @param name Define the name of the camera in the scene
  81699. * @param position Define the start position of the camera in the scene
  81700. * @param scene Define the scene the camera belongs to
  81701. */
  81702. function GamepadCamera(name, position, scene) {
  81703. return _super.call(this, name, position, scene) || this;
  81704. }
  81705. /**
  81706. * Gets the current object class name.
  81707. * @return the class name
  81708. */
  81709. GamepadCamera.prototype.getClassName = function () {
  81710. return "GamepadCamera";
  81711. };
  81712. return GamepadCamera;
  81713. }(BABYLON.UniversalCamera));
  81714. BABYLON.GamepadCamera = GamepadCamera;
  81715. })(BABYLON || (BABYLON = {}));
  81716. //# sourceMappingURL=babylon.gamepadCamera.js.map
  81717. var BABYLON;
  81718. (function (BABYLON) {
  81719. /**
  81720. * PostProcessRenderPipelineManager class
  81721. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  81722. */
  81723. var PostProcessRenderPipelineManager = /** @class */ (function () {
  81724. /**
  81725. * Initializes a PostProcessRenderPipelineManager
  81726. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  81727. */
  81728. function PostProcessRenderPipelineManager() {
  81729. this._renderPipelines = {};
  81730. }
  81731. /**
  81732. * Adds a pipeline to the manager
  81733. * @param renderPipeline The pipeline to add
  81734. */
  81735. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  81736. this._renderPipelines[renderPipeline._name] = renderPipeline;
  81737. };
  81738. /**
  81739. * Attaches a camera to the pipeline
  81740. * @param renderPipelineName The name of the pipeline to attach to
  81741. * @param cameras the camera to attach
  81742. * @param unique if the camera can be attached multiple times to the pipeline
  81743. */
  81744. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  81745. if (unique === void 0) { unique = false; }
  81746. var renderPipeline = this._renderPipelines[renderPipelineName];
  81747. if (!renderPipeline) {
  81748. return;
  81749. }
  81750. renderPipeline._attachCameras(cameras, unique);
  81751. };
  81752. /**
  81753. * Detaches a camera from the pipeline
  81754. * @param renderPipelineName The name of the pipeline to detach from
  81755. * @param cameras the camera to detach
  81756. */
  81757. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  81758. var renderPipeline = this._renderPipelines[renderPipelineName];
  81759. if (!renderPipeline) {
  81760. return;
  81761. }
  81762. renderPipeline._detachCameras(cameras);
  81763. };
  81764. /**
  81765. * Enables an effect by name on a pipeline
  81766. * @param renderPipelineName the name of the pipeline to enable the effect in
  81767. * @param renderEffectName the name of the effect to enable
  81768. * @param cameras the cameras that the effect should be enabled on
  81769. */
  81770. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  81771. var renderPipeline = this._renderPipelines[renderPipelineName];
  81772. if (!renderPipeline) {
  81773. return;
  81774. }
  81775. renderPipeline._enableEffect(renderEffectName, cameras);
  81776. };
  81777. /**
  81778. * Disables an effect by name on a pipeline
  81779. * @param renderPipelineName the name of the pipeline to disable the effect in
  81780. * @param renderEffectName the name of the effect to disable
  81781. * @param cameras the cameras that the effect should be disabled on
  81782. */
  81783. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  81784. var renderPipeline = this._renderPipelines[renderPipelineName];
  81785. if (!renderPipeline) {
  81786. return;
  81787. }
  81788. renderPipeline._disableEffect(renderEffectName, cameras);
  81789. };
  81790. /**
  81791. * Updates the state of all contained render pipelines and disposes of any non supported pipelines
  81792. */
  81793. PostProcessRenderPipelineManager.prototype.update = function () {
  81794. for (var renderPipelineName in this._renderPipelines) {
  81795. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  81796. var pipeline = this._renderPipelines[renderPipelineName];
  81797. if (!pipeline.isSupported) {
  81798. pipeline.dispose();
  81799. delete this._renderPipelines[renderPipelineName];
  81800. }
  81801. else {
  81802. pipeline._update();
  81803. }
  81804. }
  81805. }
  81806. };
  81807. /** @hidden */
  81808. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  81809. for (var renderPipelineName in this._renderPipelines) {
  81810. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  81811. var pipeline = this._renderPipelines[renderPipelineName];
  81812. pipeline._rebuild();
  81813. }
  81814. }
  81815. };
  81816. /**
  81817. * Disposes of the manager and pipelines
  81818. */
  81819. PostProcessRenderPipelineManager.prototype.dispose = function () {
  81820. for (var renderPipelineName in this._renderPipelines) {
  81821. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  81822. var pipeline = this._renderPipelines[renderPipelineName];
  81823. pipeline.dispose();
  81824. }
  81825. }
  81826. };
  81827. return PostProcessRenderPipelineManager;
  81828. }());
  81829. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  81830. })(BABYLON || (BABYLON = {}));
  81831. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  81832. var BABYLON;
  81833. (function (BABYLON) {
  81834. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  81835. get: function () {
  81836. if (!this._postProcessRenderPipelineManager) {
  81837. // Register the G Buffer component to the scene.
  81838. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  81839. if (!component) {
  81840. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  81841. this._addComponent(component);
  81842. }
  81843. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  81844. }
  81845. return this._postProcessRenderPipelineManager;
  81846. },
  81847. enumerable: true,
  81848. configurable: true
  81849. });
  81850. /**
  81851. * Defines the Render Pipeline scene component responsible to rendering pipelines
  81852. */
  81853. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  81854. /**
  81855. * Creates a new instance of the component for the given scene
  81856. * @param scene Defines the scene to register the component in
  81857. */
  81858. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  81859. /**
  81860. * The component name helpfull to identify the component in the list of scene components.
  81861. */
  81862. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  81863. this.scene = scene;
  81864. }
  81865. /**
  81866. * Registers the component in a given scene
  81867. */
  81868. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  81869. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  81870. };
  81871. /**
  81872. * Rebuilds the elements related to this component in case of
  81873. * context lost for instance.
  81874. */
  81875. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  81876. if (this.scene._postProcessRenderPipelineManager) {
  81877. this.scene._postProcessRenderPipelineManager._rebuild();
  81878. }
  81879. };
  81880. /**
  81881. * Disposes the component and the associated ressources
  81882. */
  81883. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  81884. if (this.scene._postProcessRenderPipelineManager) {
  81885. this.scene._postProcessRenderPipelineManager.dispose();
  81886. }
  81887. };
  81888. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  81889. if (this.scene._postProcessRenderPipelineManager) {
  81890. this.scene._postProcessRenderPipelineManager.update();
  81891. }
  81892. };
  81893. return PostProcessRenderPipelineManagerSceneComponent;
  81894. }());
  81895. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  81896. })(BABYLON || (BABYLON = {}));
  81897. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  81898. var BABYLON;
  81899. (function (BABYLON) {
  81900. /**
  81901. * This represents a set of one or more post processes in Babylon.
  81902. * A post process can be used to apply a shader to a texture after it is rendered.
  81903. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  81904. */
  81905. var PostProcessRenderEffect = /** @class */ (function () {
  81906. /**
  81907. * Instantiates a post process render effect.
  81908. * A post process can be used to apply a shader to a texture after it is rendered.
  81909. * @param engine The engine the effect is tied to
  81910. * @param name The name of the effect
  81911. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  81912. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  81913. */
  81914. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  81915. this._name = name;
  81916. this._singleInstance = singleInstance || true;
  81917. this._getPostProcesses = getPostProcesses;
  81918. this._cameras = {};
  81919. this._indicesForCamera = {};
  81920. this._postProcesses = {};
  81921. }
  81922. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  81923. /**
  81924. * Checks if all the post processes in the effect are supported.
  81925. */
  81926. get: function () {
  81927. for (var index in this._postProcesses) {
  81928. if (this._postProcesses.hasOwnProperty(index)) {
  81929. var pps = this._postProcesses[index];
  81930. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  81931. if (!pps[ppIndex].isSupported) {
  81932. return false;
  81933. }
  81934. }
  81935. }
  81936. }
  81937. return true;
  81938. },
  81939. enumerable: true,
  81940. configurable: true
  81941. });
  81942. /**
  81943. * Updates the current state of the effect
  81944. * @hidden
  81945. */
  81946. PostProcessRenderEffect.prototype._update = function () {
  81947. };
  81948. /**
  81949. * Attaches the effect on cameras
  81950. * @param cameras The camera to attach to.
  81951. * @hidden
  81952. */
  81953. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  81954. var _this = this;
  81955. var cameraKey;
  81956. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  81957. if (!cams) {
  81958. return;
  81959. }
  81960. for (var i = 0; i < cams.length; i++) {
  81961. var camera = cams[i];
  81962. var cameraName = camera.name;
  81963. if (this._singleInstance) {
  81964. cameraKey = 0;
  81965. }
  81966. else {
  81967. cameraKey = cameraName;
  81968. }
  81969. if (!this._postProcesses[cameraKey]) {
  81970. var postProcess = this._getPostProcesses();
  81971. if (postProcess) {
  81972. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  81973. }
  81974. }
  81975. if (!this._indicesForCamera[cameraName]) {
  81976. this._indicesForCamera[cameraName] = [];
  81977. }
  81978. this._postProcesses[cameraKey].forEach(function (postProcess) {
  81979. var index = camera.attachPostProcess(postProcess);
  81980. _this._indicesForCamera[cameraName].push(index);
  81981. });
  81982. if (!this._cameras[cameraName]) {
  81983. this._cameras[cameraName] = camera;
  81984. }
  81985. }
  81986. };
  81987. /**
  81988. * Detatches the effect on cameras
  81989. * @param cameras The camera to detatch from.
  81990. * @hidden
  81991. */
  81992. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  81993. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  81994. if (!cams) {
  81995. return;
  81996. }
  81997. for (var i = 0; i < cams.length; i++) {
  81998. var camera = cams[i];
  81999. var cameraName = camera.name;
  82000. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  82001. camera.detachPostProcess(postProcess);
  82002. });
  82003. if (this._cameras[cameraName]) {
  82004. //this._indicesForCamera.splice(index, 1);
  82005. this._cameras[cameraName] = null;
  82006. }
  82007. }
  82008. };
  82009. /**
  82010. * Enables the effect on given cameras
  82011. * @param cameras The camera to enable.
  82012. * @hidden
  82013. */
  82014. PostProcessRenderEffect.prototype._enable = function (cameras) {
  82015. var _this = this;
  82016. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  82017. if (!cams) {
  82018. return;
  82019. }
  82020. for (var i = 0; i < cams.length; i++) {
  82021. var camera = cams[i];
  82022. var cameraName = camera.name;
  82023. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  82024. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  82025. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  82026. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  82027. });
  82028. }
  82029. }
  82030. }
  82031. };
  82032. /**
  82033. * Disables the effect on the given cameras
  82034. * @param cameras The camera to disable.
  82035. * @hidden
  82036. */
  82037. PostProcessRenderEffect.prototype._disable = function (cameras) {
  82038. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  82039. if (!cams) {
  82040. return;
  82041. }
  82042. for (var i = 0; i < cams.length; i++) {
  82043. var camera = cams[i];
  82044. var cameraName = camera.name;
  82045. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  82046. camera.detachPostProcess(postProcess);
  82047. });
  82048. }
  82049. };
  82050. /**
  82051. * Gets a list of the post processes contained in the effect.
  82052. * @param camera The camera to get the post processes on.
  82053. * @returns The list of the post processes in the effect.
  82054. */
  82055. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  82056. if (this._singleInstance) {
  82057. return this._postProcesses[0];
  82058. }
  82059. else {
  82060. if (!camera) {
  82061. return null;
  82062. }
  82063. return this._postProcesses[camera.name];
  82064. }
  82065. };
  82066. return PostProcessRenderEffect;
  82067. }());
  82068. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  82069. })(BABYLON || (BABYLON = {}));
  82070. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  82071. var BABYLON;
  82072. (function (BABYLON) {
  82073. /**
  82074. * PostProcessRenderPipeline
  82075. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  82076. */
  82077. var PostProcessRenderPipeline = /** @class */ (function () {
  82078. /**
  82079. * Initializes a PostProcessRenderPipeline
  82080. * @param engine engine to add the pipeline to
  82081. * @param name name of the pipeline
  82082. */
  82083. function PostProcessRenderPipeline(engine, name) {
  82084. this.engine = engine;
  82085. this._name = name;
  82086. this._renderEffects = {};
  82087. this._renderEffectsForIsolatedPass = new Array();
  82088. this._cameras = [];
  82089. }
  82090. /**
  82091. * "PostProcessRenderPipeline"
  82092. * @returns "PostProcessRenderPipeline"
  82093. */
  82094. PostProcessRenderPipeline.prototype.getClassName = function () {
  82095. return "PostProcessRenderPipeline";
  82096. };
  82097. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  82098. /**
  82099. * If all the render effects in the pipeline are support
  82100. */
  82101. get: function () {
  82102. for (var renderEffectName in this._renderEffects) {
  82103. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  82104. if (!this._renderEffects[renderEffectName].isSupported) {
  82105. return false;
  82106. }
  82107. }
  82108. }
  82109. return true;
  82110. },
  82111. enumerable: true,
  82112. configurable: true
  82113. });
  82114. /**
  82115. * Adds an effect to the pipeline
  82116. * @param renderEffect the effect to add
  82117. */
  82118. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  82119. this._renderEffects[renderEffect._name] = renderEffect;
  82120. };
  82121. // private
  82122. /** @hidden */
  82123. PostProcessRenderPipeline.prototype._rebuild = function () {
  82124. };
  82125. /** @hidden */
  82126. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  82127. var renderEffects = this._renderEffects[renderEffectName];
  82128. if (!renderEffects) {
  82129. return;
  82130. }
  82131. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  82132. };
  82133. /** @hidden */
  82134. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  82135. var renderEffects = this._renderEffects[renderEffectName];
  82136. if (!renderEffects) {
  82137. return;
  82138. }
  82139. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  82140. };
  82141. /** @hidden */
  82142. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  82143. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  82144. if (!cams) {
  82145. return;
  82146. }
  82147. var indicesToDelete = [];
  82148. var i;
  82149. for (i = 0; i < cams.length; i++) {
  82150. var camera = cams[i];
  82151. var cameraName = camera.name;
  82152. if (this._cameras.indexOf(camera) === -1) {
  82153. this._cameras[cameraName] = camera;
  82154. }
  82155. else if (unique) {
  82156. indicesToDelete.push(i);
  82157. }
  82158. }
  82159. for (i = 0; i < indicesToDelete.length; i++) {
  82160. cameras.splice(indicesToDelete[i], 1);
  82161. }
  82162. for (var renderEffectName in this._renderEffects) {
  82163. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  82164. this._renderEffects[renderEffectName]._attachCameras(cams);
  82165. }
  82166. }
  82167. };
  82168. /** @hidden */
  82169. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  82170. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  82171. if (!cams) {
  82172. return;
  82173. }
  82174. for (var renderEffectName in this._renderEffects) {
  82175. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  82176. this._renderEffects[renderEffectName]._detachCameras(cams);
  82177. }
  82178. }
  82179. for (var i = 0; i < cams.length; i++) {
  82180. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  82181. }
  82182. };
  82183. /** @hidden */
  82184. PostProcessRenderPipeline.prototype._update = function () {
  82185. for (var renderEffectName in this._renderEffects) {
  82186. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  82187. this._renderEffects[renderEffectName]._update();
  82188. }
  82189. }
  82190. for (var i = 0; i < this._cameras.length; i++) {
  82191. var cameraName = this._cameras[i].name;
  82192. if (this._renderEffectsForIsolatedPass[cameraName]) {
  82193. this._renderEffectsForIsolatedPass[cameraName]._update();
  82194. }
  82195. }
  82196. };
  82197. /** @hidden */
  82198. PostProcessRenderPipeline.prototype._reset = function () {
  82199. this._renderEffects = {};
  82200. this._renderEffectsForIsolatedPass = new Array();
  82201. };
  82202. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  82203. // 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)
  82204. var effectKeys = Object.keys(this._renderEffects);
  82205. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  82206. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  82207. if (postProcesses) {
  82208. postProcesses[0].samples = sampleCount;
  82209. return true;
  82210. }
  82211. }
  82212. return false;
  82213. };
  82214. /**
  82215. * Disposes of the pipeline
  82216. */
  82217. PostProcessRenderPipeline.prototype.dispose = function () {
  82218. // Must be implemented by children
  82219. };
  82220. __decorate([
  82221. BABYLON.serialize()
  82222. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  82223. return PostProcessRenderPipeline;
  82224. }());
  82225. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  82226. })(BABYLON || (BABYLON = {}));
  82227. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  82228. var BABYLON;
  82229. (function (BABYLON) {
  82230. /**
  82231. * This represents a depth renderer in Babylon.
  82232. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  82233. */
  82234. var DepthRenderer = /** @class */ (function () {
  82235. /**
  82236. * Instantiates a depth renderer
  82237. * @param scene The scene the renderer belongs to
  82238. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  82239. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  82240. */
  82241. function DepthRenderer(scene, type, camera) {
  82242. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  82243. if (camera === void 0) { camera = null; }
  82244. var _this = this;
  82245. /**
  82246. * Specifiess that the depth renderer will only be used within
  82247. * the camera it is created for.
  82248. * This can help forcing its rendering during the camera processing.
  82249. */
  82250. this.useOnlyInActiveCamera = false;
  82251. this._scene = scene;
  82252. // Register the G Buffer component to the scene.
  82253. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  82254. if (!component) {
  82255. component = new BABYLON.DepthRendererSceneComponent(scene);
  82256. scene._addComponent(component);
  82257. }
  82258. this._camera = camera;
  82259. var engine = scene.getEngine();
  82260. // Render target
  82261. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  82262. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82263. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82264. this._depthMap.refreshRate = 1;
  82265. this._depthMap.renderParticles = false;
  82266. this._depthMap.renderList = null;
  82267. // Camera to get depth map from to support multiple concurrent cameras
  82268. this._depthMap.activeCamera = this._camera;
  82269. this._depthMap.ignoreCameraViewport = true;
  82270. this._depthMap.useCameraPostProcesses = false;
  82271. // set default depth value to 1.0 (far away)
  82272. this._depthMap.onClearObservable.add(function (engine) {
  82273. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  82274. });
  82275. // Custom render function
  82276. var renderSubMesh = function (subMesh) {
  82277. var mesh = subMesh.getRenderingMesh();
  82278. var scene = _this._scene;
  82279. var engine = scene.getEngine();
  82280. var material = subMesh.getMaterial();
  82281. if (!material) {
  82282. return;
  82283. }
  82284. // Culling and reverse (right handed system)
  82285. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  82286. // Managing instances
  82287. var batch = mesh._getInstancesRenderList(subMesh._id);
  82288. if (batch.mustReturn) {
  82289. return;
  82290. }
  82291. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  82292. var camera = _this._camera || scene.activeCamera;
  82293. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  82294. engine.enableEffect(_this._effect);
  82295. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  82296. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  82297. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  82298. // Alpha test
  82299. if (material && material.needAlphaTesting()) {
  82300. var alphaTexture = material.getAlphaTestTexture();
  82301. if (alphaTexture) {
  82302. _this._effect.setTexture("diffuseSampler", alphaTexture);
  82303. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  82304. }
  82305. }
  82306. // Bones
  82307. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  82308. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  82309. }
  82310. // Draw
  82311. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  82312. }
  82313. };
  82314. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  82315. var index;
  82316. if (depthOnlySubMeshes.length) {
  82317. engine.setColorWrite(false);
  82318. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  82319. renderSubMesh(depthOnlySubMeshes.data[index]);
  82320. }
  82321. engine.setColorWrite(true);
  82322. }
  82323. for (index = 0; index < opaqueSubMeshes.length; index++) {
  82324. renderSubMesh(opaqueSubMeshes.data[index]);
  82325. }
  82326. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  82327. renderSubMesh(alphaTestSubMeshes.data[index]);
  82328. }
  82329. };
  82330. }
  82331. /**
  82332. * Creates the depth rendering effect and checks if the effect is ready.
  82333. * @param subMesh The submesh to be used to render the depth map of
  82334. * @param useInstances If multiple world instances should be used
  82335. * @returns if the depth renderer is ready to render the depth map
  82336. */
  82337. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  82338. var material = subMesh.getMaterial();
  82339. if (material.disableDepthWrite) {
  82340. return false;
  82341. }
  82342. var defines = [];
  82343. var attribs = [BABYLON.VertexBuffer.PositionKind];
  82344. var mesh = subMesh.getMesh();
  82345. // Alpha test
  82346. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  82347. defines.push("#define ALPHATEST");
  82348. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82349. attribs.push(BABYLON.VertexBuffer.UVKind);
  82350. defines.push("#define UV1");
  82351. }
  82352. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  82353. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  82354. defines.push("#define UV2");
  82355. }
  82356. }
  82357. // Bones
  82358. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  82359. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  82360. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  82361. if (mesh.numBoneInfluencers > 4) {
  82362. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  82363. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  82364. }
  82365. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  82366. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  82367. }
  82368. else {
  82369. defines.push("#define NUM_BONE_INFLUENCERS 0");
  82370. }
  82371. // Instances
  82372. if (useInstances) {
  82373. defines.push("#define INSTANCES");
  82374. attribs.push("world0");
  82375. attribs.push("world1");
  82376. attribs.push("world2");
  82377. attribs.push("world3");
  82378. }
  82379. // Get correct effect
  82380. var join = defines.join("\n");
  82381. if (this._cachedDefines !== join) {
  82382. this._cachedDefines = join;
  82383. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  82384. }
  82385. return this._effect.isReady();
  82386. };
  82387. /**
  82388. * Gets the texture which the depth map will be written to.
  82389. * @returns The depth map texture
  82390. */
  82391. DepthRenderer.prototype.getDepthMap = function () {
  82392. return this._depthMap;
  82393. };
  82394. /**
  82395. * Disposes of the depth renderer.
  82396. */
  82397. DepthRenderer.prototype.dispose = function () {
  82398. this._depthMap.dispose();
  82399. };
  82400. return DepthRenderer;
  82401. }());
  82402. BABYLON.DepthRenderer = DepthRenderer;
  82403. })(BABYLON || (BABYLON = {}));
  82404. //# sourceMappingURL=babylon.depthRenderer.js.map
  82405. var BABYLON;
  82406. (function (BABYLON) {
  82407. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  82408. camera = camera || this.activeCamera;
  82409. if (!camera) {
  82410. throw "No camera available to enable depth renderer";
  82411. }
  82412. if (!this._depthRenderer) {
  82413. this._depthRenderer = {};
  82414. }
  82415. if (!this._depthRenderer[camera.id]) {
  82416. var textureType = 0;
  82417. if (this.getEngine().getCaps().textureHalfFloatRender) {
  82418. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82419. }
  82420. else if (this.getEngine().getCaps().textureFloatRender) {
  82421. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82422. }
  82423. else {
  82424. throw "Depth renderer does not support int texture type";
  82425. }
  82426. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  82427. }
  82428. return this._depthRenderer[camera.id];
  82429. };
  82430. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  82431. camera = camera || this.activeCamera;
  82432. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  82433. return;
  82434. }
  82435. this._depthRenderer[camera.id].dispose();
  82436. delete this._depthRenderer[camera.id];
  82437. };
  82438. /**
  82439. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  82440. * in several rendering techniques.
  82441. */
  82442. var DepthRendererSceneComponent = /** @class */ (function () {
  82443. /**
  82444. * Creates a new instance of the component for the given scene
  82445. * @param scene Defines the scene to register the component in
  82446. */
  82447. function DepthRendererSceneComponent(scene) {
  82448. /**
  82449. * The component name helpfull to identify the component in the list of scene components.
  82450. */
  82451. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  82452. this.scene = scene;
  82453. }
  82454. /**
  82455. * Registers the component in a given scene
  82456. */
  82457. DepthRendererSceneComponent.prototype.register = function () {
  82458. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  82459. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  82460. };
  82461. /**
  82462. * Rebuilds the elements related to this component in case of
  82463. * context lost for instance.
  82464. */
  82465. DepthRendererSceneComponent.prototype.rebuild = function () {
  82466. // Nothing to do for this component
  82467. };
  82468. /**
  82469. * Disposes the component and the associated ressources
  82470. */
  82471. DepthRendererSceneComponent.prototype.dispose = function () {
  82472. for (var key in this.scene._depthRenderer) {
  82473. this.scene._depthRenderer[key].dispose();
  82474. }
  82475. };
  82476. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  82477. if (this.scene._depthRenderer) {
  82478. for (var key in this.scene._depthRenderer) {
  82479. var depthRenderer = this.scene._depthRenderer[key];
  82480. if (!depthRenderer.useOnlyInActiveCamera) {
  82481. renderTargets.push(depthRenderer.getDepthMap());
  82482. }
  82483. }
  82484. }
  82485. };
  82486. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  82487. if (this.scene._depthRenderer) {
  82488. for (var key in this.scene._depthRenderer) {
  82489. var depthRenderer = this.scene._depthRenderer[key];
  82490. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  82491. renderTargets.push(depthRenderer.getDepthMap());
  82492. }
  82493. }
  82494. }
  82495. };
  82496. return DepthRendererSceneComponent;
  82497. }());
  82498. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  82499. })(BABYLON || (BABYLON = {}));
  82500. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  82501. var BABYLON;
  82502. (function (BABYLON) {
  82503. /**
  82504. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  82505. */
  82506. var GeometryBufferRenderer = /** @class */ (function () {
  82507. /**
  82508. * Creates a new G Buffer for the scene
  82509. * @param scene The scene the buffer belongs to
  82510. * @param ratio How big is the buffer related to the main canvas.
  82511. */
  82512. function GeometryBufferRenderer(scene, ratio) {
  82513. if (ratio === void 0) { ratio = 1; }
  82514. this._enablePosition = false;
  82515. this._scene = scene;
  82516. this._ratio = ratio;
  82517. // Register the G Buffer component to the scene.
  82518. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  82519. if (!component) {
  82520. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  82521. scene._addComponent(component);
  82522. }
  82523. // Render target
  82524. this._createRenderTargets();
  82525. }
  82526. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  82527. /**
  82528. * Set the render list (meshes to be rendered) used in the G buffer.
  82529. */
  82530. set: function (meshes) {
  82531. this._multiRenderTarget.renderList = meshes;
  82532. },
  82533. enumerable: true,
  82534. configurable: true
  82535. });
  82536. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  82537. /**
  82538. * Gets wether or not G buffer are supported by the running hardware.
  82539. * This requires draw buffer supports
  82540. */
  82541. get: function () {
  82542. return this._multiRenderTarget.isSupported;
  82543. },
  82544. enumerable: true,
  82545. configurable: true
  82546. });
  82547. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  82548. /**
  82549. * Gets wether or not position are enabled for the G buffer.
  82550. */
  82551. get: function () {
  82552. return this._enablePosition;
  82553. },
  82554. /**
  82555. * Sets wether or not position are enabled for the G buffer.
  82556. */
  82557. set: function (enable) {
  82558. this._enablePosition = enable;
  82559. this.dispose();
  82560. this._createRenderTargets();
  82561. },
  82562. enumerable: true,
  82563. configurable: true
  82564. });
  82565. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  82566. /**
  82567. * Gets the scene associated with the buffer.
  82568. */
  82569. get: function () {
  82570. return this._scene;
  82571. },
  82572. enumerable: true,
  82573. configurable: true
  82574. });
  82575. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  82576. /**
  82577. * Gets the ratio used by the buffer during its creation.
  82578. * How big is the buffer related to the main canvas.
  82579. */
  82580. get: function () {
  82581. return this._ratio;
  82582. },
  82583. enumerable: true,
  82584. configurable: true
  82585. });
  82586. /**
  82587. * Checks wether everything is ready to render a submesh to the G buffer.
  82588. * @param subMesh the submesh to check readiness for
  82589. * @param useInstances is the mesh drawn using instance or not
  82590. * @returns true if ready otherwise false
  82591. */
  82592. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  82593. var material = subMesh.getMaterial();
  82594. if (material && material.disableDepthWrite) {
  82595. return false;
  82596. }
  82597. var defines = [];
  82598. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  82599. var mesh = subMesh.getMesh();
  82600. // Alpha test
  82601. if (material && material.needAlphaTesting()) {
  82602. defines.push("#define ALPHATEST");
  82603. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82604. attribs.push(BABYLON.VertexBuffer.UVKind);
  82605. defines.push("#define UV1");
  82606. }
  82607. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  82608. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  82609. defines.push("#define UV2");
  82610. }
  82611. }
  82612. // Buffers
  82613. if (this._enablePosition) {
  82614. defines.push("#define POSITION");
  82615. }
  82616. // Bones
  82617. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  82618. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  82619. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  82620. if (mesh.numBoneInfluencers > 4) {
  82621. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  82622. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  82623. }
  82624. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  82625. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  82626. }
  82627. else {
  82628. defines.push("#define NUM_BONE_INFLUENCERS 0");
  82629. }
  82630. // Instances
  82631. if (useInstances) {
  82632. defines.push("#define INSTANCES");
  82633. attribs.push("world0");
  82634. attribs.push("world1");
  82635. attribs.push("world2");
  82636. attribs.push("world3");
  82637. }
  82638. // Get correct effect
  82639. var join = defines.join("\n");
  82640. if (this._cachedDefines !== join) {
  82641. this._cachedDefines = join;
  82642. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  82643. }
  82644. return this._effect.isReady();
  82645. };
  82646. /**
  82647. * Gets the current underlying G Buffer.
  82648. * @returns the buffer
  82649. */
  82650. GeometryBufferRenderer.prototype.getGBuffer = function () {
  82651. return this._multiRenderTarget;
  82652. };
  82653. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  82654. /**
  82655. * Gets the number of samples used to render the buffer (anti aliasing).
  82656. */
  82657. get: function () {
  82658. return this._multiRenderTarget.samples;
  82659. },
  82660. /**
  82661. * Sets the number of samples used to render the buffer (anti aliasing).
  82662. */
  82663. set: function (value) {
  82664. this._multiRenderTarget.samples = value;
  82665. },
  82666. enumerable: true,
  82667. configurable: true
  82668. });
  82669. /**
  82670. * Disposes the renderer and frees up associated resources.
  82671. */
  82672. GeometryBufferRenderer.prototype.dispose = function () {
  82673. this.getGBuffer().dispose();
  82674. };
  82675. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  82676. var _this = this;
  82677. var engine = this._scene.getEngine();
  82678. var count = this._enablePosition ? 3 : 2;
  82679. 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 });
  82680. if (!this.isSupported) {
  82681. return;
  82682. }
  82683. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82684. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82685. this._multiRenderTarget.refreshRate = 1;
  82686. this._multiRenderTarget.renderParticles = false;
  82687. this._multiRenderTarget.renderList = null;
  82688. // set default depth value to 1.0 (far away)
  82689. this._multiRenderTarget.onClearObservable.add(function (engine) {
  82690. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  82691. });
  82692. // Custom render function
  82693. var renderSubMesh = function (subMesh) {
  82694. var mesh = subMesh.getRenderingMesh();
  82695. var scene = _this._scene;
  82696. var engine = scene.getEngine();
  82697. var material = subMesh.getMaterial();
  82698. if (!material) {
  82699. return;
  82700. }
  82701. // Culling
  82702. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  82703. // Managing instances
  82704. var batch = mesh._getInstancesRenderList(subMesh._id);
  82705. if (batch.mustReturn) {
  82706. return;
  82707. }
  82708. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  82709. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  82710. engine.enableEffect(_this._effect);
  82711. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  82712. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  82713. _this._effect.setMatrix("view", scene.getViewMatrix());
  82714. // Alpha test
  82715. if (material && material.needAlphaTesting()) {
  82716. var alphaTexture = material.getAlphaTestTexture();
  82717. if (alphaTexture) {
  82718. _this._effect.setTexture("diffuseSampler", alphaTexture);
  82719. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  82720. }
  82721. }
  82722. // Bones
  82723. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  82724. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  82725. }
  82726. // Draw
  82727. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  82728. }
  82729. };
  82730. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  82731. var index;
  82732. if (depthOnlySubMeshes.length) {
  82733. engine.setColorWrite(false);
  82734. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  82735. renderSubMesh(depthOnlySubMeshes.data[index]);
  82736. }
  82737. engine.setColorWrite(true);
  82738. }
  82739. for (index = 0; index < opaqueSubMeshes.length; index++) {
  82740. renderSubMesh(opaqueSubMeshes.data[index]);
  82741. }
  82742. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  82743. renderSubMesh(alphaTestSubMeshes.data[index]);
  82744. }
  82745. };
  82746. };
  82747. return GeometryBufferRenderer;
  82748. }());
  82749. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  82750. })(BABYLON || (BABYLON = {}));
  82751. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  82752. var BABYLON;
  82753. (function (BABYLON) {
  82754. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  82755. get: function () {
  82756. this._geometryBufferRenderer;
  82757. },
  82758. set: function (value) {
  82759. if (value && value.isSupported) {
  82760. this._geometryBufferRenderer = value;
  82761. }
  82762. ;
  82763. },
  82764. enumerable: true,
  82765. configurable: true
  82766. });
  82767. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  82768. if (ratio === void 0) { ratio = 1; }
  82769. if (this._geometryBufferRenderer) {
  82770. return this._geometryBufferRenderer;
  82771. }
  82772. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  82773. if (!this._geometryBufferRenderer.isSupported) {
  82774. this._geometryBufferRenderer = null;
  82775. }
  82776. return this._geometryBufferRenderer;
  82777. };
  82778. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  82779. if (!this._geometryBufferRenderer) {
  82780. return;
  82781. }
  82782. this._geometryBufferRenderer.dispose();
  82783. this._geometryBufferRenderer = null;
  82784. };
  82785. /**
  82786. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
  82787. * in several rendering techniques.
  82788. */
  82789. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  82790. /**
  82791. * Creates a new instance of the component for the given scene
  82792. * @param scene Defines the scene to register the component in
  82793. */
  82794. function GeometryBufferRendererSceneComponent(scene) {
  82795. /**
  82796. * The component name helpful to identify the component in the list of scene components.
  82797. */
  82798. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  82799. this.scene = scene;
  82800. }
  82801. /**
  82802. * Registers the component in a given scene
  82803. */
  82804. GeometryBufferRendererSceneComponent.prototype.register = function () {
  82805. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  82806. };
  82807. /**
  82808. * Rebuilds the elements related to this component in case of
  82809. * context lost for instance.
  82810. */
  82811. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  82812. // Nothing to do for this component
  82813. };
  82814. /**
  82815. * Disposes the component and the associated ressources
  82816. */
  82817. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  82818. // Nothing to do for this component
  82819. };
  82820. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  82821. if (this.scene._geometryBufferRenderer) {
  82822. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  82823. }
  82824. };
  82825. return GeometryBufferRendererSceneComponent;
  82826. }());
  82827. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  82828. })(BABYLON || (BABYLON = {}));
  82829. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  82830. var BABYLON;
  82831. (function (BABYLON) {
  82832. var SSAORenderingPipeline = /** @class */ (function (_super) {
  82833. __extends(SSAORenderingPipeline, _super);
  82834. /**
  82835. * @constructor
  82836. * @param {string} name - The rendering pipeline name
  82837. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  82838. * @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 }
  82839. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  82840. */
  82841. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  82842. var _this = _super.call(this, scene.getEngine(), name) || this;
  82843. // Members
  82844. /**
  82845. * The PassPostProcess id in the pipeline that contains the original scene color
  82846. */
  82847. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  82848. /**
  82849. * The SSAO PostProcess id in the pipeline
  82850. */
  82851. _this.SSAORenderEffect = "SSAORenderEffect";
  82852. /**
  82853. * The horizontal blur PostProcess id in the pipeline
  82854. */
  82855. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  82856. /**
  82857. * The vertical blur PostProcess id in the pipeline
  82858. */
  82859. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  82860. /**
  82861. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  82862. */
  82863. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  82864. /**
  82865. * The output strength of the SSAO post-process. Default value is 1.0.
  82866. */
  82867. _this.totalStrength = 1.0;
  82868. /**
  82869. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  82870. */
  82871. _this.radius = 0.0001;
  82872. /**
  82873. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  82874. * Must not be equal to fallOff and superior to fallOff.
  82875. * Default value is 0.975
  82876. */
  82877. _this.area = 0.0075;
  82878. /**
  82879. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  82880. * Must not be equal to area and inferior to area.
  82881. * Default value is 0.0
  82882. */
  82883. _this.fallOff = 0.000001;
  82884. /**
  82885. * The base color of the SSAO post-process
  82886. * The final result is "base + ssao" between [0, 1]
  82887. */
  82888. _this.base = 0.5;
  82889. _this._firstUpdate = true;
  82890. _this._scene = scene;
  82891. // Set up assets
  82892. _this._createRandomTexture();
  82893. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  82894. var ssaoRatio = ratio.ssaoRatio || ratio;
  82895. var combineRatio = ratio.combineRatio || ratio;
  82896. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  82897. _this._createSSAOPostProcess(ssaoRatio);
  82898. _this._createBlurPostProcess(ssaoRatio);
  82899. _this._createSSAOCombinePostProcess(combineRatio);
  82900. // Set up pipeline
  82901. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  82902. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  82903. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  82904. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  82905. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  82906. // Finish
  82907. scene.postProcessRenderPipelineManager.addPipeline(_this);
  82908. if (cameras)
  82909. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  82910. return _this;
  82911. }
  82912. // Public Methods
  82913. /**
  82914. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  82915. */
  82916. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  82917. if (disableDepthRender === void 0) { disableDepthRender = false; }
  82918. for (var i = 0; i < this._scene.cameras.length; i++) {
  82919. var camera = this._scene.cameras[i];
  82920. this._originalColorPostProcess.dispose(camera);
  82921. this._ssaoPostProcess.dispose(camera);
  82922. this._blurHPostProcess.dispose(camera);
  82923. this._blurVPostProcess.dispose(camera);
  82924. this._ssaoCombinePostProcess.dispose(camera);
  82925. }
  82926. this._randomTexture.dispose();
  82927. if (disableDepthRender)
  82928. this._scene.disableDepthRenderer();
  82929. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  82930. _super.prototype.dispose.call(this);
  82931. };
  82932. // Private Methods
  82933. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  82934. var _this = this;
  82935. var size = 16;
  82936. 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);
  82937. 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);
  82938. this._blurHPostProcess.onActivateObservable.add(function () {
  82939. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  82940. _this._blurHPostProcess.kernel = size * dw;
  82941. });
  82942. this._blurVPostProcess.onActivateObservable.add(function () {
  82943. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  82944. _this._blurVPostProcess.kernel = size * dw;
  82945. });
  82946. };
  82947. /** @hidden */
  82948. SSAORenderingPipeline.prototype._rebuild = function () {
  82949. this._firstUpdate = true;
  82950. _super.prototype._rebuild.call(this);
  82951. };
  82952. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  82953. var _this = this;
  82954. var numSamples = 16;
  82955. var sampleSphere = [
  82956. 0.5381, 0.1856, -0.4319,
  82957. 0.1379, 0.2486, 0.4430,
  82958. 0.3371, 0.5679, -0.0057,
  82959. -0.6999, -0.0451, -0.0019,
  82960. 0.0689, -0.1598, -0.8547,
  82961. 0.0560, 0.0069, -0.1843,
  82962. -0.0146, 0.1402, 0.0762,
  82963. 0.0100, -0.1924, -0.0344,
  82964. -0.3577, -0.5301, -0.4358,
  82965. -0.3169, 0.1063, 0.0158,
  82966. 0.0103, -0.5869, 0.0046,
  82967. -0.0897, -0.4940, 0.3287,
  82968. 0.7119, -0.0154, -0.0918,
  82969. -0.0533, 0.0596, -0.5411,
  82970. 0.0352, -0.0631, 0.5460,
  82971. -0.4776, 0.2847, -0.0271
  82972. ];
  82973. var samplesFactor = 1.0 / numSamples;
  82974. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  82975. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  82976. "area", "fallOff", "base", "range", "viewport"
  82977. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  82978. this._ssaoPostProcess.onApply = function (effect) {
  82979. if (_this._firstUpdate) {
  82980. effect.setArray3("sampleSphere", sampleSphere);
  82981. effect.setFloat("samplesFactor", samplesFactor);
  82982. effect.setFloat("randTextureTiles", 4.0);
  82983. }
  82984. effect.setFloat("totalStrength", _this.totalStrength);
  82985. effect.setFloat("radius", _this.radius);
  82986. effect.setFloat("area", _this.area);
  82987. effect.setFloat("fallOff", _this.fallOff);
  82988. effect.setFloat("base", _this.base);
  82989. effect.setTexture("textureSampler", _this._depthTexture);
  82990. effect.setTexture("randomSampler", _this._randomTexture);
  82991. };
  82992. };
  82993. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  82994. var _this = this;
  82995. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  82996. this._ssaoCombinePostProcess.onApply = function (effect) {
  82997. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  82998. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  82999. };
  83000. };
  83001. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  83002. var size = 512;
  83003. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  83004. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  83005. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  83006. var context = this._randomTexture.getContext();
  83007. var rand = function (min, max) {
  83008. return Math.random() * (max - min) + min;
  83009. };
  83010. var randVector = BABYLON.Vector3.Zero();
  83011. for (var x = 0; x < size; x++) {
  83012. for (var y = 0; y < size; y++) {
  83013. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  83014. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  83015. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  83016. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  83017. context.fillRect(x, y, 1, 1);
  83018. }
  83019. }
  83020. this._randomTexture.update(false);
  83021. };
  83022. __decorate([
  83023. BABYLON.serialize()
  83024. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  83025. __decorate([
  83026. BABYLON.serialize()
  83027. ], SSAORenderingPipeline.prototype, "radius", void 0);
  83028. __decorate([
  83029. BABYLON.serialize()
  83030. ], SSAORenderingPipeline.prototype, "area", void 0);
  83031. __decorate([
  83032. BABYLON.serialize()
  83033. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  83034. __decorate([
  83035. BABYLON.serialize()
  83036. ], SSAORenderingPipeline.prototype, "base", void 0);
  83037. return SSAORenderingPipeline;
  83038. }(BABYLON.PostProcessRenderPipeline));
  83039. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  83040. })(BABYLON || (BABYLON = {}));
  83041. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  83042. var BABYLON;
  83043. (function (BABYLON) {
  83044. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  83045. __extends(SSAO2RenderingPipeline, _super);
  83046. /**
  83047. * @constructor
  83048. * @param {string} name - The rendering pipeline name
  83049. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  83050. * @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 }
  83051. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  83052. */
  83053. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  83054. var _this = _super.call(this, scene.getEngine(), name) || this;
  83055. // Members
  83056. /**
  83057. * The PassPostProcess id in the pipeline that contains the original scene color
  83058. */
  83059. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  83060. /**
  83061. * The SSAO PostProcess id in the pipeline
  83062. */
  83063. _this.SSAORenderEffect = "SSAORenderEffect";
  83064. /**
  83065. * The horizontal blur PostProcess id in the pipeline
  83066. */
  83067. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  83068. /**
  83069. * The vertical blur PostProcess id in the pipeline
  83070. */
  83071. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  83072. /**
  83073. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  83074. */
  83075. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  83076. /**
  83077. * The output strength of the SSAO post-process. Default value is 1.0.
  83078. */
  83079. _this.totalStrength = 1.0;
  83080. /**
  83081. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  83082. */
  83083. _this.maxZ = 100.0;
  83084. /**
  83085. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  83086. */
  83087. _this.minZAspect = 0.2;
  83088. _this._samples = 8;
  83089. _this._textureSamples = 1;
  83090. /**
  83091. * Are we using bilateral blur ?
  83092. */
  83093. _this._expensiveBlur = true;
  83094. /**
  83095. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  83096. */
  83097. _this.radius = 2.0;
  83098. /**
  83099. * The base color of the SSAO post-process
  83100. * The final result is "base + ssao" between [0, 1]
  83101. */
  83102. _this.base = 0;
  83103. _this._firstUpdate = true;
  83104. _this._bits = new Uint32Array(1);
  83105. _this._scene = scene;
  83106. _this._ratio = ratio;
  83107. if (!_this.isSupported) {
  83108. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  83109. return _this;
  83110. }
  83111. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  83112. var blurRatio = _this._ratio.blurRatio || ratio;
  83113. // Set up assets
  83114. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  83115. _this._createRandomTexture();
  83116. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  83117. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  83118. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  83119. _this._originalColorPostProcess.samples = _this.textureSamples;
  83120. _this._createSSAOPostProcess(1.0);
  83121. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  83122. _this._createSSAOCombinePostProcess(blurRatio);
  83123. // Set up pipeline
  83124. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  83125. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  83126. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  83127. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  83128. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  83129. // Finish
  83130. scene.postProcessRenderPipelineManager.addPipeline(_this);
  83131. if (cameras)
  83132. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  83133. return _this;
  83134. }
  83135. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  83136. get: function () {
  83137. return this._samples;
  83138. },
  83139. /**
  83140. * Number of samples used for the SSAO calculations. Default value is 8
  83141. */
  83142. set: function (n) {
  83143. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  83144. this._samples = n;
  83145. this._sampleSphere = this._generateHemisphere();
  83146. this._firstUpdate = true;
  83147. },
  83148. enumerable: true,
  83149. configurable: true
  83150. });
  83151. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  83152. get: function () {
  83153. return this._textureSamples;
  83154. },
  83155. /**
  83156. * Number of samples to use for antialiasing
  83157. */
  83158. set: function (n) {
  83159. this._textureSamples = n;
  83160. this._originalColorPostProcess.samples = n;
  83161. this._blurHPostProcess.samples = n;
  83162. this._blurVPostProcess.samples = n;
  83163. this._ssaoPostProcess.samples = n;
  83164. this._ssaoCombinePostProcess.samples = n;
  83165. },
  83166. enumerable: true,
  83167. configurable: true
  83168. });
  83169. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  83170. get: function () {
  83171. return this._expensiveBlur;
  83172. },
  83173. set: function (b) {
  83174. 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"]);
  83175. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  83176. this._expensiveBlur = b;
  83177. this._firstUpdate = true;
  83178. },
  83179. enumerable: true,
  83180. configurable: true
  83181. });
  83182. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  83183. /**
  83184. * Support test.
  83185. */
  83186. get: function () {
  83187. var engine = BABYLON.Engine.LastCreatedEngine;
  83188. if (!engine) {
  83189. return false;
  83190. }
  83191. return engine.getCaps().drawBuffersExtension;
  83192. },
  83193. enumerable: true,
  83194. configurable: true
  83195. });
  83196. // Public Methods
  83197. /**
  83198. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  83199. */
  83200. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  83201. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  83202. for (var i = 0; i < this._scene.cameras.length; i++) {
  83203. var camera = this._scene.cameras[i];
  83204. this._originalColorPostProcess.dispose(camera);
  83205. this._ssaoPostProcess.dispose(camera);
  83206. this._blurHPostProcess.dispose(camera);
  83207. this._blurVPostProcess.dispose(camera);
  83208. this._ssaoCombinePostProcess.dispose(camera);
  83209. }
  83210. this._randomTexture.dispose();
  83211. if (disableGeometryBufferRenderer)
  83212. this._scene.disableGeometryBufferRenderer();
  83213. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  83214. _super.prototype.dispose.call(this);
  83215. };
  83216. // Private Methods
  83217. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  83218. var _this = this;
  83219. this._samplerOffsets = [];
  83220. var expensive = this.expensiveBlur;
  83221. for (var i = -8; i < 8; i++) {
  83222. this._samplerOffsets.push(i * 2 + 0.5);
  83223. }
  83224. 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");
  83225. this._blurHPostProcess.onApply = function (effect) {
  83226. if (!_this._scene.activeCamera) {
  83227. return;
  83228. }
  83229. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  83230. effect.setFloat("near", _this._scene.activeCamera.minZ);
  83231. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  83232. effect.setFloat("radius", _this.radius);
  83233. effect.setTexture("depthSampler", _this._depthTexture);
  83234. if (_this._firstUpdate) {
  83235. effect.setArray("samplerOffsets", _this._samplerOffsets);
  83236. }
  83237. };
  83238. 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");
  83239. this._blurVPostProcess.onApply = function (effect) {
  83240. if (!_this._scene.activeCamera) {
  83241. return;
  83242. }
  83243. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  83244. effect.setFloat("near", _this._scene.activeCamera.minZ);
  83245. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  83246. effect.setFloat("radius", _this.radius);
  83247. effect.setTexture("depthSampler", _this._depthTexture);
  83248. if (_this._firstUpdate) {
  83249. effect.setArray("samplerOffsets", _this._samplerOffsets);
  83250. _this._firstUpdate = false;
  83251. }
  83252. };
  83253. this._blurHPostProcess.samples = this.textureSamples;
  83254. this._blurVPostProcess.samples = this.textureSamples;
  83255. };
  83256. /** @hidden */
  83257. SSAO2RenderingPipeline.prototype._rebuild = function () {
  83258. this._firstUpdate = true;
  83259. _super.prototype._rebuild.call(this);
  83260. };
  83261. //Van der Corput radical inverse
  83262. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  83263. this._bits[0] = i;
  83264. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  83265. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  83266. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  83267. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  83268. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  83269. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  83270. };
  83271. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  83272. return [i / n, this._radicalInverse_VdC(i)];
  83273. };
  83274. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  83275. var phi = v * 2.0 * Math.PI;
  83276. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  83277. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  83278. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  83279. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  83280. };
  83281. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  83282. var numSamples = this.samples;
  83283. var result = [];
  83284. var vector;
  83285. var i = 0;
  83286. while (i < numSamples) {
  83287. if (numSamples < 16) {
  83288. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  83289. }
  83290. else {
  83291. var rand = this._hammersley(i, numSamples);
  83292. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  83293. }
  83294. result.push(vector.x, vector.y, vector.z);
  83295. i++;
  83296. }
  83297. return result;
  83298. };
  83299. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  83300. var _this = this;
  83301. var numSamples = this.samples;
  83302. this._sampleSphere = this._generateHemisphere();
  83303. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  83304. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  83305. "base", "range", "projection", "near", "far", "texelSize",
  83306. "xViewport", "yViewport", "maxZ", "minZAspect"
  83307. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  83308. this._ssaoPostProcess.onApply = function (effect) {
  83309. if (_this._firstUpdate) {
  83310. effect.setArray3("sampleSphere", _this._sampleSphere);
  83311. effect.setFloat("randTextureTiles", 32.0);
  83312. }
  83313. if (!_this._scene.activeCamera) {
  83314. return;
  83315. }
  83316. effect.setFloat("samplesFactor", 1 / _this.samples);
  83317. effect.setFloat("totalStrength", _this.totalStrength);
  83318. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  83319. effect.setFloat("radius", _this.radius);
  83320. effect.setFloat("maxZ", _this.maxZ);
  83321. effect.setFloat("minZAspect", _this.minZAspect);
  83322. effect.setFloat("base", _this.base);
  83323. effect.setFloat("near", _this._scene.activeCamera.minZ);
  83324. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  83325. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  83326. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  83327. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  83328. effect.setTexture("textureSampler", _this._depthTexture);
  83329. effect.setTexture("normalSampler", _this._normalTexture);
  83330. effect.setTexture("randomSampler", _this._randomTexture);
  83331. };
  83332. this._ssaoPostProcess.samples = this.textureSamples;
  83333. };
  83334. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  83335. var _this = this;
  83336. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  83337. this._ssaoCombinePostProcess.onApply = function (effect) {
  83338. var viewport = _this._scene.activeCamera.viewport;
  83339. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  83340. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  83341. };
  83342. this._ssaoCombinePostProcess.samples = this.textureSamples;
  83343. };
  83344. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  83345. var size = 128;
  83346. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  83347. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  83348. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  83349. var context = this._randomTexture.getContext();
  83350. var rand = function (min, max) {
  83351. return Math.random() * (max - min) + min;
  83352. };
  83353. var randVector = BABYLON.Vector3.Zero();
  83354. for (var x = 0; x < size; x++) {
  83355. for (var y = 0; y < size; y++) {
  83356. randVector.x = rand(0.0, 1.0);
  83357. randVector.y = rand(0.0, 1.0);
  83358. randVector.z = 0.0;
  83359. randVector.normalize();
  83360. randVector.scaleInPlace(255);
  83361. randVector.x = Math.floor(randVector.x);
  83362. randVector.y = Math.floor(randVector.y);
  83363. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  83364. context.fillRect(x, y, 1, 1);
  83365. }
  83366. }
  83367. this._randomTexture.update(false);
  83368. };
  83369. /**
  83370. * Serialize the rendering pipeline (Used when exporting)
  83371. * @returns the serialized object
  83372. */
  83373. SSAO2RenderingPipeline.prototype.serialize = function () {
  83374. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  83375. serializationObject.customType = "SSAO2RenderingPipeline";
  83376. return serializationObject;
  83377. };
  83378. /**
  83379. * Parse the serialized pipeline
  83380. * @param source Source pipeline.
  83381. * @param scene The scene to load the pipeline to.
  83382. * @param rootUrl The URL of the serialized pipeline.
  83383. * @returns An instantiated pipeline from the serialized object.
  83384. */
  83385. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  83386. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  83387. };
  83388. __decorate([
  83389. BABYLON.serialize()
  83390. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  83391. __decorate([
  83392. BABYLON.serialize()
  83393. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  83394. __decorate([
  83395. BABYLON.serialize()
  83396. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  83397. __decorate([
  83398. BABYLON.serialize("samples")
  83399. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  83400. __decorate([
  83401. BABYLON.serialize("textureSamples")
  83402. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  83403. __decorate([
  83404. BABYLON.serialize()
  83405. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  83406. __decorate([
  83407. BABYLON.serialize("expensiveBlur")
  83408. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  83409. __decorate([
  83410. BABYLON.serialize()
  83411. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  83412. __decorate([
  83413. BABYLON.serialize()
  83414. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  83415. return SSAO2RenderingPipeline;
  83416. }(BABYLON.PostProcessRenderPipeline));
  83417. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  83418. })(BABYLON || (BABYLON = {}));
  83419. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  83420. // BABYLON.JS Chromatic Aberration GLSL Shader
  83421. // Author: Olivier Guyot
  83422. // Separates very slightly R, G and B colors on the edges of the screen
  83423. // Inspired by Francois Tarlier & Martins Upitis
  83424. var BABYLON;
  83425. (function (BABYLON) {
  83426. var LensRenderingPipeline = /** @class */ (function (_super) {
  83427. __extends(LensRenderingPipeline, _super);
  83428. /**
  83429. * @constructor
  83430. *
  83431. * Effect parameters are as follow:
  83432. * {
  83433. * chromatic_aberration: number; // from 0 to x (1 for realism)
  83434. * edge_blur: number; // from 0 to x (1 for realism)
  83435. * distortion: number; // from 0 to x (1 for realism)
  83436. * grain_amount: number; // from 0 to 1
  83437. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  83438. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  83439. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  83440. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  83441. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  83442. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  83443. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  83444. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  83445. * }
  83446. * Note: if an effect parameter is unset, effect is disabled
  83447. *
  83448. * @param {string} name - The rendering pipeline name
  83449. * @param {object} parameters - An object containing all parameters (see above)
  83450. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  83451. * @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)
  83452. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  83453. */
  83454. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  83455. if (ratio === void 0) { ratio = 1.0; }
  83456. var _this = _super.call(this, scene.getEngine(), name) || this;
  83457. // Lens effects can be of the following:
  83458. // - chromatic aberration (slight shift of RGB colors)
  83459. // - blur on the edge of the lens
  83460. // - lens distortion
  83461. // - depth-of-field blur & highlights enhancing
  83462. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  83463. // - grain effect (noise or custom texture)
  83464. // Two additional texture samplers are needed:
  83465. // - depth map (for depth-of-field)
  83466. // - grain texture
  83467. /**
  83468. * The chromatic aberration PostProcess id in the pipeline
  83469. */
  83470. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  83471. /**
  83472. * The highlights enhancing PostProcess id in the pipeline
  83473. */
  83474. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  83475. /**
  83476. * The depth-of-field PostProcess id in the pipeline
  83477. */
  83478. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  83479. _this._scene = scene;
  83480. // Fetch texture samplers
  83481. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  83482. if (parameters.grain_texture) {
  83483. _this._grainTexture = parameters.grain_texture;
  83484. }
  83485. else {
  83486. _this._createGrainTexture();
  83487. }
  83488. // save parameters
  83489. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  83490. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  83491. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  83492. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  83493. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  83494. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  83495. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  83496. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  83497. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  83498. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  83499. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  83500. // Create effects
  83501. _this._createChromaticAberrationPostProcess(ratio);
  83502. _this._createHighlightsPostProcess(ratio);
  83503. _this._createDepthOfFieldPostProcess(ratio / 4);
  83504. // Set up pipeline
  83505. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  83506. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  83507. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  83508. if (_this._highlightsGain === -1) {
  83509. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  83510. }
  83511. // Finish
  83512. scene.postProcessRenderPipelineManager.addPipeline(_this);
  83513. if (cameras) {
  83514. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  83515. }
  83516. return _this;
  83517. }
  83518. // public methods (self explanatory)
  83519. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  83520. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  83521. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  83522. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  83523. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  83524. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  83525. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  83526. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  83527. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  83528. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  83529. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  83530. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  83531. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  83532. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  83533. };
  83534. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  83535. this._highlightsPostProcess.updateEffect();
  83536. };
  83537. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  83538. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  83539. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  83540. this._highlightsGain = amount;
  83541. };
  83542. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  83543. if (this._highlightsGain === -1) {
  83544. this._highlightsGain = 1.0;
  83545. }
  83546. this._highlightsThreshold = amount;
  83547. };
  83548. LensRenderingPipeline.prototype.disableHighlights = function () {
  83549. this._highlightsGain = -1;
  83550. };
  83551. /**
  83552. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  83553. */
  83554. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  83555. if (disableDepthRender === void 0) { disableDepthRender = false; }
  83556. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  83557. this._chromaticAberrationPostProcess = null;
  83558. this._highlightsPostProcess = null;
  83559. this._depthOfFieldPostProcess = null;
  83560. this._grainTexture.dispose();
  83561. if (disableDepthRender)
  83562. this._scene.disableDepthRenderer();
  83563. };
  83564. // colors shifting and distortion
  83565. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  83566. var _this = this;
  83567. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  83568. [], // samplers
  83569. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  83570. this._chromaticAberrationPostProcess.onApply = function (effect) {
  83571. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  83572. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  83573. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  83574. effect.setFloat('radialIntensity', 1);
  83575. effect.setFloat2('direction', 17, 17);
  83576. effect.setFloat2('centerPosition', 0.5, 0.5);
  83577. };
  83578. };
  83579. // highlights enhancing
  83580. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  83581. var _this = this;
  83582. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  83583. [], // samplers
  83584. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  83585. this._highlightsPostProcess.onApply = function (effect) {
  83586. effect.setFloat('gain', _this._highlightsGain);
  83587. effect.setFloat('threshold', _this._highlightsThreshold);
  83588. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  83589. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  83590. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  83591. };
  83592. };
  83593. // colors shifting and distortion
  83594. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  83595. var _this = this;
  83596. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  83597. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  83598. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  83599. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  83600. this._depthOfFieldPostProcess.onApply = function (effect) {
  83601. effect.setTexture("depthSampler", _this._depthTexture);
  83602. effect.setTexture("grainSampler", _this._grainTexture);
  83603. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  83604. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  83605. effect.setFloat('grain_amount', _this._grainAmount);
  83606. effect.setBool('blur_noise', _this._blurNoise);
  83607. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  83608. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  83609. effect.setFloat('distortion', _this._distortion);
  83610. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  83611. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  83612. effect.setFloat('aperture', _this._dofAperture);
  83613. effect.setFloat('darken', _this._dofDarken);
  83614. effect.setFloat('edge_blur', _this._edgeBlur);
  83615. effect.setBool('highlights', (_this._highlightsGain !== -1));
  83616. if (_this._scene.activeCamera) {
  83617. effect.setFloat('near', _this._scene.activeCamera.minZ);
  83618. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  83619. }
  83620. };
  83621. };
  83622. // creates a black and white random noise texture, 512x512
  83623. LensRenderingPipeline.prototype._createGrainTexture = function () {
  83624. var size = 512;
  83625. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83626. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  83627. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  83628. var context = this._grainTexture.getContext();
  83629. var rand = function (min, max) {
  83630. return Math.random() * (max - min) + min;
  83631. };
  83632. var value;
  83633. for (var x = 0; x < size; x++) {
  83634. for (var y = 0; y < size; y++) {
  83635. value = Math.floor(rand(0.42, 0.58) * 255);
  83636. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  83637. context.fillRect(x, y, 1, 1);
  83638. }
  83639. }
  83640. this._grainTexture.update(false);
  83641. };
  83642. return LensRenderingPipeline;
  83643. }(BABYLON.PostProcessRenderPipeline));
  83644. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  83645. })(BABYLON || (BABYLON = {}));
  83646. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  83647. var BABYLON;
  83648. (function (BABYLON) {
  83649. /**
  83650. * Standard rendering pipeline
  83651. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  83652. * @see https://doc.babylonjs.com/how_to/using_standard_rendering_pipeline
  83653. */
  83654. var StandardRenderingPipeline = /** @class */ (function (_super) {
  83655. __extends(StandardRenderingPipeline, _super);
  83656. /**
  83657. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  83658. * @constructor
  83659. * @param {string} name - The rendering pipeline name
  83660. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  83661. * @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)
  83662. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  83663. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  83664. */
  83665. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  83666. if (originalPostProcess === void 0) { originalPostProcess = null; }
  83667. var _this = _super.call(this, scene.getEngine(), name) || this;
  83668. /**
  83669. * Post-process used to down scale an image x4
  83670. */
  83671. _this.downSampleX4PostProcess = null;
  83672. /**
  83673. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  83674. */
  83675. _this.brightPassPostProcess = null;
  83676. /**
  83677. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  83678. */
  83679. _this.blurHPostProcesses = [];
  83680. /**
  83681. * Post-process array storing all the vertical blur post-processes used by the pipeline
  83682. */
  83683. _this.blurVPostProcesses = [];
  83684. /**
  83685. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  83686. */
  83687. _this.textureAdderPostProcess = null;
  83688. /**
  83689. * Post-process used to create volumetric lighting effect
  83690. */
  83691. _this.volumetricLightPostProcess = null;
  83692. /**
  83693. * Post-process used to smooth the previous volumetric light post-process on the X axis
  83694. */
  83695. _this.volumetricLightSmoothXPostProcess = null;
  83696. /**
  83697. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  83698. */
  83699. _this.volumetricLightSmoothYPostProcess = null;
  83700. /**
  83701. * Post-process used to merge the volumetric light effect and the real scene color
  83702. */
  83703. _this.volumetricLightMergePostProces = null;
  83704. /**
  83705. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  83706. */
  83707. _this.volumetricLightFinalPostProcess = null;
  83708. /**
  83709. * Base post-process used to calculate the average luminance of the final image for HDR
  83710. */
  83711. _this.luminancePostProcess = null;
  83712. /**
  83713. * Post-processes used to create down sample post-processes in order to get
  83714. * the average luminance of the final image for HDR
  83715. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  83716. */
  83717. _this.luminanceDownSamplePostProcesses = [];
  83718. /**
  83719. * Post-process used to create a HDR effect (light adaptation)
  83720. */
  83721. _this.hdrPostProcess = null;
  83722. /**
  83723. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  83724. */
  83725. _this.textureAdderFinalPostProcess = null;
  83726. /**
  83727. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  83728. */
  83729. _this.lensFlareFinalPostProcess = null;
  83730. /**
  83731. * Post-process used to merge the final HDR post-process and the real scene color
  83732. */
  83733. _this.hdrFinalPostProcess = null;
  83734. /**
  83735. * Post-process used to create a lens flare effect
  83736. */
  83737. _this.lensFlarePostProcess = null;
  83738. /**
  83739. * Post-process that merges the result of the lens flare post-process and the real scene color
  83740. */
  83741. _this.lensFlareComposePostProcess = null;
  83742. /**
  83743. * Post-process used to create a motion blur effect
  83744. */
  83745. _this.motionBlurPostProcess = null;
  83746. /**
  83747. * Post-process used to create a depth of field effect
  83748. */
  83749. _this.depthOfFieldPostProcess = null;
  83750. /**
  83751. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  83752. */
  83753. _this.fxaaPostProcess = null;
  83754. // Values
  83755. /**
  83756. * Represents the brightness threshold in order to configure the illuminated surfaces
  83757. */
  83758. _this.brightThreshold = 1.0;
  83759. /**
  83760. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  83761. */
  83762. _this.blurWidth = 512.0;
  83763. /**
  83764. * Sets if the blur for highlighted surfaces must be only horizontal
  83765. */
  83766. _this.horizontalBlur = false;
  83767. /**
  83768. * Sets the overall exposure used by the pipeline
  83769. */
  83770. _this.exposure = 1.0;
  83771. /**
  83772. * Texture used typically to simulate "dirty" on camera lens
  83773. */
  83774. _this.lensTexture = null;
  83775. /**
  83776. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  83777. */
  83778. _this.volumetricLightCoefficient = 0.2;
  83779. /**
  83780. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  83781. */
  83782. _this.volumetricLightPower = 4.0;
  83783. /**
  83784. * Used the set the blur intensity to smooth the volumetric lights
  83785. */
  83786. _this.volumetricLightBlurScale = 64.0;
  83787. /**
  83788. * Light (spot or directional) used to generate the volumetric lights rays
  83789. * The source light must have a shadow generate so the pipeline can get its
  83790. * depth map
  83791. */
  83792. _this.sourceLight = null;
  83793. /**
  83794. * For eye adaptation, represents the minimum luminance the eye can see
  83795. */
  83796. _this.hdrMinimumLuminance = 1.0;
  83797. /**
  83798. * For eye adaptation, represents the decrease luminance speed
  83799. */
  83800. _this.hdrDecreaseRate = 0.5;
  83801. /**
  83802. * For eye adaptation, represents the increase luminance speed
  83803. */
  83804. _this.hdrIncreaseRate = 0.5;
  83805. /**
  83806. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  83807. */
  83808. _this.lensColorTexture = null;
  83809. /**
  83810. * The overall strengh for the lens flare effect
  83811. */
  83812. _this.lensFlareStrength = 20.0;
  83813. /**
  83814. * Dispersion coefficient for lens flare ghosts
  83815. */
  83816. _this.lensFlareGhostDispersal = 1.4;
  83817. /**
  83818. * Main lens flare halo width
  83819. */
  83820. _this.lensFlareHaloWidth = 0.7;
  83821. /**
  83822. * Based on the lens distortion effect, defines how much the lens flare result
  83823. * is distorted
  83824. */
  83825. _this.lensFlareDistortionStrength = 16.0;
  83826. /**
  83827. * Lens star texture must be used to simulate rays on the flares and is available
  83828. * in the documentation
  83829. */
  83830. _this.lensStarTexture = null;
  83831. /**
  83832. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  83833. * flare effect by taking account of the dirt texture
  83834. */
  83835. _this.lensFlareDirtTexture = null;
  83836. /**
  83837. * Represents the focal length for the depth of field effect
  83838. */
  83839. _this.depthOfFieldDistance = 10.0;
  83840. /**
  83841. * Represents the blur intensity for the blurred part of the depth of field effect
  83842. */
  83843. _this.depthOfFieldBlurWidth = 64.0;
  83844. /**
  83845. * For motion blur, defines how much the image is blurred by the movement
  83846. */
  83847. _this.motionStrength = 1.0;
  83848. /**
  83849. * List of animations for the pipeline (IAnimatable implementation)
  83850. */
  83851. _this.animations = [];
  83852. _this._currentDepthOfFieldSource = null;
  83853. _this._hdrCurrentLuminance = 1.0;
  83854. // Getters and setters
  83855. _this._bloomEnabled = false;
  83856. _this._depthOfFieldEnabled = false;
  83857. _this._vlsEnabled = false;
  83858. _this._lensFlareEnabled = false;
  83859. _this._hdrEnabled = false;
  83860. _this._motionBlurEnabled = false;
  83861. _this._fxaaEnabled = false;
  83862. _this._motionBlurSamples = 64.0;
  83863. _this._volumetricLightStepsCount = 50.0;
  83864. _this._samples = 1;
  83865. _this._cameras = cameras || [];
  83866. // Initialize
  83867. _this._scene = scene;
  83868. _this._basePostProcess = originalPostProcess;
  83869. _this._ratio = ratio;
  83870. // Misc
  83871. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83872. // Finish
  83873. scene.postProcessRenderPipelineManager.addPipeline(_this);
  83874. _this._buildPipeline();
  83875. return _this;
  83876. }
  83877. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  83878. /**
  83879. * Specifies if the bloom pipeline is enabled
  83880. */
  83881. get: function () {
  83882. return this._bloomEnabled;
  83883. },
  83884. set: function (enabled) {
  83885. if (this._bloomEnabled === enabled) {
  83886. return;
  83887. }
  83888. this._bloomEnabled = enabled;
  83889. this._buildPipeline();
  83890. },
  83891. enumerable: true,
  83892. configurable: true
  83893. });
  83894. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  83895. /**
  83896. * Specifies if the depth of field pipeline is enabed
  83897. */
  83898. get: function () {
  83899. return this._depthOfFieldEnabled;
  83900. },
  83901. set: function (enabled) {
  83902. if (this._depthOfFieldEnabled === enabled) {
  83903. return;
  83904. }
  83905. this._depthOfFieldEnabled = enabled;
  83906. this._buildPipeline();
  83907. },
  83908. enumerable: true,
  83909. configurable: true
  83910. });
  83911. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  83912. /**
  83913. * Specifies if the lens flare pipeline is enabed
  83914. */
  83915. get: function () {
  83916. return this._lensFlareEnabled;
  83917. },
  83918. set: function (enabled) {
  83919. if (this._lensFlareEnabled === enabled) {
  83920. return;
  83921. }
  83922. this._lensFlareEnabled = enabled;
  83923. this._buildPipeline();
  83924. },
  83925. enumerable: true,
  83926. configurable: true
  83927. });
  83928. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  83929. /**
  83930. * Specifies if the HDR pipeline is enabled
  83931. */
  83932. get: function () {
  83933. return this._hdrEnabled;
  83934. },
  83935. set: function (enabled) {
  83936. if (this._hdrEnabled === enabled) {
  83937. return;
  83938. }
  83939. this._hdrEnabled = enabled;
  83940. this._buildPipeline();
  83941. },
  83942. enumerable: true,
  83943. configurable: true
  83944. });
  83945. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  83946. /**
  83947. * Specifies if the volumetric lights scattering effect is enabled
  83948. */
  83949. get: function () {
  83950. return this._vlsEnabled;
  83951. },
  83952. set: function (enabled) {
  83953. if (this._vlsEnabled === enabled) {
  83954. return;
  83955. }
  83956. if (enabled) {
  83957. var geometry = this._scene.enableGeometryBufferRenderer();
  83958. if (!geometry) {
  83959. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  83960. return;
  83961. }
  83962. }
  83963. this._vlsEnabled = enabled;
  83964. this._buildPipeline();
  83965. },
  83966. enumerable: true,
  83967. configurable: true
  83968. });
  83969. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  83970. /**
  83971. * Specifies if the motion blur effect is enabled
  83972. */
  83973. get: function () {
  83974. return this._motionBlurEnabled;
  83975. },
  83976. set: function (enabled) {
  83977. if (this._motionBlurEnabled === enabled) {
  83978. return;
  83979. }
  83980. this._motionBlurEnabled = enabled;
  83981. this._buildPipeline();
  83982. },
  83983. enumerable: true,
  83984. configurable: true
  83985. });
  83986. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  83987. /**
  83988. * Specifies if anti-aliasing is enabled
  83989. */
  83990. get: function () {
  83991. return this._fxaaEnabled;
  83992. },
  83993. set: function (enabled) {
  83994. if (this._fxaaEnabled === enabled) {
  83995. return;
  83996. }
  83997. this._fxaaEnabled = enabled;
  83998. this._buildPipeline();
  83999. },
  84000. enumerable: true,
  84001. configurable: true
  84002. });
  84003. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  84004. /**
  84005. * Specifies the number of steps used to calculate the volumetric lights
  84006. * Typically in interval [50, 200]
  84007. */
  84008. get: function () {
  84009. return this._volumetricLightStepsCount;
  84010. },
  84011. set: function (count) {
  84012. if (this.volumetricLightPostProcess) {
  84013. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  84014. }
  84015. this._volumetricLightStepsCount = count;
  84016. },
  84017. enumerable: true,
  84018. configurable: true
  84019. });
  84020. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  84021. /**
  84022. * Specifies the number of samples used for the motion blur effect
  84023. * Typically in interval [16, 64]
  84024. */
  84025. get: function () {
  84026. return this._motionBlurSamples;
  84027. },
  84028. set: function (samples) {
  84029. if (this.motionBlurPostProcess) {
  84030. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  84031. }
  84032. this._motionBlurSamples = samples;
  84033. },
  84034. enumerable: true,
  84035. configurable: true
  84036. });
  84037. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  84038. /**
  84039. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  84040. */
  84041. get: function () {
  84042. return this._samples;
  84043. },
  84044. set: function (sampleCount) {
  84045. if (this._samples === sampleCount) {
  84046. return;
  84047. }
  84048. this._samples = sampleCount;
  84049. this._buildPipeline();
  84050. },
  84051. enumerable: true,
  84052. configurable: true
  84053. });
  84054. StandardRenderingPipeline.prototype._buildPipeline = function () {
  84055. var _this = this;
  84056. var ratio = this._ratio;
  84057. var scene = this._scene;
  84058. this._disposePostProcesses();
  84059. this._reset();
  84060. // Create pass post-process
  84061. if (!this._basePostProcess) {
  84062. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  84063. this.originalPostProcess.onApply = function (effect) {
  84064. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  84065. };
  84066. }
  84067. else {
  84068. this.originalPostProcess = this._basePostProcess;
  84069. }
  84070. if (this._bloomEnabled || this._vlsEnabled || this._lensFlareEnabled || this._depthOfFieldEnabled || this._motionBlurEnabled) {
  84071. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  84072. }
  84073. this._currentDepthOfFieldSource = this.originalPostProcess;
  84074. if (this._bloomEnabled) {
  84075. // Create down sample X4 post-process
  84076. this._createDownSampleX4PostProcess(scene, ratio / 2);
  84077. // Create bright pass post-process
  84078. this._createBrightPassPostProcess(scene, ratio / 2);
  84079. // Create gaussian blur post-processes (down sampling blurs)
  84080. this._createBlurPostProcesses(scene, ratio / 4, 1);
  84081. // Create texture adder post-process
  84082. this._createTextureAdderPostProcess(scene, ratio);
  84083. // Create depth-of-field source post-process
  84084. 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);
  84085. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  84086. }
  84087. if (this._vlsEnabled) {
  84088. // Create volumetric light
  84089. this._createVolumetricLightPostProcess(scene, ratio);
  84090. // Create volumetric light final post-process
  84091. 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);
  84092. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  84093. }
  84094. if (this._lensFlareEnabled) {
  84095. // Create lens flare post-process
  84096. this._createLensFlarePostProcess(scene, ratio);
  84097. // Create depth-of-field source post-process post lens-flare and disable it now
  84098. 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);
  84099. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  84100. }
  84101. if (this._hdrEnabled) {
  84102. // Create luminance
  84103. this._createLuminancePostProcesses(scene, this._floatTextureType);
  84104. // Create HDR
  84105. this._createHdrPostProcess(scene, ratio);
  84106. // Create depth-of-field source post-process post hdr and disable it now
  84107. 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);
  84108. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  84109. }
  84110. if (this._depthOfFieldEnabled) {
  84111. // Create gaussian blur used by depth-of-field
  84112. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  84113. // Create depth-of-field post-process
  84114. this._createDepthOfFieldPostProcess(scene, ratio);
  84115. }
  84116. if (this._motionBlurEnabled) {
  84117. // Create motion blur post-process
  84118. this._createMotionBlurPostProcess(scene, ratio);
  84119. }
  84120. if (this._fxaaEnabled) {
  84121. // Create fxaa post-process
  84122. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  84123. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  84124. }
  84125. if (this._cameras !== null) {
  84126. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  84127. }
  84128. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  84129. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  84130. }
  84131. };
  84132. // Down Sample X4 Post-Processs
  84133. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  84134. var _this = this;
  84135. var downSampleX4Offsets = new Array(32);
  84136. 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);
  84137. this.downSampleX4PostProcess.onApply = function (effect) {
  84138. var id = 0;
  84139. var width = _this.downSampleX4PostProcess.width;
  84140. var height = _this.downSampleX4PostProcess.height;
  84141. for (var i = -2; i < 2; i++) {
  84142. for (var j = -2; j < 2; j++) {
  84143. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  84144. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  84145. id += 2;
  84146. }
  84147. }
  84148. effect.setArray2("dsOffsets", downSampleX4Offsets);
  84149. };
  84150. // Add to pipeline
  84151. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  84152. };
  84153. // Brightpass Post-Process
  84154. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  84155. var _this = this;
  84156. var brightOffsets = new Array(8);
  84157. 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);
  84158. this.brightPassPostProcess.onApply = function (effect) {
  84159. var sU = (1.0 / _this.brightPassPostProcess.width);
  84160. var sV = (1.0 / _this.brightPassPostProcess.height);
  84161. brightOffsets[0] = -0.5 * sU;
  84162. brightOffsets[1] = 0.5 * sV;
  84163. brightOffsets[2] = 0.5 * sU;
  84164. brightOffsets[3] = 0.5 * sV;
  84165. brightOffsets[4] = -0.5 * sU;
  84166. brightOffsets[5] = -0.5 * sV;
  84167. brightOffsets[6] = 0.5 * sU;
  84168. brightOffsets[7] = -0.5 * sV;
  84169. effect.setArray2("dsOffsets", brightOffsets);
  84170. effect.setFloat("brightThreshold", _this.brightThreshold);
  84171. };
  84172. // Add to pipeline
  84173. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  84174. };
  84175. // Create blur H&V post-processes
  84176. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  84177. var _this = this;
  84178. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  84179. var engine = scene.getEngine();
  84180. 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);
  84181. 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);
  84182. blurX.onActivateObservable.add(function () {
  84183. var dw = blurX.width / engine.getRenderWidth();
  84184. blurX.kernel = _this[blurWidthKey] * dw;
  84185. });
  84186. blurY.onActivateObservable.add(function () {
  84187. var dw = blurY.height / engine.getRenderHeight();
  84188. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  84189. });
  84190. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  84191. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  84192. this.blurHPostProcesses.push(blurX);
  84193. this.blurVPostProcesses.push(blurY);
  84194. };
  84195. // Create texture adder post-process
  84196. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  84197. var _this = this;
  84198. 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);
  84199. this.textureAdderPostProcess.onApply = function (effect) {
  84200. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  84201. effect.setTexture("lensSampler", _this.lensTexture);
  84202. effect.setFloat("exposure", _this.exposure);
  84203. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  84204. };
  84205. // Add to pipeline
  84206. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  84207. };
  84208. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  84209. var _this = this;
  84210. var geometryRenderer = scene.enableGeometryBufferRenderer();
  84211. geometryRenderer.enablePosition = true;
  84212. var geometry = geometryRenderer.getGBuffer();
  84213. // Base post-process
  84214. 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));
  84215. var depthValues = BABYLON.Vector2.Zero();
  84216. this.volumetricLightPostProcess.onApply = function (effect) {
  84217. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  84218. var generator = _this.sourceLight.getShadowGenerator();
  84219. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  84220. effect.setTexture("positionSampler", geometry.textures[2]);
  84221. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  84222. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  84223. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  84224. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  84225. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  84226. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  84227. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  84228. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  84229. effect.setVector2("depthValues", depthValues);
  84230. }
  84231. };
  84232. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  84233. // Smooth
  84234. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  84235. // Merge
  84236. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  84237. this.volumetricLightMergePostProces.onApply = function (effect) {
  84238. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  84239. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  84240. };
  84241. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  84242. };
  84243. // Create luminance
  84244. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  84245. var _this = this;
  84246. // Create luminance
  84247. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  84248. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  84249. var offsets = [];
  84250. this.luminancePostProcess.onApply = function (effect) {
  84251. var sU = (1.0 / _this.luminancePostProcess.width);
  84252. var sV = (1.0 / _this.luminancePostProcess.height);
  84253. offsets[0] = -0.5 * sU;
  84254. offsets[1] = 0.5 * sV;
  84255. offsets[2] = 0.5 * sU;
  84256. offsets[3] = 0.5 * sV;
  84257. offsets[4] = -0.5 * sU;
  84258. offsets[5] = -0.5 * sV;
  84259. offsets[6] = 0.5 * sU;
  84260. offsets[7] = -0.5 * sV;
  84261. effect.setArray2("lumOffsets", offsets);
  84262. };
  84263. // Add to pipeline
  84264. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  84265. // Create down sample luminance
  84266. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  84267. var size = Math.pow(3, i);
  84268. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  84269. if (i === 0) {
  84270. defines += "#define FINAL_DOWN_SAMPLER";
  84271. }
  84272. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  84273. this.luminanceDownSamplePostProcesses.push(postProcess);
  84274. }
  84275. // Create callbacks and add effects
  84276. var lastLuminance = this.luminancePostProcess;
  84277. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  84278. var downSampleOffsets = new Array(18);
  84279. pp.onApply = function (effect) {
  84280. if (!lastLuminance) {
  84281. return;
  84282. }
  84283. var id = 0;
  84284. for (var x = -1; x < 2; x++) {
  84285. for (var y = -1; y < 2; y++) {
  84286. downSampleOffsets[id] = x / lastLuminance.width;
  84287. downSampleOffsets[id + 1] = y / lastLuminance.height;
  84288. id += 2;
  84289. }
  84290. }
  84291. effect.setArray2("dsOffsets", downSampleOffsets);
  84292. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  84293. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  84294. lastLuminance = _this.luminancePostProcess;
  84295. }
  84296. else {
  84297. lastLuminance = pp;
  84298. }
  84299. };
  84300. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  84301. pp.onAfterRender = function (effect) {
  84302. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  84303. 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);
  84304. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  84305. };
  84306. }
  84307. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  84308. });
  84309. };
  84310. // Create HDR post-process
  84311. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  84312. var _this = this;
  84313. 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);
  84314. var outputLiminance = 1;
  84315. var time = 0;
  84316. var lastTime = 0;
  84317. this.hdrPostProcess.onApply = function (effect) {
  84318. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  84319. time += scene.getEngine().getDeltaTime();
  84320. if (outputLiminance < 0) {
  84321. outputLiminance = _this._hdrCurrentLuminance;
  84322. }
  84323. else {
  84324. var dt = (lastTime - time) / 1000.0;
  84325. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  84326. outputLiminance += _this.hdrDecreaseRate * dt;
  84327. }
  84328. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  84329. outputLiminance -= _this.hdrIncreaseRate * dt;
  84330. }
  84331. else {
  84332. outputLiminance = _this._hdrCurrentLuminance;
  84333. }
  84334. }
  84335. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  84336. effect.setFloat("averageLuminance", outputLiminance);
  84337. lastTime = time;
  84338. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  84339. };
  84340. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  84341. };
  84342. // Create lens flare post-process
  84343. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  84344. var _this = this;
  84345. 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);
  84346. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  84347. this._createBlurPostProcesses(scene, ratio / 4, 2);
  84348. 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);
  84349. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  84350. var resolution = new BABYLON.Vector2(0, 0);
  84351. // Lens flare
  84352. this.lensFlarePostProcess.onApply = function (effect) {
  84353. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  84354. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  84355. effect.setFloat("strength", _this.lensFlareStrength);
  84356. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  84357. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  84358. // Shift
  84359. resolution.x = _this.lensFlarePostProcess.width;
  84360. resolution.y = _this.lensFlarePostProcess.height;
  84361. effect.setVector2("resolution", resolution);
  84362. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  84363. };
  84364. // Compose
  84365. 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);
  84366. 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);
  84367. this.lensFlareComposePostProcess.onApply = function (effect) {
  84368. if (!_this._scene.activeCamera) {
  84369. return;
  84370. }
  84371. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  84372. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  84373. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  84374. // Lens start rotation matrix
  84375. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  84376. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  84377. 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));
  84378. camRot *= 4.0;
  84379. 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);
  84380. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  84381. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  84382. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  84383. };
  84384. };
  84385. // Create depth-of-field post-process
  84386. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  84387. var _this = this;
  84388. 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);
  84389. this.depthOfFieldPostProcess.onApply = function (effect) {
  84390. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  84391. effect.setTexture("depthSampler", _this._getDepthTexture());
  84392. effect.setFloat("distance", _this.depthOfFieldDistance);
  84393. };
  84394. // Add to pipeline
  84395. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  84396. };
  84397. // Create motion blur post-process
  84398. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  84399. var _this = this;
  84400. 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);
  84401. var motionScale = 0;
  84402. var prevViewProjection = BABYLON.Matrix.Identity();
  84403. var invViewProjection = BABYLON.Matrix.Identity();
  84404. var viewProjection = BABYLON.Matrix.Identity();
  84405. var screenSize = BABYLON.Vector2.Zero();
  84406. this.motionBlurPostProcess.onApply = function (effect) {
  84407. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  84408. viewProjection.invertToRef(invViewProjection);
  84409. effect.setMatrix("inverseViewProjection", invViewProjection);
  84410. effect.setMatrix("prevViewProjection", prevViewProjection);
  84411. prevViewProjection = viewProjection;
  84412. screenSize.x = _this.motionBlurPostProcess.width;
  84413. screenSize.y = _this.motionBlurPostProcess.height;
  84414. effect.setVector2("screenSize", screenSize);
  84415. motionScale = scene.getEngine().getFps() / 60.0;
  84416. effect.setFloat("motionScale", motionScale);
  84417. effect.setFloat("motionStrength", _this.motionStrength);
  84418. effect.setTexture("depthSampler", _this._getDepthTexture());
  84419. };
  84420. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  84421. };
  84422. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  84423. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  84424. var renderer = this._scene.enableGeometryBufferRenderer();
  84425. return renderer.getGBuffer().textures[0];
  84426. }
  84427. return this._scene.enableDepthRenderer().getDepthMap();
  84428. };
  84429. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  84430. for (var i = 0; i < this._cameras.length; i++) {
  84431. var camera = this._cameras[i];
  84432. if (this.originalPostProcess) {
  84433. this.originalPostProcess.dispose(camera);
  84434. }
  84435. if (this.downSampleX4PostProcess) {
  84436. this.downSampleX4PostProcess.dispose(camera);
  84437. }
  84438. if (this.brightPassPostProcess) {
  84439. this.brightPassPostProcess.dispose(camera);
  84440. }
  84441. if (this.textureAdderPostProcess) {
  84442. this.textureAdderPostProcess.dispose(camera);
  84443. }
  84444. if (this.textureAdderFinalPostProcess) {
  84445. this.textureAdderFinalPostProcess.dispose(camera);
  84446. }
  84447. if (this.volumetricLightPostProcess) {
  84448. this.volumetricLightPostProcess.dispose(camera);
  84449. }
  84450. if (this.volumetricLightSmoothXPostProcess) {
  84451. this.volumetricLightSmoothXPostProcess.dispose(camera);
  84452. }
  84453. if (this.volumetricLightSmoothYPostProcess) {
  84454. this.volumetricLightSmoothYPostProcess.dispose(camera);
  84455. }
  84456. if (this.volumetricLightMergePostProces) {
  84457. this.volumetricLightMergePostProces.dispose(camera);
  84458. }
  84459. if (this.volumetricLightFinalPostProcess) {
  84460. this.volumetricLightFinalPostProcess.dispose(camera);
  84461. }
  84462. if (this.lensFlarePostProcess) {
  84463. this.lensFlarePostProcess.dispose(camera);
  84464. }
  84465. if (this.lensFlareComposePostProcess) {
  84466. this.lensFlareComposePostProcess.dispose(camera);
  84467. }
  84468. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  84469. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  84470. }
  84471. if (this.luminancePostProcess) {
  84472. this.luminancePostProcess.dispose(camera);
  84473. }
  84474. if (this.hdrPostProcess) {
  84475. this.hdrPostProcess.dispose(camera);
  84476. }
  84477. if (this.hdrFinalPostProcess) {
  84478. this.hdrFinalPostProcess.dispose(camera);
  84479. }
  84480. if (this.depthOfFieldPostProcess) {
  84481. this.depthOfFieldPostProcess.dispose(camera);
  84482. }
  84483. if (this.motionBlurPostProcess) {
  84484. this.motionBlurPostProcess.dispose(camera);
  84485. }
  84486. if (this.fxaaPostProcess) {
  84487. this.fxaaPostProcess.dispose(camera);
  84488. }
  84489. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  84490. this.blurHPostProcesses[j].dispose(camera);
  84491. }
  84492. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  84493. this.blurVPostProcesses[j].dispose(camera);
  84494. }
  84495. }
  84496. this.originalPostProcess = null;
  84497. this.downSampleX4PostProcess = null;
  84498. this.brightPassPostProcess = null;
  84499. this.textureAdderPostProcess = null;
  84500. this.textureAdderFinalPostProcess = null;
  84501. this.volumetricLightPostProcess = null;
  84502. this.volumetricLightSmoothXPostProcess = null;
  84503. this.volumetricLightSmoothYPostProcess = null;
  84504. this.volumetricLightMergePostProces = null;
  84505. this.volumetricLightFinalPostProcess = null;
  84506. this.lensFlarePostProcess = null;
  84507. this.lensFlareComposePostProcess = null;
  84508. this.luminancePostProcess = null;
  84509. this.hdrPostProcess = null;
  84510. this.hdrFinalPostProcess = null;
  84511. this.depthOfFieldPostProcess = null;
  84512. this.motionBlurPostProcess = null;
  84513. this.fxaaPostProcess = null;
  84514. this.luminanceDownSamplePostProcesses = [];
  84515. this.blurHPostProcesses = [];
  84516. this.blurVPostProcesses = [];
  84517. };
  84518. /**
  84519. * Dispose of the pipeline and stop all post processes
  84520. */
  84521. StandardRenderingPipeline.prototype.dispose = function () {
  84522. this._disposePostProcesses();
  84523. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  84524. _super.prototype.dispose.call(this);
  84525. };
  84526. /**
  84527. * Serialize the rendering pipeline (Used when exporting)
  84528. * @returns the serialized object
  84529. */
  84530. StandardRenderingPipeline.prototype.serialize = function () {
  84531. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  84532. if (this.sourceLight) {
  84533. serializationObject.sourceLightId = this.sourceLight.id;
  84534. }
  84535. serializationObject.customType = "StandardRenderingPipeline";
  84536. return serializationObject;
  84537. };
  84538. /**
  84539. * Parse the serialized pipeline
  84540. * @param source Source pipeline.
  84541. * @param scene The scene to load the pipeline to.
  84542. * @param rootUrl The URL of the serialized pipeline.
  84543. * @returns An instantiated pipeline from the serialized object.
  84544. */
  84545. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  84546. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  84547. if (source.sourceLightId) {
  84548. p.sourceLight = scene.getLightByID(source.sourceLightId);
  84549. }
  84550. return p;
  84551. };
  84552. // Luminance steps
  84553. StandardRenderingPipeline.LuminanceSteps = 6;
  84554. __decorate([
  84555. BABYLON.serialize()
  84556. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  84557. __decorate([
  84558. BABYLON.serialize()
  84559. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  84560. __decorate([
  84561. BABYLON.serialize()
  84562. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  84563. __decorate([
  84564. BABYLON.serialize()
  84565. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  84566. __decorate([
  84567. BABYLON.serializeAsTexture("lensTexture")
  84568. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  84569. __decorate([
  84570. BABYLON.serialize()
  84571. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  84572. __decorate([
  84573. BABYLON.serialize()
  84574. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  84575. __decorate([
  84576. BABYLON.serialize()
  84577. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  84578. __decorate([
  84579. BABYLON.serialize()
  84580. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  84581. __decorate([
  84582. BABYLON.serialize()
  84583. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  84584. __decorate([
  84585. BABYLON.serialize()
  84586. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  84587. __decorate([
  84588. BABYLON.serializeAsTexture("lensColorTexture")
  84589. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  84590. __decorate([
  84591. BABYLON.serialize()
  84592. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  84593. __decorate([
  84594. BABYLON.serialize()
  84595. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  84596. __decorate([
  84597. BABYLON.serialize()
  84598. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  84599. __decorate([
  84600. BABYLON.serialize()
  84601. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  84602. __decorate([
  84603. BABYLON.serializeAsTexture("lensStarTexture")
  84604. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  84605. __decorate([
  84606. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  84607. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  84608. __decorate([
  84609. BABYLON.serialize()
  84610. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  84611. __decorate([
  84612. BABYLON.serialize()
  84613. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  84614. __decorate([
  84615. BABYLON.serialize()
  84616. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  84617. __decorate([
  84618. BABYLON.serialize()
  84619. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  84620. __decorate([
  84621. BABYLON.serialize()
  84622. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  84623. __decorate([
  84624. BABYLON.serialize()
  84625. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  84626. __decorate([
  84627. BABYLON.serialize()
  84628. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  84629. __decorate([
  84630. BABYLON.serialize()
  84631. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  84632. __decorate([
  84633. BABYLON.serialize()
  84634. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  84635. __decorate([
  84636. BABYLON.serialize()
  84637. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  84638. __decorate([
  84639. BABYLON.serialize()
  84640. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  84641. __decorate([
  84642. BABYLON.serialize()
  84643. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  84644. __decorate([
  84645. BABYLON.serialize()
  84646. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  84647. __decorate([
  84648. BABYLON.serialize()
  84649. ], StandardRenderingPipeline.prototype, "samples", null);
  84650. return StandardRenderingPipeline;
  84651. }(BABYLON.PostProcessRenderPipeline));
  84652. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  84653. })(BABYLON || (BABYLON = {}));
  84654. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  84655. var BABYLON;
  84656. (function (BABYLON) {
  84657. var FxaaPostProcess = /** @class */ (function (_super) {
  84658. __extends(FxaaPostProcess, _super);
  84659. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  84660. if (camera === void 0) { camera = null; }
  84661. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84662. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  84663. var defines = _this._getDefines();
  84664. _this.updateEffect(defines);
  84665. _this.onApplyObservable.add(function (effect) {
  84666. var texelSize = _this.texelSize;
  84667. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  84668. });
  84669. return _this;
  84670. }
  84671. FxaaPostProcess.prototype._getDefines = function () {
  84672. var engine = this.getEngine();
  84673. if (!engine) {
  84674. return null;
  84675. }
  84676. var glInfo = engine.getGlInfo();
  84677. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  84678. return "#define MALI 1\n";
  84679. }
  84680. return null;
  84681. };
  84682. return FxaaPostProcess;
  84683. }(BABYLON.PostProcess));
  84684. BABYLON.FxaaPostProcess = FxaaPostProcess;
  84685. })(BABYLON || (BABYLON = {}));
  84686. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  84687. var BABYLON;
  84688. (function (BABYLON) {
  84689. /**
  84690. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  84691. */
  84692. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  84693. __extends(ChromaticAberrationPostProcess, _super);
  84694. /**
  84695. * Creates a new instance ChromaticAberrationPostProcess
  84696. * @param name The name of the effect.
  84697. * @param screenWidth The width of the screen to apply the effect on.
  84698. * @param screenHeight The height of the screen to apply the effect on.
  84699. * @param options The required width/height ratio to downsize to before computing the render pass.
  84700. * @param camera The camera to apply the render pass to.
  84701. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  84702. * @param engine The engine which the post process will be applied. (default: current engine)
  84703. * @param reusable If the post process can be reused on the same frame. (default: false)
  84704. * @param textureType Type of textures used when performing the post process. (default: 0)
  84705. * @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)
  84706. */
  84707. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  84708. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84709. if (blockCompilation === void 0) { blockCompilation = false; }
  84710. 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;
  84711. /**
  84712. * The amount of seperation of rgb channels (default: 30)
  84713. */
  84714. _this.aberrationAmount = 30;
  84715. /**
  84716. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  84717. */
  84718. _this.radialIntensity = 0;
  84719. /**
  84720. * 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))
  84721. */
  84722. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  84723. /**
  84724. * 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))
  84725. */
  84726. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  84727. _this.onApplyObservable.add(function (effect) {
  84728. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  84729. effect.setFloat('screen_width', screenWidth);
  84730. effect.setFloat('screen_height', screenHeight);
  84731. effect.setFloat('radialIntensity', _this.radialIntensity);
  84732. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  84733. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  84734. });
  84735. return _this;
  84736. }
  84737. return ChromaticAberrationPostProcess;
  84738. }(BABYLON.PostProcess));
  84739. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  84740. })(BABYLON || (BABYLON = {}));
  84741. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  84742. var BABYLON;
  84743. (function (BABYLON) {
  84744. /**
  84745. * The GrainPostProcess adds noise to the image at mid luminance levels
  84746. */
  84747. var GrainPostProcess = /** @class */ (function (_super) {
  84748. __extends(GrainPostProcess, _super);
  84749. /**
  84750. * Creates a new instance of @see GrainPostProcess
  84751. * @param name The name of the effect.
  84752. * @param options The required width/height ratio to downsize to before computing the render pass.
  84753. * @param camera The camera to apply the render pass to.
  84754. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  84755. * @param engine The engine which the post process will be applied. (default: current engine)
  84756. * @param reusable If the post process can be reused on the same frame. (default: false)
  84757. * @param textureType Type of textures used when performing the post process. (default: 0)
  84758. * @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)
  84759. */
  84760. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  84761. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84762. if (blockCompilation === void 0) { blockCompilation = false; }
  84763. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  84764. /**
  84765. * The intensity of the grain added (default: 30)
  84766. */
  84767. _this.intensity = 30;
  84768. /**
  84769. * If the grain should be randomized on every frame
  84770. */
  84771. _this.animated = false;
  84772. _this.onApplyObservable.add(function (effect) {
  84773. effect.setFloat('intensity', _this.intensity);
  84774. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  84775. });
  84776. return _this;
  84777. }
  84778. return GrainPostProcess;
  84779. }(BABYLON.PostProcess));
  84780. BABYLON.GrainPostProcess = GrainPostProcess;
  84781. })(BABYLON || (BABYLON = {}));
  84782. //# sourceMappingURL=babylon.grainPostProcess.js.map
  84783. var BABYLON;
  84784. (function (BABYLON) {
  84785. /**
  84786. * The SharpenPostProcess applies a sharpen kernel to every pixel
  84787. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  84788. */
  84789. var SharpenPostProcess = /** @class */ (function (_super) {
  84790. __extends(SharpenPostProcess, _super);
  84791. /**
  84792. * Creates a new instance ConvolutionPostProcess
  84793. * @param name The name of the effect.
  84794. * @param options The required width/height ratio to downsize to before computing the render pass.
  84795. * @param camera The camera to apply the render pass to.
  84796. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  84797. * @param engine The engine which the post process will be applied. (default: current engine)
  84798. * @param reusable If the post process can be reused on the same frame. (default: false)
  84799. * @param textureType Type of textures used when performing the post process. (default: 0)
  84800. * @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)
  84801. */
  84802. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  84803. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84804. if (blockCompilation === void 0) { blockCompilation = false; }
  84805. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  84806. /**
  84807. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  84808. */
  84809. _this.colorAmount = 1.0;
  84810. /**
  84811. * How much sharpness should be applied (default: 0.3)
  84812. */
  84813. _this.edgeAmount = 0.3;
  84814. _this.onApply = function (effect) {
  84815. effect.setFloat2("screenSize", _this.width, _this.height);
  84816. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  84817. };
  84818. return _this;
  84819. }
  84820. return SharpenPostProcess;
  84821. }(BABYLON.PostProcess));
  84822. BABYLON.SharpenPostProcess = SharpenPostProcess;
  84823. })(BABYLON || (BABYLON = {}));
  84824. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  84825. var BABYLON;
  84826. (function (BABYLON) {
  84827. /**
  84828. * The Blur Post Process which blurs an image based on a kernel and direction.
  84829. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  84830. */
  84831. var BlurPostProcess = /** @class */ (function (_super) {
  84832. __extends(BlurPostProcess, _super);
  84833. /**
  84834. * Creates a new instance BlurPostProcess
  84835. * @param name The name of the effect.
  84836. * @param direction The direction in which to blur the image.
  84837. * @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.
  84838. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  84839. * @param camera The camera to apply the render pass to.
  84840. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  84841. * @param engine The engine which the post process will be applied. (default: current engine)
  84842. * @param reusable If the post process can be reused on the same frame. (default: false)
  84843. * @param textureType Type of textures used when performing the post process. (default: 0)
  84844. * @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)
  84845. */
  84846. function BlurPostProcess(name,
  84847. /** The direction in which to blur the image. */
  84848. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  84849. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  84850. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84851. if (defines === void 0) { defines = ""; }
  84852. if (blockCompilation === void 0) { blockCompilation = false; }
  84853. 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;
  84854. _this.direction = direction;
  84855. _this.blockCompilation = blockCompilation;
  84856. _this._packedFloat = false;
  84857. _this._staticDefines = "";
  84858. _this._staticDefines = defines;
  84859. _this.onApplyObservable.add(function (effect) {
  84860. if (_this._outputTexture) {
  84861. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  84862. }
  84863. else {
  84864. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  84865. }
  84866. });
  84867. _this.kernel = kernel;
  84868. return _this;
  84869. }
  84870. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  84871. /**
  84872. * Gets the length in pixels of the blur sample region
  84873. */
  84874. get: function () {
  84875. return this._idealKernel;
  84876. },
  84877. /**
  84878. * Sets the length in pixels of the blur sample region
  84879. */
  84880. set: function (v) {
  84881. if (this._idealKernel === v) {
  84882. return;
  84883. }
  84884. v = Math.max(v, 1);
  84885. this._idealKernel = v;
  84886. this._kernel = this._nearestBestKernel(v);
  84887. if (!this.blockCompilation) {
  84888. this._updateParameters();
  84889. }
  84890. },
  84891. enumerable: true,
  84892. configurable: true
  84893. });
  84894. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  84895. /**
  84896. * Gets wether or not the blur is unpacking/repacking floats
  84897. */
  84898. get: function () {
  84899. return this._packedFloat;
  84900. },
  84901. /**
  84902. * Sets wether or not the blur needs to unpack/repack floats
  84903. */
  84904. set: function (v) {
  84905. if (this._packedFloat === v) {
  84906. return;
  84907. }
  84908. this._packedFloat = v;
  84909. if (!this.blockCompilation) {
  84910. this._updateParameters();
  84911. }
  84912. },
  84913. enumerable: true,
  84914. configurable: true
  84915. });
  84916. /**
  84917. * Updates the effect with the current post process compile time values and recompiles the shader.
  84918. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  84919. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  84920. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  84921. * @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
  84922. * @param onCompiled Called when the shader has been compiled.
  84923. * @param onError Called if there is an error when compiling a shader.
  84924. */
  84925. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  84926. if (defines === void 0) { defines = null; }
  84927. if (uniforms === void 0) { uniforms = null; }
  84928. if (samplers === void 0) { samplers = null; }
  84929. this._updateParameters(onCompiled, onError);
  84930. };
  84931. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  84932. // Generate sampling offsets and weights
  84933. var N = this._kernel;
  84934. var centerIndex = (N - 1) / 2;
  84935. // Generate Gaussian sampling weights over kernel
  84936. var offsets = [];
  84937. var weights = [];
  84938. var totalWeight = 0;
  84939. for (var i = 0; i < N; i++) {
  84940. var u = i / (N - 1);
  84941. var w = this._gaussianWeight(u * 2.0 - 1);
  84942. offsets[i] = (i - centerIndex);
  84943. weights[i] = w;
  84944. totalWeight += w;
  84945. }
  84946. // Normalize weights
  84947. for (var i = 0; i < weights.length; i++) {
  84948. weights[i] /= totalWeight;
  84949. }
  84950. // Optimize: combine samples to take advantage of hardware linear sampling
  84951. // Walk from left to center, combining pairs (symmetrically)
  84952. var linearSamplingWeights = [];
  84953. var linearSamplingOffsets = [];
  84954. var linearSamplingMap = [];
  84955. for (var i = 0; i <= centerIndex; i += 2) {
  84956. var j = Math.min(i + 1, Math.floor(centerIndex));
  84957. var singleCenterSample = i === j;
  84958. if (singleCenterSample) {
  84959. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  84960. }
  84961. else {
  84962. var sharedCell = j === centerIndex;
  84963. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  84964. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  84965. if (offsetLinear === 0) {
  84966. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  84967. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  84968. }
  84969. else {
  84970. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  84971. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  84972. }
  84973. }
  84974. }
  84975. for (var i = 0; i < linearSamplingMap.length; i++) {
  84976. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  84977. linearSamplingWeights[i] = linearSamplingMap[i].w;
  84978. }
  84979. // Replace with optimized
  84980. offsets = linearSamplingOffsets;
  84981. weights = linearSamplingWeights;
  84982. // Generate shaders
  84983. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  84984. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  84985. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  84986. var defines = "";
  84987. defines += this._staticDefines;
  84988. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  84989. if (this._staticDefines.indexOf("DOF") != -1) {
  84990. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  84991. varyingCount--;
  84992. }
  84993. for (var i = 0; i < varyingCount; i++) {
  84994. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  84995. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  84996. }
  84997. var depCount = 0;
  84998. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  84999. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  85000. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  85001. depCount++;
  85002. }
  85003. if (this.packedFloat) {
  85004. defines += "#define PACKEDFLOAT 1";
  85005. }
  85006. this.blockCompilation = false;
  85007. _super.prototype.updateEffect.call(this, defines, null, null, {
  85008. varyingCount: varyingCount,
  85009. depCount: depCount
  85010. }, onCompiled, onError);
  85011. };
  85012. /**
  85013. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  85014. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  85015. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  85016. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  85017. * The gaps between physical kernels are compensated for in the weighting of the samples
  85018. * @param idealKernel Ideal blur kernel.
  85019. * @return Nearest best kernel.
  85020. */
  85021. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  85022. var v = Math.round(idealKernel);
  85023. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  85024. var k = _a[_i];
  85025. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  85026. return Math.max(k, 3);
  85027. }
  85028. }
  85029. return Math.max(v, 3);
  85030. };
  85031. /**
  85032. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  85033. * @param x The point on the Gaussian distribution to sample.
  85034. * @return the value of the Gaussian function at x.
  85035. */
  85036. BlurPostProcess.prototype._gaussianWeight = function (x) {
  85037. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  85038. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  85039. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  85040. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  85041. // truncated at around 1.3% of peak strength.
  85042. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  85043. var sigma = (1 / 3);
  85044. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  85045. var exponent = -((x * x) / (2.0 * sigma * sigma));
  85046. var weight = (1.0 / denominator) * Math.exp(exponent);
  85047. return weight;
  85048. };
  85049. /**
  85050. * Generates a string that can be used as a floating point number in GLSL.
  85051. * @param x Value to print.
  85052. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  85053. * @return GLSL float string.
  85054. */
  85055. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  85056. if (decimalFigures === void 0) { decimalFigures = 8; }
  85057. return x.toFixed(decimalFigures).replace(/0+$/, '');
  85058. };
  85059. return BlurPostProcess;
  85060. }(BABYLON.PostProcess));
  85061. BABYLON.BlurPostProcess = BlurPostProcess;
  85062. })(BABYLON || (BABYLON = {}));
  85063. //# sourceMappingURL=babylon.blurPostProcess.js.map
  85064. var BABYLON;
  85065. (function (BABYLON) {
  85066. /**
  85067. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  85068. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  85069. * based on samples that have a large difference in distance than the center pixel.
  85070. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  85071. */
  85072. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  85073. __extends(DepthOfFieldBlurPostProcess, _super);
  85074. /**
  85075. * Creates a new instance CircleOfConfusionPostProcess
  85076. * @param name The name of the effect.
  85077. * @param scene The scene the effect belongs to.
  85078. * @param direction The direction the blur should be applied.
  85079. * @param kernel The size of the kernel used to blur.
  85080. * @param options The required width/height ratio to downsize to before computing the render pass.
  85081. * @param camera The camera to apply the render pass to.
  85082. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  85083. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  85084. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85085. * @param engine The engine which the post process will be applied. (default: current engine)
  85086. * @param reusable If the post process can be reused on the same frame. (default: false)
  85087. * @param textureType Type of textures used when performing the post process. (default: 0)
  85088. * @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)
  85089. */
  85090. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  85091. if (imageToBlur === void 0) { imageToBlur = null; }
  85092. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  85093. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85094. if (blockCompilation === void 0) { blockCompilation = false; }
  85095. 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;
  85096. _this.direction = direction;
  85097. _this.onApplyObservable.add(function (effect) {
  85098. if (imageToBlur != null) {
  85099. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  85100. }
  85101. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  85102. if (scene.activeCamera) {
  85103. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  85104. }
  85105. });
  85106. return _this;
  85107. }
  85108. return DepthOfFieldBlurPostProcess;
  85109. }(BABYLON.BlurPostProcess));
  85110. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  85111. })(BABYLON || (BABYLON = {}));
  85112. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  85113. var BABYLON;
  85114. (function (BABYLON) {
  85115. /**
  85116. * Options to be set when merging outputs from the default pipeline.
  85117. */
  85118. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  85119. function DepthOfFieldMergePostProcessOptions() {
  85120. }
  85121. return DepthOfFieldMergePostProcessOptions;
  85122. }());
  85123. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  85124. /**
  85125. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  85126. */
  85127. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  85128. __extends(DepthOfFieldMergePostProcess, _super);
  85129. /**
  85130. * Creates a new instance of DepthOfFieldMergePostProcess
  85131. * @param name The name of the effect.
  85132. * @param originalFromInput Post process which's input will be used for the merge.
  85133. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  85134. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  85135. * @param options The required width/height ratio to downsize to before computing the render pass.
  85136. * @param camera The camera to apply the render pass to.
  85137. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85138. * @param engine The engine which the post process will be applied. (default: current engine)
  85139. * @param reusable If the post process can be reused on the same frame. (default: false)
  85140. * @param textureType Type of textures used when performing the post process. (default: 0)
  85141. * @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)
  85142. */
  85143. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  85144. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85145. if (blockCompilation === void 0) { blockCompilation = false; }
  85146. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  85147. _this.blurSteps = blurSteps;
  85148. _this.onApplyObservable.add(function (effect) {
  85149. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  85150. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  85151. blurSteps.forEach(function (step, index) {
  85152. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  85153. });
  85154. });
  85155. if (!blockCompilation) {
  85156. _this.updateEffect();
  85157. }
  85158. return _this;
  85159. }
  85160. /**
  85161. * Updates the effect with the current post process compile time values and recompiles the shader.
  85162. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  85163. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  85164. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  85165. * @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
  85166. * @param onCompiled Called when the shader has been compiled.
  85167. * @param onError Called if there is an error when compiling a shader.
  85168. */
  85169. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  85170. if (defines === void 0) { defines = null; }
  85171. if (uniforms === void 0) { uniforms = null; }
  85172. if (samplers === void 0) { samplers = null; }
  85173. if (!defines) {
  85174. defines = "";
  85175. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  85176. }
  85177. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  85178. };
  85179. return DepthOfFieldMergePostProcess;
  85180. }(BABYLON.PostProcess));
  85181. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  85182. })(BABYLON || (BABYLON = {}));
  85183. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  85184. var BABYLON;
  85185. (function (BABYLON) {
  85186. /**
  85187. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  85188. */
  85189. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  85190. __extends(CircleOfConfusionPostProcess, _super);
  85191. /**
  85192. * Creates a new instance CircleOfConfusionPostProcess
  85193. * @param name The name of the effect.
  85194. * @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.
  85195. * @param options The required width/height ratio to downsize to before computing the render pass.
  85196. * @param camera The camera to apply the render pass to.
  85197. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85198. * @param engine The engine which the post process will be applied. (default: current engine)
  85199. * @param reusable If the post process can be reused on the same frame. (default: false)
  85200. * @param textureType Type of textures used when performing the post process. (default: 0)
  85201. * @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)
  85202. */
  85203. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  85204. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85205. if (blockCompilation === void 0) { blockCompilation = false; }
  85206. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  85207. /**
  85208. * 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.
  85209. */
  85210. _this.lensSize = 50;
  85211. /**
  85212. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  85213. */
  85214. _this.fStop = 1.4;
  85215. /**
  85216. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  85217. */
  85218. _this.focusDistance = 2000;
  85219. /**
  85220. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  85221. */
  85222. _this.focalLength = 50;
  85223. _this._depthTexture = null;
  85224. _this._depthTexture = depthTexture;
  85225. _this.onApplyObservable.add(function (effect) {
  85226. if (!_this._depthTexture) {
  85227. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  85228. return;
  85229. }
  85230. effect.setTexture("depthSampler", _this._depthTexture);
  85231. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  85232. var aperture = _this.lensSize / _this.fStop;
  85233. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  85234. effect.setFloat('focusDistance', _this.focusDistance);
  85235. effect.setFloat('cocPrecalculation', cocPrecalculation);
  85236. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  85237. });
  85238. return _this;
  85239. }
  85240. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  85241. /**
  85242. * 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.
  85243. */
  85244. set: function (value) {
  85245. this._depthTexture = value;
  85246. },
  85247. enumerable: true,
  85248. configurable: true
  85249. });
  85250. return CircleOfConfusionPostProcess;
  85251. }(BABYLON.PostProcess));
  85252. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  85253. })(BABYLON || (BABYLON = {}));
  85254. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  85255. var BABYLON;
  85256. (function (BABYLON) {
  85257. /**
  85258. * Specifies the level of max blur that should be applied when using the depth of field effect
  85259. */
  85260. var DepthOfFieldEffectBlurLevel;
  85261. (function (DepthOfFieldEffectBlurLevel) {
  85262. /**
  85263. * Subtle blur
  85264. */
  85265. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  85266. /**
  85267. * Medium blur
  85268. */
  85269. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  85270. /**
  85271. * Large blur
  85272. */
  85273. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  85274. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  85275. ;
  85276. /**
  85277. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  85278. */
  85279. var DepthOfFieldEffect = /** @class */ (function (_super) {
  85280. __extends(DepthOfFieldEffect, _super);
  85281. /**
  85282. * Creates a new instance DepthOfFieldEffect
  85283. * @param scene The scene the effect belongs to.
  85284. * @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.
  85285. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  85286. * @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)
  85287. */
  85288. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  85289. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  85290. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  85291. if (blockCompilation === void 0) { blockCompilation = false; }
  85292. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  85293. return _this._effects;
  85294. }, true) || this;
  85295. /**
  85296. * @hidden Internal post processes in depth of field effect
  85297. */
  85298. _this._effects = [];
  85299. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  85300. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  85301. // 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)
  85302. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  85303. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  85304. _this._depthOfFieldBlurY = [];
  85305. _this._depthOfFieldBlurX = [];
  85306. var blurCount = 1;
  85307. var kernelSize = 15;
  85308. switch (blurLevel) {
  85309. case DepthOfFieldEffectBlurLevel.High: {
  85310. blurCount = 3;
  85311. kernelSize = 51;
  85312. break;
  85313. }
  85314. case DepthOfFieldEffectBlurLevel.Medium: {
  85315. blurCount = 2;
  85316. kernelSize = 31;
  85317. break;
  85318. }
  85319. default: {
  85320. kernelSize = 15;
  85321. blurCount = 1;
  85322. break;
  85323. }
  85324. }
  85325. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  85326. var ratio = 1.0;
  85327. for (var i = 0; i < blurCount; i++) {
  85328. 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);
  85329. blurY.autoClear = false;
  85330. ratio = 0.75 / Math.pow(2, i);
  85331. 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);
  85332. blurX.autoClear = false;
  85333. _this._depthOfFieldBlurY.push(blurY);
  85334. _this._depthOfFieldBlurX.push(blurX);
  85335. }
  85336. // Set all post processes on the effect.
  85337. _this._effects = [_this._circleOfConfusion];
  85338. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  85339. _this._effects.push(_this._depthOfFieldBlurY[i]);
  85340. _this._effects.push(_this._depthOfFieldBlurX[i]);
  85341. }
  85342. // Merge blurred images with original image based on circleOfConfusion
  85343. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  85344. _this._dofMerge.autoClear = false;
  85345. _this._effects.push(_this._dofMerge);
  85346. return _this;
  85347. }
  85348. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  85349. get: function () {
  85350. return this._circleOfConfusion.focalLength;
  85351. },
  85352. /**
  85353. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  85354. */
  85355. set: function (value) {
  85356. this._circleOfConfusion.focalLength = value;
  85357. },
  85358. enumerable: true,
  85359. configurable: true
  85360. });
  85361. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  85362. get: function () {
  85363. return this._circleOfConfusion.fStop;
  85364. },
  85365. /**
  85366. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  85367. */
  85368. set: function (value) {
  85369. this._circleOfConfusion.fStop = value;
  85370. },
  85371. enumerable: true,
  85372. configurable: true
  85373. });
  85374. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  85375. get: function () {
  85376. return this._circleOfConfusion.focusDistance;
  85377. },
  85378. /**
  85379. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  85380. */
  85381. set: function (value) {
  85382. this._circleOfConfusion.focusDistance = value;
  85383. },
  85384. enumerable: true,
  85385. configurable: true
  85386. });
  85387. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  85388. get: function () {
  85389. return this._circleOfConfusion.lensSize;
  85390. },
  85391. /**
  85392. * 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.
  85393. */
  85394. set: function (value) {
  85395. this._circleOfConfusion.lensSize = value;
  85396. },
  85397. enumerable: true,
  85398. configurable: true
  85399. });
  85400. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  85401. /**
  85402. * 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.
  85403. */
  85404. set: function (value) {
  85405. this._circleOfConfusion.depthTexture = value;
  85406. },
  85407. enumerable: true,
  85408. configurable: true
  85409. });
  85410. /**
  85411. * Disposes each of the internal effects for a given camera.
  85412. * @param camera The camera to dispose the effect on.
  85413. */
  85414. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  85415. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  85416. this._effects[effectIndex].dispose(camera);
  85417. }
  85418. };
  85419. /**
  85420. * @hidden Internal
  85421. */
  85422. DepthOfFieldEffect.prototype._updateEffects = function () {
  85423. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  85424. this._effects[effectIndex].updateEffect();
  85425. }
  85426. };
  85427. /**
  85428. * Internal
  85429. * @returns if all the contained post processes are ready.
  85430. * @hidden
  85431. */
  85432. DepthOfFieldEffect.prototype._isReady = function () {
  85433. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  85434. if (!this._effects[effectIndex].isReady()) {
  85435. return false;
  85436. }
  85437. }
  85438. return true;
  85439. };
  85440. return DepthOfFieldEffect;
  85441. }(BABYLON.PostProcessRenderEffect));
  85442. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  85443. })(BABYLON || (BABYLON = {}));
  85444. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  85445. var BABYLON;
  85446. (function (BABYLON) {
  85447. /**
  85448. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  85449. */
  85450. var BloomMergePostProcess = /** @class */ (function (_super) {
  85451. __extends(BloomMergePostProcess, _super);
  85452. /**
  85453. * Creates a new instance of @see BloomMergePostProcess
  85454. * @param name The name of the effect.
  85455. * @param originalFromInput Post process which's input will be used for the merge.
  85456. * @param blurred Blurred highlights post process which's output will be used.
  85457. * @param weight Weight of the bloom to be added to the original input.
  85458. * @param options The required width/height ratio to downsize to before computing the render pass.
  85459. * @param camera The camera to apply the render pass to.
  85460. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85461. * @param engine The engine which the post process will be applied. (default: current engine)
  85462. * @param reusable If the post process can be reused on the same frame. (default: false)
  85463. * @param textureType Type of textures used when performing the post process. (default: 0)
  85464. * @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)
  85465. */
  85466. function BloomMergePostProcess(name, originalFromInput, blurred,
  85467. /** Weight of the bloom to be added to the original input. */
  85468. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  85469. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85470. if (blockCompilation === void 0) { blockCompilation = false; }
  85471. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  85472. _this.weight = weight;
  85473. _this.onApplyObservable.add(function (effect) {
  85474. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  85475. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  85476. effect.setFloat("bloomWeight", _this.weight);
  85477. });
  85478. if (!blockCompilation) {
  85479. _this.updateEffect();
  85480. }
  85481. return _this;
  85482. }
  85483. return BloomMergePostProcess;
  85484. }(BABYLON.PostProcess));
  85485. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  85486. })(BABYLON || (BABYLON = {}));
  85487. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  85488. var BABYLON;
  85489. (function (BABYLON) {
  85490. /**
  85491. * 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.
  85492. */
  85493. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  85494. __extends(ExtractHighlightsPostProcess, _super);
  85495. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  85496. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85497. if (blockCompilation === void 0) { blockCompilation = false; }
  85498. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  85499. /**
  85500. * The luminance threshold, pixels below this value will be set to black.
  85501. */
  85502. _this.threshold = 0.9;
  85503. /** @hidden */
  85504. _this._exposure = 1;
  85505. /**
  85506. * Post process which has the input texture to be used when performing highlight extraction
  85507. * @hidden
  85508. */
  85509. _this._inputPostProcess = null;
  85510. _this.onApplyObservable.add(function (effect) {
  85511. if (_this._inputPostProcess) {
  85512. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  85513. }
  85514. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  85515. effect.setFloat('exposure', _this._exposure);
  85516. });
  85517. return _this;
  85518. }
  85519. return ExtractHighlightsPostProcess;
  85520. }(BABYLON.PostProcess));
  85521. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  85522. })(BABYLON || (BABYLON = {}));
  85523. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  85524. var BABYLON;
  85525. (function (BABYLON) {
  85526. /**
  85527. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  85528. */
  85529. var BloomEffect = /** @class */ (function (_super) {
  85530. __extends(BloomEffect, _super);
  85531. /**
  85532. * Creates a new instance of @see BloomEffect
  85533. * @param scene The scene the effect belongs to.
  85534. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  85535. * @param bloomKernel The size of the kernel to be used when applying the blur.
  85536. * @param bloomWeight The the strength of bloom.
  85537. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  85538. * @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)
  85539. */
  85540. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  85541. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  85542. if (blockCompilation === void 0) { blockCompilation = false; }
  85543. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  85544. return _this._effects;
  85545. }, true) || this;
  85546. _this.bloomScale = bloomScale;
  85547. /**
  85548. * @hidden Internal
  85549. */
  85550. _this._effects = [];
  85551. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  85552. _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);
  85553. _this._blurX.alwaysForcePOT = true;
  85554. _this._blurX.autoClear = false;
  85555. _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);
  85556. _this._blurY.alwaysForcePOT = true;
  85557. _this._blurY.autoClear = false;
  85558. _this.kernel = bloomKernel;
  85559. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  85560. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  85561. _this._merge.autoClear = false;
  85562. _this._effects.push(_this._merge);
  85563. return _this;
  85564. }
  85565. Object.defineProperty(BloomEffect.prototype, "threshold", {
  85566. /**
  85567. * The luminance threshold to find bright areas of the image to bloom.
  85568. */
  85569. get: function () {
  85570. return this._downscale.threshold;
  85571. },
  85572. set: function (value) {
  85573. this._downscale.threshold = value;
  85574. },
  85575. enumerable: true,
  85576. configurable: true
  85577. });
  85578. Object.defineProperty(BloomEffect.prototype, "weight", {
  85579. /**
  85580. * The strength of the bloom.
  85581. */
  85582. get: function () {
  85583. return this._merge.weight;
  85584. },
  85585. set: function (value) {
  85586. this._merge.weight = value;
  85587. },
  85588. enumerable: true,
  85589. configurable: true
  85590. });
  85591. Object.defineProperty(BloomEffect.prototype, "kernel", {
  85592. /**
  85593. * Specifies the size of the bloom blur kernel, relative to the final output size
  85594. */
  85595. get: function () {
  85596. return this._blurX.kernel / this.bloomScale;
  85597. },
  85598. set: function (value) {
  85599. this._blurX.kernel = value * this.bloomScale;
  85600. this._blurY.kernel = value * this.bloomScale;
  85601. },
  85602. enumerable: true,
  85603. configurable: true
  85604. });
  85605. /**
  85606. * Disposes each of the internal effects for a given camera.
  85607. * @param camera The camera to dispose the effect on.
  85608. */
  85609. BloomEffect.prototype.disposeEffects = function (camera) {
  85610. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  85611. this._effects[effectIndex].dispose(camera);
  85612. }
  85613. };
  85614. /**
  85615. * @hidden Internal
  85616. */
  85617. BloomEffect.prototype._updateEffects = function () {
  85618. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  85619. this._effects[effectIndex].updateEffect();
  85620. }
  85621. };
  85622. /**
  85623. * Internal
  85624. * @returns if all the contained post processes are ready.
  85625. * @hidden
  85626. */
  85627. BloomEffect.prototype._isReady = function () {
  85628. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  85629. if (!this._effects[effectIndex].isReady()) {
  85630. return false;
  85631. }
  85632. }
  85633. return true;
  85634. };
  85635. return BloomEffect;
  85636. }(BABYLON.PostProcessRenderEffect));
  85637. BABYLON.BloomEffect = BloomEffect;
  85638. })(BABYLON || (BABYLON = {}));
  85639. //# sourceMappingURL=babylon.bloomEffect.js.map
  85640. var BABYLON;
  85641. (function (BABYLON) {
  85642. /**
  85643. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  85644. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  85645. */
  85646. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  85647. __extends(DefaultRenderingPipeline, _super);
  85648. /**
  85649. * @constructor
  85650. * @param {string} name - The rendering pipeline name (default: "")
  85651. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  85652. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  85653. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  85654. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  85655. */
  85656. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  85657. if (name === void 0) { name = ""; }
  85658. if (hdr === void 0) { hdr = true; }
  85659. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  85660. if (automaticBuild === void 0) { automaticBuild = true; }
  85661. var _this = _super.call(this, scene.getEngine(), name) || this;
  85662. _this._camerasToBeAttached = [];
  85663. /**
  85664. * ID of the sharpen post process,
  85665. */
  85666. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  85667. /**
  85668. * @ignore
  85669. * ID of the image processing post process;
  85670. */
  85671. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  85672. /**
  85673. * @ignore
  85674. * ID of the Fast Approximate Anti-Aliasing post process;
  85675. */
  85676. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  85677. /**
  85678. * ID of the chromatic aberration post process,
  85679. */
  85680. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  85681. /**
  85682. * ID of the grain post process
  85683. */
  85684. _this.GrainPostProcessId = "GrainPostProcessEffect";
  85685. /**
  85686. * Glow post process which adds a glow to emmisive areas of the image
  85687. */
  85688. _this._glowLayer = null;
  85689. /**
  85690. * Animations which can be used to tweak settings over a period of time
  85691. */
  85692. _this.animations = [];
  85693. _this._imageProcessingConfigurationObserver = null;
  85694. // Values
  85695. _this._sharpenEnabled = false;
  85696. _this._bloomEnabled = false;
  85697. _this._depthOfFieldEnabled = false;
  85698. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  85699. _this._fxaaEnabled = false;
  85700. _this._imageProcessingEnabled = true;
  85701. _this._bloomScale = 0.5;
  85702. _this._chromaticAberrationEnabled = false;
  85703. _this._grainEnabled = false;
  85704. _this._buildAllowed = true;
  85705. _this._resizeObserver = null;
  85706. _this._hardwareScaleLevel = 1.0;
  85707. _this._bloomKernel = 64;
  85708. /**
  85709. * Specifies the weight of the bloom in the final rendering
  85710. */
  85711. _this._bloomWeight = 0.15;
  85712. /**
  85713. * Specifies the luma threshold for the area that will be blurred by the bloom
  85714. */
  85715. _this._bloomThreshold = 0.9;
  85716. _this._samples = 1;
  85717. _this._hasCleared = false;
  85718. _this._prevPostProcess = null;
  85719. _this._prevPrevPostProcess = null;
  85720. _this._depthOfFieldSceneObserver = null;
  85721. _this._cameras = cameras || scene.cameras;
  85722. _this._cameras = _this._cameras.slice();
  85723. _this._camerasToBeAttached = _this._cameras.slice();
  85724. _this._buildAllowed = automaticBuild;
  85725. // Initialize
  85726. _this._scene = scene;
  85727. var caps = _this._scene.getEngine().getCaps();
  85728. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  85729. // Misc
  85730. if (_this._hdr) {
  85731. if (caps.textureHalfFloatRender) {
  85732. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  85733. }
  85734. else if (caps.textureFloatRender) {
  85735. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  85736. }
  85737. }
  85738. else {
  85739. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  85740. }
  85741. // Attach
  85742. scene.postProcessRenderPipelineManager.addPipeline(_this);
  85743. var engine = _this._scene.getEngine();
  85744. // Create post processes before hand so they can be modified before enabled.
  85745. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  85746. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  85747. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  85748. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  85749. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  85750. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  85751. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  85752. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  85753. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  85754. _this._resizeObserver = engine.onResizeObservable.add(function () {
  85755. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  85756. _this.bloomKernel = _this.bloomKernel;
  85757. });
  85758. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  85759. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  85760. });
  85761. _this._buildPipeline();
  85762. return _this;
  85763. }
  85764. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  85765. get: function () {
  85766. return this._sharpenEnabled;
  85767. },
  85768. /**
  85769. * Enable or disable the sharpen process from the pipeline
  85770. */
  85771. set: function (enabled) {
  85772. if (this._sharpenEnabled === enabled) {
  85773. return;
  85774. }
  85775. this._sharpenEnabled = enabled;
  85776. this._buildPipeline();
  85777. },
  85778. enumerable: true,
  85779. configurable: true
  85780. });
  85781. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  85782. /**
  85783. * Specifies the size of the bloom blur kernel, relative to the final output size
  85784. */
  85785. get: function () {
  85786. return this._bloomKernel;
  85787. },
  85788. set: function (value) {
  85789. this._bloomKernel = value;
  85790. this.bloom.kernel = value / this._hardwareScaleLevel;
  85791. },
  85792. enumerable: true,
  85793. configurable: true
  85794. });
  85795. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  85796. get: function () {
  85797. return this._bloomWeight;
  85798. },
  85799. /**
  85800. * The strength of the bloom.
  85801. */
  85802. set: function (value) {
  85803. if (this._bloomWeight === value) {
  85804. return;
  85805. }
  85806. this.bloom.weight = value;
  85807. this._bloomWeight = value;
  85808. },
  85809. enumerable: true,
  85810. configurable: true
  85811. });
  85812. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  85813. get: function () {
  85814. return this._bloomThreshold;
  85815. },
  85816. /**
  85817. * The strength of the bloom.
  85818. */
  85819. set: function (value) {
  85820. if (this._bloomThreshold === value) {
  85821. return;
  85822. }
  85823. this.bloom.threshold = value;
  85824. this._bloomThreshold = value;
  85825. },
  85826. enumerable: true,
  85827. configurable: true
  85828. });
  85829. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  85830. get: function () {
  85831. return this._bloomScale;
  85832. },
  85833. /**
  85834. * The scale of the bloom, lower value will provide better performance.
  85835. */
  85836. set: function (value) {
  85837. if (this._bloomScale === value) {
  85838. return;
  85839. }
  85840. this._bloomScale = value;
  85841. // recreate bloom and dispose old as this setting is not dynamic
  85842. this._rebuildBloom();
  85843. this._buildPipeline();
  85844. },
  85845. enumerable: true,
  85846. configurable: true
  85847. });
  85848. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  85849. get: function () {
  85850. return this._bloomEnabled;
  85851. },
  85852. /**
  85853. * Enable or disable the bloom from the pipeline
  85854. */
  85855. set: function (enabled) {
  85856. if (this._bloomEnabled === enabled) {
  85857. return;
  85858. }
  85859. this._bloomEnabled = enabled;
  85860. this._buildPipeline();
  85861. },
  85862. enumerable: true,
  85863. configurable: true
  85864. });
  85865. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  85866. // recreate bloom and dispose old as this setting is not dynamic
  85867. var oldBloom = this.bloom;
  85868. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  85869. this.bloom.threshold = oldBloom.threshold;
  85870. for (var i = 0; i < this._cameras.length; i++) {
  85871. oldBloom.disposeEffects(this._cameras[i]);
  85872. }
  85873. };
  85874. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  85875. /**
  85876. * If the depth of field is enabled.
  85877. */
  85878. get: function () {
  85879. return this._depthOfFieldEnabled;
  85880. },
  85881. set: function (enabled) {
  85882. if (this._depthOfFieldEnabled === enabled) {
  85883. return;
  85884. }
  85885. this._depthOfFieldEnabled = enabled;
  85886. this._buildPipeline();
  85887. },
  85888. enumerable: true,
  85889. configurable: true
  85890. });
  85891. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  85892. /**
  85893. * Blur level of the depth of field effect. (Higher blur will effect performance)
  85894. */
  85895. get: function () {
  85896. return this._depthOfFieldBlurLevel;
  85897. },
  85898. set: function (value) {
  85899. if (this._depthOfFieldBlurLevel === value) {
  85900. return;
  85901. }
  85902. this._depthOfFieldBlurLevel = value;
  85903. // recreate dof and dispose old as this setting is not dynamic
  85904. var oldDof = this.depthOfField;
  85905. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  85906. this.depthOfField.focalLength = oldDof.focalLength;
  85907. this.depthOfField.focusDistance = oldDof.focusDistance;
  85908. this.depthOfField.fStop = oldDof.fStop;
  85909. this.depthOfField.lensSize = oldDof.lensSize;
  85910. for (var i = 0; i < this._cameras.length; i++) {
  85911. oldDof.disposeEffects(this._cameras[i]);
  85912. }
  85913. this._buildPipeline();
  85914. },
  85915. enumerable: true,
  85916. configurable: true
  85917. });
  85918. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  85919. get: function () {
  85920. return this._fxaaEnabled;
  85921. },
  85922. /**
  85923. * If the anti aliasing is enabled.
  85924. */
  85925. set: function (enabled) {
  85926. if (this._fxaaEnabled === enabled) {
  85927. return;
  85928. }
  85929. this._fxaaEnabled = enabled;
  85930. this._buildPipeline();
  85931. },
  85932. enumerable: true,
  85933. configurable: true
  85934. });
  85935. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  85936. get: function () {
  85937. return this._samples;
  85938. },
  85939. /**
  85940. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  85941. */
  85942. set: function (sampleCount) {
  85943. if (this._samples === sampleCount) {
  85944. return;
  85945. }
  85946. this._samples = sampleCount;
  85947. this._buildPipeline();
  85948. },
  85949. enumerable: true,
  85950. configurable: true
  85951. });
  85952. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  85953. get: function () {
  85954. return this._imageProcessingEnabled;
  85955. },
  85956. /**
  85957. * If image processing is enabled.
  85958. */
  85959. set: function (enabled) {
  85960. if (this._imageProcessingEnabled === enabled) {
  85961. return;
  85962. }
  85963. this._imageProcessingEnabled = enabled;
  85964. this._buildPipeline();
  85965. },
  85966. enumerable: true,
  85967. configurable: true
  85968. });
  85969. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  85970. get: function () {
  85971. return this._glowLayer == null;
  85972. },
  85973. /**
  85974. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  85975. */
  85976. set: function (enabled) {
  85977. if (enabled && !this._glowLayer) {
  85978. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  85979. }
  85980. else if (!enabled && this._glowLayer) {
  85981. this._glowLayer.dispose();
  85982. this._glowLayer = null;
  85983. }
  85984. },
  85985. enumerable: true,
  85986. configurable: true
  85987. });
  85988. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  85989. get: function () {
  85990. return this._chromaticAberrationEnabled;
  85991. },
  85992. /**
  85993. * Enable or disable the chromaticAberration process from the pipeline
  85994. */
  85995. set: function (enabled) {
  85996. if (this._chromaticAberrationEnabled === enabled) {
  85997. return;
  85998. }
  85999. this._chromaticAberrationEnabled = enabled;
  86000. this._buildPipeline();
  86001. },
  86002. enumerable: true,
  86003. configurable: true
  86004. });
  86005. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  86006. get: function () {
  86007. return this._grainEnabled;
  86008. },
  86009. /**
  86010. * Enable or disable the grain process from the pipeline
  86011. */
  86012. set: function (enabled) {
  86013. if (this._grainEnabled === enabled) {
  86014. return;
  86015. }
  86016. this._grainEnabled = enabled;
  86017. this._buildPipeline();
  86018. },
  86019. enumerable: true,
  86020. configurable: true
  86021. });
  86022. /**
  86023. * Force the compilation of the entire pipeline.
  86024. */
  86025. DefaultRenderingPipeline.prototype.prepare = function () {
  86026. var previousState = this._buildAllowed;
  86027. this._buildAllowed = true;
  86028. this._buildPipeline();
  86029. this._buildAllowed = previousState;
  86030. };
  86031. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  86032. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  86033. if (this._hasCleared) {
  86034. postProcess.autoClear = false;
  86035. }
  86036. else {
  86037. postProcess.autoClear = true;
  86038. this._scene.autoClear = false;
  86039. this._hasCleared = true;
  86040. }
  86041. if (!skipTextureSharing) {
  86042. if (this._prevPrevPostProcess) {
  86043. postProcess.shareOutputWith(this._prevPrevPostProcess);
  86044. }
  86045. else {
  86046. postProcess.useOwnOutput();
  86047. }
  86048. if (this._prevPostProcess) {
  86049. this._prevPrevPostProcess = this._prevPostProcess;
  86050. }
  86051. this._prevPostProcess = postProcess;
  86052. }
  86053. };
  86054. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  86055. var _this = this;
  86056. if (!this._buildAllowed) {
  86057. return;
  86058. }
  86059. this._scene.autoClear = true;
  86060. var engine = this._scene.getEngine();
  86061. this._disposePostProcesses();
  86062. if (this._cameras !== null) {
  86063. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  86064. // get back cameras to be used to reattach pipeline
  86065. this._cameras = this._camerasToBeAttached.slice();
  86066. }
  86067. this._reset();
  86068. this._prevPostProcess = null;
  86069. this._prevPrevPostProcess = null;
  86070. this._hasCleared = false;
  86071. if (this.depthOfFieldEnabled) {
  86072. // Multi camera suport
  86073. if (this._cameras.length > 1) {
  86074. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  86075. var camera = _a[_i];
  86076. var depthRenderer = this._scene.enableDepthRenderer(camera);
  86077. depthRenderer.useOnlyInActiveCamera = true;
  86078. }
  86079. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  86080. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  86081. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  86082. }
  86083. });
  86084. }
  86085. else {
  86086. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  86087. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  86088. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  86089. }
  86090. if (!this.depthOfField._isReady()) {
  86091. this.depthOfField._updateEffects();
  86092. }
  86093. this.addEffect(this.depthOfField);
  86094. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  86095. }
  86096. else {
  86097. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  86098. }
  86099. if (this.bloomEnabled) {
  86100. if (!this.bloom._isReady()) {
  86101. this.bloom._updateEffects();
  86102. }
  86103. this.addEffect(this.bloom);
  86104. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  86105. }
  86106. if (this._imageProcessingEnabled) {
  86107. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  86108. if (this._hdr) {
  86109. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  86110. this._setAutoClearAndTextureSharing(this.imageProcessing);
  86111. }
  86112. else {
  86113. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  86114. }
  86115. }
  86116. if (this.sharpenEnabled) {
  86117. if (!this.sharpen.isReady()) {
  86118. this.sharpen.updateEffect();
  86119. }
  86120. this.addEffect(this._sharpenEffect);
  86121. this._setAutoClearAndTextureSharing(this.sharpen);
  86122. }
  86123. if (this.grainEnabled) {
  86124. if (!this.grain.isReady()) {
  86125. this.grain.updateEffect();
  86126. }
  86127. this.addEffect(this._grainEffect);
  86128. this._setAutoClearAndTextureSharing(this.grain);
  86129. }
  86130. if (this.chromaticAberrationEnabled) {
  86131. if (!this.chromaticAberration.isReady()) {
  86132. this.chromaticAberration.updateEffect();
  86133. }
  86134. this.addEffect(this._chromaticAberrationEffect);
  86135. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  86136. }
  86137. if (this.fxaaEnabled) {
  86138. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  86139. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  86140. this._setAutoClearAndTextureSharing(this.fxaa, true);
  86141. }
  86142. if (this._cameras !== null) {
  86143. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  86144. }
  86145. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  86146. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  86147. }
  86148. };
  86149. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  86150. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  86151. for (var i = 0; i < this._cameras.length; i++) {
  86152. var camera = this._cameras[i];
  86153. if (this.imageProcessing) {
  86154. this.imageProcessing.dispose(camera);
  86155. }
  86156. if (this.fxaa) {
  86157. this.fxaa.dispose(camera);
  86158. }
  86159. // These are created in the constructor and should not be disposed on every pipeline change
  86160. if (disposeNonRecreated) {
  86161. if (this.sharpen) {
  86162. this.sharpen.dispose(camera);
  86163. }
  86164. if (this.depthOfField) {
  86165. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  86166. this.depthOfField.disposeEffects(camera);
  86167. }
  86168. if (this.bloom) {
  86169. this.bloom.disposeEffects(camera);
  86170. }
  86171. if (this.chromaticAberration) {
  86172. this.chromaticAberration.dispose(camera);
  86173. }
  86174. if (this.grain) {
  86175. this.grain.dispose(camera);
  86176. }
  86177. if (this._glowLayer) {
  86178. this._glowLayer.dispose();
  86179. }
  86180. }
  86181. }
  86182. this.imageProcessing = null;
  86183. this.fxaa = null;
  86184. if (disposeNonRecreated) {
  86185. this.sharpen = null;
  86186. this._sharpenEffect = null;
  86187. this.depthOfField = null;
  86188. this.bloom = null;
  86189. this.chromaticAberration = null;
  86190. this._chromaticAberrationEffect = null;
  86191. this.grain = null;
  86192. this._grainEffect = null;
  86193. this._glowLayer = null;
  86194. }
  86195. };
  86196. /**
  86197. * Adds a camera to the pipeline
  86198. * @param camera the camera to be added
  86199. */
  86200. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  86201. this._camerasToBeAttached.push(camera);
  86202. this._buildPipeline();
  86203. };
  86204. /**
  86205. * Removes a camera from the pipeline
  86206. * @param camera the camera to remove
  86207. */
  86208. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  86209. var index = this._camerasToBeAttached.indexOf(camera);
  86210. this._camerasToBeAttached.splice(index, 1);
  86211. this._buildPipeline();
  86212. };
  86213. /**
  86214. * Dispose of the pipeline and stop all post processes
  86215. */
  86216. DefaultRenderingPipeline.prototype.dispose = function () {
  86217. this._disposePostProcesses(true);
  86218. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  86219. this._scene.autoClear = true;
  86220. if (this._resizeObserver) {
  86221. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  86222. this._resizeObserver = null;
  86223. }
  86224. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  86225. _super.prototype.dispose.call(this);
  86226. };
  86227. /**
  86228. * Serialize the rendering pipeline (Used when exporting)
  86229. * @returns the serialized object
  86230. */
  86231. DefaultRenderingPipeline.prototype.serialize = function () {
  86232. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  86233. serializationObject.customType = "DefaultRenderingPipeline";
  86234. return serializationObject;
  86235. };
  86236. /**
  86237. * Parse the serialized pipeline
  86238. * @param source Source pipeline.
  86239. * @param scene The scene to load the pipeline to.
  86240. * @param rootUrl The URL of the serialized pipeline.
  86241. * @returns An instantiated pipeline from the serialized object.
  86242. */
  86243. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  86244. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  86245. };
  86246. __decorate([
  86247. BABYLON.serialize()
  86248. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  86249. __decorate([
  86250. BABYLON.serialize()
  86251. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  86252. __decorate([
  86253. BABYLON.serialize()
  86254. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  86255. __decorate([
  86256. BABYLON.serialize()
  86257. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  86258. __decorate([
  86259. BABYLON.serialize()
  86260. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  86261. __decorate([
  86262. BABYLON.serialize()
  86263. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  86264. __decorate([
  86265. BABYLON.serialize()
  86266. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  86267. __decorate([
  86268. BABYLON.serialize()
  86269. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  86270. __decorate([
  86271. BABYLON.serialize()
  86272. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  86273. __decorate([
  86274. BABYLON.serialize()
  86275. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  86276. __decorate([
  86277. BABYLON.serialize()
  86278. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  86279. __decorate([
  86280. BABYLON.serialize()
  86281. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  86282. __decorate([
  86283. BABYLON.serialize()
  86284. ], DefaultRenderingPipeline.prototype, "samples", null);
  86285. __decorate([
  86286. BABYLON.serialize()
  86287. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  86288. __decorate([
  86289. BABYLON.serialize()
  86290. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  86291. __decorate([
  86292. BABYLON.serialize()
  86293. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  86294. __decorate([
  86295. BABYLON.serialize()
  86296. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  86297. return DefaultRenderingPipeline;
  86298. }(BABYLON.PostProcessRenderPipeline));
  86299. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  86300. })(BABYLON || (BABYLON = {}));
  86301. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  86302. var BABYLON;
  86303. (function (BABYLON) {
  86304. /**
  86305. * @hidden
  86306. */
  86307. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  86308. __extends(ImageProcessingConfigurationDefines, _super);
  86309. function ImageProcessingConfigurationDefines() {
  86310. var _this = _super.call(this) || this;
  86311. _this.IMAGEPROCESSING = false;
  86312. _this.VIGNETTE = false;
  86313. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  86314. _this.VIGNETTEBLENDMODEOPAQUE = false;
  86315. _this.TONEMAPPING = false;
  86316. _this.TONEMAPPING_ACES = false;
  86317. _this.CONTRAST = false;
  86318. _this.COLORCURVES = false;
  86319. _this.COLORGRADING = false;
  86320. _this.COLORGRADING3D = false;
  86321. _this.SAMPLER3DGREENDEPTH = false;
  86322. _this.SAMPLER3DBGRMAP = false;
  86323. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  86324. _this.EXPOSURE = false;
  86325. _this.rebuild();
  86326. return _this;
  86327. }
  86328. return ImageProcessingConfigurationDefines;
  86329. }(BABYLON.MaterialDefines));
  86330. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  86331. /**
  86332. * This groups together the common properties used for image processing either in direct forward pass
  86333. * or through post processing effect depending on the use of the image processing pipeline in your scene
  86334. * or not.
  86335. */
  86336. var ImageProcessingConfiguration = /** @class */ (function () {
  86337. function ImageProcessingConfiguration() {
  86338. /**
  86339. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  86340. */
  86341. this.colorCurves = new BABYLON.ColorCurves();
  86342. this._colorCurvesEnabled = false;
  86343. this._colorGradingEnabled = false;
  86344. this._colorGradingWithGreenDepth = true;
  86345. this._colorGradingBGR = true;
  86346. /** @hidden */
  86347. this._exposure = 1.0;
  86348. this._toneMappingEnabled = false;
  86349. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  86350. this._contrast = 1.0;
  86351. /**
  86352. * Vignette stretch size.
  86353. */
  86354. this.vignetteStretch = 0;
  86355. /**
  86356. * Vignette centre X Offset.
  86357. */
  86358. this.vignetteCentreX = 0;
  86359. /**
  86360. * Vignette centre Y Offset.
  86361. */
  86362. this.vignetteCentreY = 0;
  86363. /**
  86364. * Vignette weight or intensity of the vignette effect.
  86365. */
  86366. this.vignetteWeight = 1.5;
  86367. /**
  86368. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  86369. * if vignetteEnabled is set to true.
  86370. */
  86371. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  86372. /**
  86373. * Camera field of view used by the Vignette effect.
  86374. */
  86375. this.vignetteCameraFov = 0.5;
  86376. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  86377. this._vignetteEnabled = false;
  86378. this._applyByPostProcess = false;
  86379. this._isEnabled = true;
  86380. /**
  86381. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  86382. */
  86383. this.onUpdateParameters = new BABYLON.Observable();
  86384. }
  86385. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  86386. /**
  86387. * Gets wether the color curves effect is enabled.
  86388. */
  86389. get: function () {
  86390. return this._colorCurvesEnabled;
  86391. },
  86392. /**
  86393. * Sets wether the color curves effect is enabled.
  86394. */
  86395. set: function (value) {
  86396. if (this._colorCurvesEnabled === value) {
  86397. return;
  86398. }
  86399. this._colorCurvesEnabled = value;
  86400. this._updateParameters();
  86401. },
  86402. enumerable: true,
  86403. configurable: true
  86404. });
  86405. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  86406. /**
  86407. * Gets wether the color grading effect is enabled.
  86408. */
  86409. get: function () {
  86410. return this._colorGradingEnabled;
  86411. },
  86412. /**
  86413. * Sets wether the color grading effect is enabled.
  86414. */
  86415. set: function (value) {
  86416. if (this._colorGradingEnabled === value) {
  86417. return;
  86418. }
  86419. this._colorGradingEnabled = value;
  86420. this._updateParameters();
  86421. },
  86422. enumerable: true,
  86423. configurable: true
  86424. });
  86425. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  86426. /**
  86427. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  86428. */
  86429. get: function () {
  86430. return this._colorGradingWithGreenDepth;
  86431. },
  86432. /**
  86433. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  86434. */
  86435. set: function (value) {
  86436. if (this._colorGradingWithGreenDepth === value) {
  86437. return;
  86438. }
  86439. this._colorGradingWithGreenDepth = value;
  86440. this._updateParameters();
  86441. },
  86442. enumerable: true,
  86443. configurable: true
  86444. });
  86445. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  86446. /**
  86447. * Gets wether the color grading texture contains BGR values.
  86448. */
  86449. get: function () {
  86450. return this._colorGradingBGR;
  86451. },
  86452. /**
  86453. * Sets wether the color grading texture contains BGR values.
  86454. */
  86455. set: function (value) {
  86456. if (this._colorGradingBGR === value) {
  86457. return;
  86458. }
  86459. this._colorGradingBGR = value;
  86460. this._updateParameters();
  86461. },
  86462. enumerable: true,
  86463. configurable: true
  86464. });
  86465. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  86466. /**
  86467. * Gets the Exposure used in the effect.
  86468. */
  86469. get: function () {
  86470. return this._exposure;
  86471. },
  86472. /**
  86473. * Sets the Exposure used in the effect.
  86474. */
  86475. set: function (value) {
  86476. if (this._exposure === value) {
  86477. return;
  86478. }
  86479. this._exposure = value;
  86480. this._updateParameters();
  86481. },
  86482. enumerable: true,
  86483. configurable: true
  86484. });
  86485. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  86486. /**
  86487. * Gets wether the tone mapping effect is enabled.
  86488. */
  86489. get: function () {
  86490. return this._toneMappingEnabled;
  86491. },
  86492. /**
  86493. * Sets wether the tone mapping effect is enabled.
  86494. */
  86495. set: function (value) {
  86496. if (this._toneMappingEnabled === value) {
  86497. return;
  86498. }
  86499. this._toneMappingEnabled = value;
  86500. this._updateParameters();
  86501. },
  86502. enumerable: true,
  86503. configurable: true
  86504. });
  86505. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  86506. /**
  86507. * Gets the type of tone mapping effect.
  86508. */
  86509. get: function () {
  86510. return this._toneMappingType;
  86511. },
  86512. /**
  86513. * Sets the type of tone mapping effect used in BabylonJS.
  86514. */
  86515. set: function (value) {
  86516. if (this._toneMappingType === value) {
  86517. return;
  86518. }
  86519. this._toneMappingType = value;
  86520. this._updateParameters();
  86521. },
  86522. enumerable: true,
  86523. configurable: true
  86524. });
  86525. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  86526. /**
  86527. * Gets the contrast used in the effect.
  86528. */
  86529. get: function () {
  86530. return this._contrast;
  86531. },
  86532. /**
  86533. * Sets the contrast used in the effect.
  86534. */
  86535. set: function (value) {
  86536. if (this._contrast === value) {
  86537. return;
  86538. }
  86539. this._contrast = value;
  86540. this._updateParameters();
  86541. },
  86542. enumerable: true,
  86543. configurable: true
  86544. });
  86545. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  86546. /**
  86547. * Gets the vignette blend mode allowing different kind of effect.
  86548. */
  86549. get: function () {
  86550. return this._vignetteBlendMode;
  86551. },
  86552. /**
  86553. * Sets the vignette blend mode allowing different kind of effect.
  86554. */
  86555. set: function (value) {
  86556. if (this._vignetteBlendMode === value) {
  86557. return;
  86558. }
  86559. this._vignetteBlendMode = value;
  86560. this._updateParameters();
  86561. },
  86562. enumerable: true,
  86563. configurable: true
  86564. });
  86565. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  86566. /**
  86567. * Gets wether the vignette effect is enabled.
  86568. */
  86569. get: function () {
  86570. return this._vignetteEnabled;
  86571. },
  86572. /**
  86573. * Sets wether the vignette effect is enabled.
  86574. */
  86575. set: function (value) {
  86576. if (this._vignetteEnabled === value) {
  86577. return;
  86578. }
  86579. this._vignetteEnabled = value;
  86580. this._updateParameters();
  86581. },
  86582. enumerable: true,
  86583. configurable: true
  86584. });
  86585. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  86586. /**
  86587. * Gets wether the image processing is applied through a post process or not.
  86588. */
  86589. get: function () {
  86590. return this._applyByPostProcess;
  86591. },
  86592. /**
  86593. * Sets wether the image processing is applied through a post process or not.
  86594. */
  86595. set: function (value) {
  86596. if (this._applyByPostProcess === value) {
  86597. return;
  86598. }
  86599. this._applyByPostProcess = value;
  86600. this._updateParameters();
  86601. },
  86602. enumerable: true,
  86603. configurable: true
  86604. });
  86605. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  86606. /**
  86607. * Gets wether the image processing is enabled or not.
  86608. */
  86609. get: function () {
  86610. return this._isEnabled;
  86611. },
  86612. /**
  86613. * Sets wether the image processing is enabled or not.
  86614. */
  86615. set: function (value) {
  86616. if (this._isEnabled === value) {
  86617. return;
  86618. }
  86619. this._isEnabled = value;
  86620. this._updateParameters();
  86621. },
  86622. enumerable: true,
  86623. configurable: true
  86624. });
  86625. /**
  86626. * Method called each time the image processing information changes requires to recompile the effect.
  86627. */
  86628. ImageProcessingConfiguration.prototype._updateParameters = function () {
  86629. this.onUpdateParameters.notifyObservers(this);
  86630. };
  86631. /**
  86632. * Gets the current class name.
  86633. * @return "ImageProcessingConfiguration"
  86634. */
  86635. ImageProcessingConfiguration.prototype.getClassName = function () {
  86636. return "ImageProcessingConfiguration";
  86637. };
  86638. /**
  86639. * Prepare the list of uniforms associated with the Image Processing effects.
  86640. * @param uniforms The list of uniforms used in the effect
  86641. * @param defines the list of defines currently in use
  86642. */
  86643. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  86644. if (defines.EXPOSURE) {
  86645. uniforms.push("exposureLinear");
  86646. }
  86647. if (defines.CONTRAST) {
  86648. uniforms.push("contrast");
  86649. }
  86650. if (defines.COLORGRADING) {
  86651. uniforms.push("colorTransformSettings");
  86652. }
  86653. if (defines.VIGNETTE) {
  86654. uniforms.push("vInverseScreenSize");
  86655. uniforms.push("vignetteSettings1");
  86656. uniforms.push("vignetteSettings2");
  86657. }
  86658. if (defines.COLORCURVES) {
  86659. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  86660. }
  86661. };
  86662. /**
  86663. * Prepare the list of samplers associated with the Image Processing effects.
  86664. * @param samplersList The list of uniforms used in the effect
  86665. * @param defines the list of defines currently in use
  86666. */
  86667. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  86668. if (defines.COLORGRADING) {
  86669. samplersList.push("txColorTransform");
  86670. }
  86671. };
  86672. /**
  86673. * Prepare the list of defines associated to the shader.
  86674. * @param defines the list of defines to complete
  86675. * @param forPostProcess Define if we are currently in post process mode or not
  86676. */
  86677. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  86678. if (forPostProcess === void 0) { forPostProcess = false; }
  86679. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  86680. defines.VIGNETTE = false;
  86681. defines.TONEMAPPING = false;
  86682. defines.TONEMAPPING_ACES = false;
  86683. defines.CONTRAST = false;
  86684. defines.EXPOSURE = false;
  86685. defines.COLORCURVES = false;
  86686. defines.COLORGRADING = false;
  86687. defines.COLORGRADING3D = false;
  86688. defines.IMAGEPROCESSING = false;
  86689. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  86690. return;
  86691. }
  86692. defines.VIGNETTE = this.vignetteEnabled;
  86693. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  86694. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  86695. defines.TONEMAPPING = this.toneMappingEnabled;
  86696. switch (this._toneMappingType) {
  86697. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  86698. defines.TONEMAPPING_ACES = true;
  86699. break;
  86700. }
  86701. defines.CONTRAST = (this.contrast !== 1.0);
  86702. defines.EXPOSURE = (this.exposure !== 1.0);
  86703. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  86704. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  86705. if (defines.COLORGRADING) {
  86706. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  86707. }
  86708. else {
  86709. defines.COLORGRADING3D = false;
  86710. }
  86711. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  86712. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  86713. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  86714. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  86715. };
  86716. /**
  86717. * Returns true if all the image processing information are ready.
  86718. * @returns True if ready, otherwise, false
  86719. */
  86720. ImageProcessingConfiguration.prototype.isReady = function () {
  86721. // Color Grading texure can not be none blocking.
  86722. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  86723. };
  86724. /**
  86725. * Binds the image processing to the shader.
  86726. * @param effect The effect to bind to
  86727. * @param aspectRatio Define the current aspect ratio of the effect
  86728. */
  86729. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  86730. if (aspectRatio === void 0) { aspectRatio = 1; }
  86731. // Color Curves
  86732. if (this._colorCurvesEnabled && this.colorCurves) {
  86733. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  86734. }
  86735. // Vignette
  86736. if (this._vignetteEnabled) {
  86737. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  86738. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  86739. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  86740. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  86741. var vignetteScaleX = vignetteScaleY * aspectRatio;
  86742. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  86743. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  86744. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  86745. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  86746. var vignettePower = -2.0 * this.vignetteWeight;
  86747. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  86748. }
  86749. // Exposure
  86750. effect.setFloat("exposureLinear", this.exposure);
  86751. // Contrast
  86752. effect.setFloat("contrast", this.contrast);
  86753. // Color transform settings
  86754. if (this.colorGradingTexture) {
  86755. effect.setTexture("txColorTransform", this.colorGradingTexture);
  86756. var textureSize = this.colorGradingTexture.getSize().height;
  86757. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  86758. 0.5 / textureSize, // textureOffset
  86759. textureSize, // textureSize
  86760. this.colorGradingTexture.level // weight
  86761. );
  86762. }
  86763. };
  86764. /**
  86765. * Clones the current image processing instance.
  86766. * @return The cloned image processing
  86767. */
  86768. ImageProcessingConfiguration.prototype.clone = function () {
  86769. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  86770. };
  86771. /**
  86772. * Serializes the current image processing instance to a json representation.
  86773. * @return a JSON representation
  86774. */
  86775. ImageProcessingConfiguration.prototype.serialize = function () {
  86776. return BABYLON.SerializationHelper.Serialize(this);
  86777. };
  86778. /**
  86779. * Parses the image processing from a json representation.
  86780. * @param source the JSON source to parse
  86781. * @return The parsed image processing
  86782. */
  86783. ImageProcessingConfiguration.Parse = function (source) {
  86784. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  86785. };
  86786. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  86787. /**
  86788. * Used to apply the vignette as a mix with the pixel color.
  86789. */
  86790. get: function () {
  86791. return this._VIGNETTEMODE_MULTIPLY;
  86792. },
  86793. enumerable: true,
  86794. configurable: true
  86795. });
  86796. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  86797. /**
  86798. * Used to apply the vignette as a replacement of the pixel color.
  86799. */
  86800. get: function () {
  86801. return this._VIGNETTEMODE_OPAQUE;
  86802. },
  86803. enumerable: true,
  86804. configurable: true
  86805. });
  86806. /**
  86807. * Default tone mapping applied in BabylonJS.
  86808. */
  86809. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  86810. /**
  86811. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  86812. * to other engines rendering to increase portability.
  86813. */
  86814. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  86815. // Static constants associated to the image processing.
  86816. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  86817. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  86818. __decorate([
  86819. BABYLON.serializeAsColorCurves()
  86820. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  86821. __decorate([
  86822. BABYLON.serialize()
  86823. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  86824. __decorate([
  86825. BABYLON.serializeAsTexture()
  86826. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  86827. __decorate([
  86828. BABYLON.serialize()
  86829. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  86830. __decorate([
  86831. BABYLON.serialize()
  86832. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  86833. __decorate([
  86834. BABYLON.serialize()
  86835. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  86836. __decorate([
  86837. BABYLON.serialize()
  86838. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  86839. __decorate([
  86840. BABYLON.serialize()
  86841. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  86842. __decorate([
  86843. BABYLON.serialize()
  86844. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  86845. __decorate([
  86846. BABYLON.serialize()
  86847. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  86848. __decorate([
  86849. BABYLON.serialize()
  86850. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  86851. __decorate([
  86852. BABYLON.serialize()
  86853. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  86854. __decorate([
  86855. BABYLON.serialize()
  86856. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  86857. __decorate([
  86858. BABYLON.serialize()
  86859. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  86860. __decorate([
  86861. BABYLON.serializeAsColor4()
  86862. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  86863. __decorate([
  86864. BABYLON.serialize()
  86865. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  86866. __decorate([
  86867. BABYLON.serialize()
  86868. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  86869. __decorate([
  86870. BABYLON.serialize()
  86871. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  86872. __decorate([
  86873. BABYLON.serialize()
  86874. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  86875. __decorate([
  86876. BABYLON.serialize()
  86877. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  86878. return ImageProcessingConfiguration;
  86879. }());
  86880. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  86881. })(BABYLON || (BABYLON = {}));
  86882. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  86883. var BABYLON;
  86884. (function (BABYLON) {
  86885. /**
  86886. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  86887. * It can help converting any input color in a desired output one. This can then be used to create effects
  86888. * from sepia, black and white to sixties or futuristic rendering...
  86889. *
  86890. * The only supported format is currently 3dl.
  86891. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table
  86892. */
  86893. var ColorGradingTexture = /** @class */ (function (_super) {
  86894. __extends(ColorGradingTexture, _super);
  86895. /**
  86896. * Instantiates a ColorGradingTexture from the following parameters.
  86897. *
  86898. * @param url The location of the color gradind data (currently only supporting 3dl)
  86899. * @param scene The scene the texture will be used in
  86900. */
  86901. function ColorGradingTexture(url, scene) {
  86902. var _this = _super.call(this, scene) || this;
  86903. if (!url) {
  86904. return _this;
  86905. }
  86906. _this._engine = scene.getEngine();
  86907. _this._textureMatrix = BABYLON.Matrix.Identity();
  86908. _this.name = url;
  86909. _this.url = url;
  86910. _this.hasAlpha = false;
  86911. _this.isCube = false;
  86912. _this.is3D = _this._engine.webGLVersion > 1;
  86913. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86914. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86915. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86916. _this.anisotropicFilteringLevel = 1;
  86917. _this._texture = _this._getFromCache(url, true);
  86918. if (!_this._texture) {
  86919. if (!scene.useDelayedTextureLoading) {
  86920. _this.loadTexture();
  86921. }
  86922. else {
  86923. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  86924. }
  86925. }
  86926. return _this;
  86927. }
  86928. /**
  86929. * Returns the texture matrix used in most of the material.
  86930. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  86931. */
  86932. ColorGradingTexture.prototype.getTextureMatrix = function () {
  86933. return this._textureMatrix;
  86934. };
  86935. /**
  86936. * Occurs when the file being loaded is a .3dl LUT file.
  86937. */
  86938. ColorGradingTexture.prototype.load3dlTexture = function () {
  86939. var engine = this._engine;
  86940. var texture;
  86941. if (engine.webGLVersion === 1) {
  86942. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86943. }
  86944. else {
  86945. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86946. }
  86947. this._texture = texture;
  86948. var callback = function (text) {
  86949. if (typeof text !== "string") {
  86950. return;
  86951. }
  86952. var data = null;
  86953. var tempData = null;
  86954. var line;
  86955. var lines = text.split('\n');
  86956. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  86957. var maxColor = 0;
  86958. for (var i = 0; i < lines.length; i++) {
  86959. line = lines[i];
  86960. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  86961. continue;
  86962. if (line.indexOf('#') === 0)
  86963. continue;
  86964. var words = line.split(" ");
  86965. if (size === 0) {
  86966. // Number of space + one
  86967. size = words.length;
  86968. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  86969. tempData = new Float32Array(size * size * size * 4);
  86970. continue;
  86971. }
  86972. if (size != 0) {
  86973. var r = Math.max(parseInt(words[0]), 0);
  86974. var g = Math.max(parseInt(words[1]), 0);
  86975. var b = Math.max(parseInt(words[2]), 0);
  86976. maxColor = Math.max(r, maxColor);
  86977. maxColor = Math.max(g, maxColor);
  86978. maxColor = Math.max(b, maxColor);
  86979. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  86980. if (tempData) {
  86981. tempData[pixelStorageIndex + 0] = r;
  86982. tempData[pixelStorageIndex + 1] = g;
  86983. tempData[pixelStorageIndex + 2] = b;
  86984. }
  86985. pixelIndexSlice++;
  86986. if (pixelIndexSlice % size == 0) {
  86987. pixelIndexH++;
  86988. pixelIndexSlice = 0;
  86989. if (pixelIndexH % size == 0) {
  86990. pixelIndexW++;
  86991. pixelIndexH = 0;
  86992. }
  86993. }
  86994. }
  86995. }
  86996. if (tempData && data) {
  86997. for (var i = 0; i < tempData.length; i++) {
  86998. if (i > 0 && (i + 1) % 4 === 0) {
  86999. data[i] = 255;
  87000. }
  87001. else {
  87002. var value = tempData[i];
  87003. data[i] = (value / maxColor * 255);
  87004. }
  87005. }
  87006. }
  87007. if (texture.is3D) {
  87008. texture.updateSize(size, size, size);
  87009. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  87010. }
  87011. else {
  87012. texture.updateSize(size * size, size);
  87013. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  87014. }
  87015. };
  87016. var scene = this.getScene();
  87017. if (scene) {
  87018. scene._loadFile(this.url, callback);
  87019. }
  87020. else {
  87021. this._engine._loadFile(this.url, callback);
  87022. }
  87023. return this._texture;
  87024. };
  87025. /**
  87026. * Starts the loading process of the texture.
  87027. */
  87028. ColorGradingTexture.prototype.loadTexture = function () {
  87029. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  87030. this.load3dlTexture();
  87031. }
  87032. };
  87033. /**
  87034. * Clones the color gradind texture.
  87035. */
  87036. ColorGradingTexture.prototype.clone = function () {
  87037. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  87038. // Base texture
  87039. newTexture.level = this.level;
  87040. return newTexture;
  87041. };
  87042. /**
  87043. * Called during delayed load for textures.
  87044. */
  87045. ColorGradingTexture.prototype.delayLoad = function () {
  87046. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  87047. return;
  87048. }
  87049. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  87050. this._texture = this._getFromCache(this.url, true);
  87051. if (!this._texture) {
  87052. this.loadTexture();
  87053. }
  87054. };
  87055. /**
  87056. * Parses a color grading texture serialized by Babylon.
  87057. * @param parsedTexture The texture information being parsedTexture
  87058. * @param scene The scene to load the texture in
  87059. * @param rootUrl The root url of the data assets to load
  87060. * @return A color gradind texture
  87061. */
  87062. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  87063. var texture = null;
  87064. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  87065. texture = new ColorGradingTexture(parsedTexture.name, scene);
  87066. texture.name = parsedTexture.name;
  87067. texture.level = parsedTexture.level;
  87068. }
  87069. return texture;
  87070. };
  87071. /**
  87072. * Serializes the LUT texture to json format.
  87073. */
  87074. ColorGradingTexture.prototype.serialize = function () {
  87075. if (!this.name) {
  87076. return null;
  87077. }
  87078. var serializationObject = {};
  87079. serializationObject.name = this.name;
  87080. serializationObject.level = this.level;
  87081. serializationObject.customType = "BABYLON.ColorGradingTexture";
  87082. return serializationObject;
  87083. };
  87084. /**
  87085. * Empty line regex stored for GC.
  87086. */
  87087. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  87088. return ColorGradingTexture;
  87089. }(BABYLON.BaseTexture));
  87090. BABYLON.ColorGradingTexture = ColorGradingTexture;
  87091. })(BABYLON || (BABYLON = {}));
  87092. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  87093. var BABYLON;
  87094. (function (BABYLON) {
  87095. /**
  87096. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  87097. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  87098. * 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;
  87099. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  87100. */
  87101. var ColorCurves = /** @class */ (function () {
  87102. function ColorCurves() {
  87103. this._dirty = true;
  87104. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  87105. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  87106. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  87107. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  87108. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  87109. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  87110. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  87111. this._globalHue = 30;
  87112. this._globalDensity = 0;
  87113. this._globalSaturation = 0;
  87114. this._globalExposure = 0;
  87115. this._highlightsHue = 30;
  87116. this._highlightsDensity = 0;
  87117. this._highlightsSaturation = 0;
  87118. this._highlightsExposure = 0;
  87119. this._midtonesHue = 30;
  87120. this._midtonesDensity = 0;
  87121. this._midtonesSaturation = 0;
  87122. this._midtonesExposure = 0;
  87123. this._shadowsHue = 30;
  87124. this._shadowsDensity = 0;
  87125. this._shadowsSaturation = 0;
  87126. this._shadowsExposure = 0;
  87127. }
  87128. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  87129. /**
  87130. * Gets the global Hue value.
  87131. * 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).
  87132. */
  87133. get: function () {
  87134. return this._globalHue;
  87135. },
  87136. /**
  87137. * Sets the global Hue value.
  87138. * 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).
  87139. */
  87140. set: function (value) {
  87141. this._globalHue = value;
  87142. this._dirty = true;
  87143. },
  87144. enumerable: true,
  87145. configurable: true
  87146. });
  87147. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  87148. /**
  87149. * Gets the global Density value.
  87150. * 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.
  87151. * Values less than zero provide a filter of opposite hue.
  87152. */
  87153. get: function () {
  87154. return this._globalDensity;
  87155. },
  87156. /**
  87157. * Sets the global Density value.
  87158. * 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.
  87159. * Values less than zero provide a filter of opposite hue.
  87160. */
  87161. set: function (value) {
  87162. this._globalDensity = value;
  87163. this._dirty = true;
  87164. },
  87165. enumerable: true,
  87166. configurable: true
  87167. });
  87168. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  87169. /**
  87170. * Gets the global Saturation value.
  87171. * 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.
  87172. */
  87173. get: function () {
  87174. return this._globalSaturation;
  87175. },
  87176. /**
  87177. * Sets the global Saturation value.
  87178. * 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.
  87179. */
  87180. set: function (value) {
  87181. this._globalSaturation = value;
  87182. this._dirty = true;
  87183. },
  87184. enumerable: true,
  87185. configurable: true
  87186. });
  87187. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  87188. /**
  87189. * Gets the global Exposure value.
  87190. * 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.
  87191. */
  87192. get: function () {
  87193. return this._globalExposure;
  87194. },
  87195. /**
  87196. * Sets the global Exposure value.
  87197. * 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.
  87198. */
  87199. set: function (value) {
  87200. this._globalExposure = value;
  87201. this._dirty = true;
  87202. },
  87203. enumerable: true,
  87204. configurable: true
  87205. });
  87206. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  87207. /**
  87208. * Gets the highlights Hue value.
  87209. * 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).
  87210. */
  87211. get: function () {
  87212. return this._highlightsHue;
  87213. },
  87214. /**
  87215. * Sets the highlights Hue value.
  87216. * 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).
  87217. */
  87218. set: function (value) {
  87219. this._highlightsHue = value;
  87220. this._dirty = true;
  87221. },
  87222. enumerable: true,
  87223. configurable: true
  87224. });
  87225. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  87226. /**
  87227. * Gets the highlights Density value.
  87228. * 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.
  87229. * Values less than zero provide a filter of opposite hue.
  87230. */
  87231. get: function () {
  87232. return this._highlightsDensity;
  87233. },
  87234. /**
  87235. * Sets the highlights Density value.
  87236. * 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.
  87237. * Values less than zero provide a filter of opposite hue.
  87238. */
  87239. set: function (value) {
  87240. this._highlightsDensity = value;
  87241. this._dirty = true;
  87242. },
  87243. enumerable: true,
  87244. configurable: true
  87245. });
  87246. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  87247. /**
  87248. * Gets the highlights Saturation value.
  87249. * 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.
  87250. */
  87251. get: function () {
  87252. return this._highlightsSaturation;
  87253. },
  87254. /**
  87255. * Sets the highlights Saturation value.
  87256. * 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.
  87257. */
  87258. set: function (value) {
  87259. this._highlightsSaturation = value;
  87260. this._dirty = true;
  87261. },
  87262. enumerable: true,
  87263. configurable: true
  87264. });
  87265. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  87266. /**
  87267. * Gets the highlights Exposure value.
  87268. * 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.
  87269. */
  87270. get: function () {
  87271. return this._highlightsExposure;
  87272. },
  87273. /**
  87274. * Sets the highlights Exposure value.
  87275. * 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.
  87276. */
  87277. set: function (value) {
  87278. this._highlightsExposure = value;
  87279. this._dirty = true;
  87280. },
  87281. enumerable: true,
  87282. configurable: true
  87283. });
  87284. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  87285. /**
  87286. * Gets the midtones Hue value.
  87287. * 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).
  87288. */
  87289. get: function () {
  87290. return this._midtonesHue;
  87291. },
  87292. /**
  87293. * Sets the midtones Hue value.
  87294. * 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).
  87295. */
  87296. set: function (value) {
  87297. this._midtonesHue = value;
  87298. this._dirty = true;
  87299. },
  87300. enumerable: true,
  87301. configurable: true
  87302. });
  87303. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  87304. /**
  87305. * Gets the midtones Density value.
  87306. * 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.
  87307. * Values less than zero provide a filter of opposite hue.
  87308. */
  87309. get: function () {
  87310. return this._midtonesDensity;
  87311. },
  87312. /**
  87313. * Sets the midtones Density value.
  87314. * 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.
  87315. * Values less than zero provide a filter of opposite hue.
  87316. */
  87317. set: function (value) {
  87318. this._midtonesDensity = value;
  87319. this._dirty = true;
  87320. },
  87321. enumerable: true,
  87322. configurable: true
  87323. });
  87324. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  87325. /**
  87326. * Gets the midtones Saturation value.
  87327. * 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.
  87328. */
  87329. get: function () {
  87330. return this._midtonesSaturation;
  87331. },
  87332. /**
  87333. * Sets the midtones Saturation value.
  87334. * 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.
  87335. */
  87336. set: function (value) {
  87337. this._midtonesSaturation = value;
  87338. this._dirty = true;
  87339. },
  87340. enumerable: true,
  87341. configurable: true
  87342. });
  87343. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  87344. /**
  87345. * Gets the midtones Exposure value.
  87346. * 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.
  87347. */
  87348. get: function () {
  87349. return this._midtonesExposure;
  87350. },
  87351. /**
  87352. * Sets the midtones Exposure value.
  87353. * 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.
  87354. */
  87355. set: function (value) {
  87356. this._midtonesExposure = value;
  87357. this._dirty = true;
  87358. },
  87359. enumerable: true,
  87360. configurable: true
  87361. });
  87362. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  87363. /**
  87364. * Gets the shadows Hue value.
  87365. * 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).
  87366. */
  87367. get: function () {
  87368. return this._shadowsHue;
  87369. },
  87370. /**
  87371. * Sets the shadows Hue value.
  87372. * 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).
  87373. */
  87374. set: function (value) {
  87375. this._shadowsHue = value;
  87376. this._dirty = true;
  87377. },
  87378. enumerable: true,
  87379. configurable: true
  87380. });
  87381. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  87382. /**
  87383. * Gets the shadows Density value.
  87384. * 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.
  87385. * Values less than zero provide a filter of opposite hue.
  87386. */
  87387. get: function () {
  87388. return this._shadowsDensity;
  87389. },
  87390. /**
  87391. * Sets the shadows Density value.
  87392. * 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.
  87393. * Values less than zero provide a filter of opposite hue.
  87394. */
  87395. set: function (value) {
  87396. this._shadowsDensity = value;
  87397. this._dirty = true;
  87398. },
  87399. enumerable: true,
  87400. configurable: true
  87401. });
  87402. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  87403. /**
  87404. * Gets the shadows Saturation value.
  87405. * 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.
  87406. */
  87407. get: function () {
  87408. return this._shadowsSaturation;
  87409. },
  87410. /**
  87411. * Sets the shadows Saturation value.
  87412. * 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.
  87413. */
  87414. set: function (value) {
  87415. this._shadowsSaturation = value;
  87416. this._dirty = true;
  87417. },
  87418. enumerable: true,
  87419. configurable: true
  87420. });
  87421. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  87422. /**
  87423. * Gets the shadows Exposure value.
  87424. * 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.
  87425. */
  87426. get: function () {
  87427. return this._shadowsExposure;
  87428. },
  87429. /**
  87430. * Sets the shadows Exposure value.
  87431. * 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.
  87432. */
  87433. set: function (value) {
  87434. this._shadowsExposure = value;
  87435. this._dirty = true;
  87436. },
  87437. enumerable: true,
  87438. configurable: true
  87439. });
  87440. /**
  87441. * Returns the class name
  87442. * @returns The class name
  87443. */
  87444. ColorCurves.prototype.getClassName = function () {
  87445. return "ColorCurves";
  87446. };
  87447. /**
  87448. * Binds the color curves to the shader.
  87449. * @param colorCurves The color curve to bind
  87450. * @param effect The effect to bind to
  87451. * @param positiveUniform The positive uniform shader parameter
  87452. * @param neutralUniform The neutral uniform shader parameter
  87453. * @param negativeUniform The negative uniform shader parameter
  87454. */
  87455. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  87456. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  87457. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  87458. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  87459. if (colorCurves._dirty) {
  87460. colorCurves._dirty = false;
  87461. // Fill in global info.
  87462. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  87463. // Compute highlights info.
  87464. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  87465. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  87466. // Compute midtones info.
  87467. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  87468. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  87469. // Compute shadows info.
  87470. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  87471. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  87472. // Compute deltas (neutral is midtones).
  87473. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  87474. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  87475. }
  87476. if (effect) {
  87477. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  87478. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  87479. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  87480. }
  87481. };
  87482. /**
  87483. * Prepare the list of uniforms associated with the ColorCurves effects.
  87484. * @param uniformsList The list of uniforms used in the effect
  87485. */
  87486. ColorCurves.PrepareUniforms = function (uniformsList) {
  87487. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  87488. };
  87489. /**
  87490. * Returns color grading data based on a hue, density, saturation and exposure value.
  87491. * @param filterHue The hue of the color filter.
  87492. * @param filterDensity The density of the color filter.
  87493. * @param saturation The saturation.
  87494. * @param exposure The exposure.
  87495. * @param result The result data container.
  87496. */
  87497. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  87498. if (hue == null) {
  87499. return;
  87500. }
  87501. hue = ColorCurves.clamp(hue, 0, 360);
  87502. density = ColorCurves.clamp(density, -100, 100);
  87503. saturation = ColorCurves.clamp(saturation, -100, 100);
  87504. exposure = ColorCurves.clamp(exposure, -100, 100);
  87505. // Remap the slider/config filter density with non-linear mapping and also scale by half
  87506. // so that the maximum filter density is only 50% control. This provides fine control
  87507. // for small values and reasonable range.
  87508. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  87509. density *= 0.5;
  87510. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  87511. if (density < 0) {
  87512. density *= -1;
  87513. hue = (hue + 180) % 360;
  87514. }
  87515. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  87516. result.scaleToRef(2, result);
  87517. result.a = 1 + 0.01 * saturation;
  87518. };
  87519. /**
  87520. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  87521. * @param value The input slider value in range [-100,100].
  87522. * @returns Adjusted value.
  87523. */
  87524. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  87525. value /= 100;
  87526. var x = Math.abs(value);
  87527. x = Math.pow(x, 2);
  87528. if (value < 0) {
  87529. x *= -1;
  87530. }
  87531. x *= 100;
  87532. return x;
  87533. };
  87534. /**
  87535. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  87536. * @param hue The hue (H) input.
  87537. * @param saturation The saturation (S) input.
  87538. * @param brightness The brightness (B) input.
  87539. * @result An RGBA color represented as Vector4.
  87540. */
  87541. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  87542. var h = ColorCurves.clamp(hue, 0, 360);
  87543. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  87544. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  87545. if (s === 0) {
  87546. result.r = v;
  87547. result.g = v;
  87548. result.b = v;
  87549. }
  87550. else {
  87551. // sector 0 to 5
  87552. h /= 60;
  87553. var i = Math.floor(h);
  87554. // fractional part of h
  87555. var f = h - i;
  87556. var p = v * (1 - s);
  87557. var q = v * (1 - s * f);
  87558. var t = v * (1 - s * (1 - f));
  87559. switch (i) {
  87560. case 0:
  87561. result.r = v;
  87562. result.g = t;
  87563. result.b = p;
  87564. break;
  87565. case 1:
  87566. result.r = q;
  87567. result.g = v;
  87568. result.b = p;
  87569. break;
  87570. case 2:
  87571. result.r = p;
  87572. result.g = v;
  87573. result.b = t;
  87574. break;
  87575. case 3:
  87576. result.r = p;
  87577. result.g = q;
  87578. result.b = v;
  87579. break;
  87580. case 4:
  87581. result.r = t;
  87582. result.g = p;
  87583. result.b = v;
  87584. break;
  87585. default: // case 5:
  87586. result.r = v;
  87587. result.g = p;
  87588. result.b = q;
  87589. break;
  87590. }
  87591. }
  87592. result.a = 1;
  87593. };
  87594. /**
  87595. * Returns a value clamped between min and max
  87596. * @param value The value to clamp
  87597. * @param min The minimum of value
  87598. * @param max The maximum of value
  87599. * @returns The clamped value.
  87600. */
  87601. ColorCurves.clamp = function (value, min, max) {
  87602. return Math.min(Math.max(value, min), max);
  87603. };
  87604. /**
  87605. * Clones the current color curve instance.
  87606. * @return The cloned curves
  87607. */
  87608. ColorCurves.prototype.clone = function () {
  87609. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  87610. };
  87611. /**
  87612. * Serializes the current color curve instance to a json representation.
  87613. * @return a JSON representation
  87614. */
  87615. ColorCurves.prototype.serialize = function () {
  87616. return BABYLON.SerializationHelper.Serialize(this);
  87617. };
  87618. /**
  87619. * Parses the color curve from a json representation.
  87620. * @param source the JSON source to parse
  87621. * @return The parsed curves
  87622. */
  87623. ColorCurves.Parse = function (source) {
  87624. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  87625. };
  87626. __decorate([
  87627. BABYLON.serialize()
  87628. ], ColorCurves.prototype, "_globalHue", void 0);
  87629. __decorate([
  87630. BABYLON.serialize()
  87631. ], ColorCurves.prototype, "_globalDensity", void 0);
  87632. __decorate([
  87633. BABYLON.serialize()
  87634. ], ColorCurves.prototype, "_globalSaturation", void 0);
  87635. __decorate([
  87636. BABYLON.serialize()
  87637. ], ColorCurves.prototype, "_globalExposure", void 0);
  87638. __decorate([
  87639. BABYLON.serialize()
  87640. ], ColorCurves.prototype, "_highlightsHue", void 0);
  87641. __decorate([
  87642. BABYLON.serialize()
  87643. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  87644. __decorate([
  87645. BABYLON.serialize()
  87646. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  87647. __decorate([
  87648. BABYLON.serialize()
  87649. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  87650. __decorate([
  87651. BABYLON.serialize()
  87652. ], ColorCurves.prototype, "_midtonesHue", void 0);
  87653. __decorate([
  87654. BABYLON.serialize()
  87655. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  87656. __decorate([
  87657. BABYLON.serialize()
  87658. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  87659. __decorate([
  87660. BABYLON.serialize()
  87661. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  87662. return ColorCurves;
  87663. }());
  87664. BABYLON.ColorCurves = ColorCurves;
  87665. })(BABYLON || (BABYLON = {}));
  87666. //# sourceMappingURL=babylon.colorCurves.js.map
  87667. var BABYLON;
  87668. (function (BABYLON) {
  87669. /**
  87670. * Post process which applies a refractin texture
  87671. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  87672. */
  87673. var RefractionPostProcess = /** @class */ (function (_super) {
  87674. __extends(RefractionPostProcess, _super);
  87675. /**
  87676. * Initializes the RefractionPostProcess
  87677. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  87678. * @param name The name of the effect.
  87679. * @param refractionTextureUrl Url of the refraction texture to use
  87680. * @param color the base color of the refraction (used to taint the rendering)
  87681. * @param depth simulated refraction depth
  87682. * @param colorLevel the coefficient of the base color (0 to remove base color tainting)
  87683. * @param camera The camera to apply the render pass to.
  87684. * @param options The required width/height ratio to downsize to before computing the render pass.
  87685. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87686. * @param engine The engine which the post process will be applied. (default: current engine)
  87687. * @param reusable If the post process can be reused on the same frame. (default: false)
  87688. */
  87689. function RefractionPostProcess(name, refractionTextureUrl,
  87690. /** the base color of the refraction (used to taint the rendering) */
  87691. color,
  87692. /** simulated refraction depth */
  87693. depth,
  87694. /** the coefficient of the base color (0 to remove base color tainting) */
  87695. colorLevel, options, camera, samplingMode, engine, reusable) {
  87696. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  87697. _this.color = color;
  87698. _this.depth = depth;
  87699. _this.colorLevel = colorLevel;
  87700. _this._ownRefractionTexture = true;
  87701. _this.onActivateObservable.add(function (cam) {
  87702. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  87703. });
  87704. _this.onApplyObservable.add(function (effect) {
  87705. effect.setColor3("baseColor", _this.color);
  87706. effect.setFloat("depth", _this.depth);
  87707. effect.setFloat("colorLevel", _this.colorLevel);
  87708. effect.setTexture("refractionSampler", _this._refTexture);
  87709. });
  87710. return _this;
  87711. }
  87712. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  87713. /**
  87714. * Gets or sets the refraction texture
  87715. * Please note that you are responsible for disposing the texture if you set it manually
  87716. */
  87717. get: function () {
  87718. return this._refTexture;
  87719. },
  87720. set: function (value) {
  87721. if (this._refTexture && this._ownRefractionTexture) {
  87722. this._refTexture.dispose();
  87723. }
  87724. this._refTexture = value;
  87725. this._ownRefractionTexture = false;
  87726. },
  87727. enumerable: true,
  87728. configurable: true
  87729. });
  87730. // Methods
  87731. /**
  87732. * Disposes of the post process
  87733. * @param camera Camera to dispose post process on
  87734. */
  87735. RefractionPostProcess.prototype.dispose = function (camera) {
  87736. if (this._refTexture && this._ownRefractionTexture) {
  87737. this._refTexture.dispose();
  87738. this._refTexture = null;
  87739. }
  87740. _super.prototype.dispose.call(this, camera);
  87741. };
  87742. return RefractionPostProcess;
  87743. }(BABYLON.PostProcess));
  87744. BABYLON.RefractionPostProcess = RefractionPostProcess;
  87745. })(BABYLON || (BABYLON = {}));
  87746. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  87747. var BABYLON;
  87748. (function (BABYLON) {
  87749. /**
  87750. * Post process used to render in black and white
  87751. */
  87752. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  87753. __extends(BlackAndWhitePostProcess, _super);
  87754. /**
  87755. * Creates a black and white post process
  87756. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#black-and-white
  87757. * @param name The name of the effect.
  87758. * @param options The required width/height ratio to downsize to before computing the render pass.
  87759. * @param camera The camera to apply the render pass to.
  87760. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87761. * @param engine The engine which the post process will be applied. (default: current engine)
  87762. * @param reusable If the post process can be reused on the same frame. (default: false)
  87763. */
  87764. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  87765. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  87766. /**
  87767. * Linear about to convert he result to black and white (default: 1)
  87768. */
  87769. _this.degree = 1;
  87770. _this.onApplyObservable.add(function (effect) {
  87771. effect.setFloat("degree", _this.degree);
  87772. });
  87773. return _this;
  87774. }
  87775. return BlackAndWhitePostProcess;
  87776. }(BABYLON.PostProcess));
  87777. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  87778. })(BABYLON || (BABYLON = {}));
  87779. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  87780. var BABYLON;
  87781. (function (BABYLON) {
  87782. /**
  87783. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  87784. * input texture to perform effects such as edge detection or sharpening
  87785. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  87786. */
  87787. var ConvolutionPostProcess = /** @class */ (function (_super) {
  87788. __extends(ConvolutionPostProcess, _super);
  87789. /**
  87790. * Creates a new instance ConvolutionPostProcess
  87791. * @param name The name of the effect.
  87792. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  87793. * @param options The required width/height ratio to downsize to before computing the render pass.
  87794. * @param camera The camera to apply the render pass to.
  87795. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87796. * @param engine The engine which the post process will be applied. (default: current engine)
  87797. * @param reusable If the post process can be reused on the same frame. (default: false)
  87798. * @param textureType Type of textures used when performing the post process. (default: 0)
  87799. */
  87800. function ConvolutionPostProcess(name,
  87801. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  87802. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  87803. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87804. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  87805. _this.kernel = kernel;
  87806. _this.onApply = function (effect) {
  87807. effect.setFloat2("screenSize", _this.width, _this.height);
  87808. effect.setArray("kernel", _this.kernel);
  87809. };
  87810. return _this;
  87811. }
  87812. // Statics
  87813. /**
  87814. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87815. */
  87816. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  87817. /**
  87818. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87819. */
  87820. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  87821. /**
  87822. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87823. */
  87824. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  87825. /**
  87826. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87827. */
  87828. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  87829. /**
  87830. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87831. */
  87832. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  87833. /**
  87834. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87835. */
  87836. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  87837. return ConvolutionPostProcess;
  87838. }(BABYLON.PostProcess));
  87839. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  87840. })(BABYLON || (BABYLON = {}));
  87841. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  87842. var BABYLON;
  87843. (function (BABYLON) {
  87844. /**
  87845. * Applies a kernel filter to the image
  87846. */
  87847. var FilterPostProcess = /** @class */ (function (_super) {
  87848. __extends(FilterPostProcess, _super);
  87849. /**
  87850. *
  87851. * @param name The name of the effect.
  87852. * @param kernelMatrix The matrix to be applied to the image
  87853. * @param options The required width/height ratio to downsize to before computing the render pass.
  87854. * @param camera The camera to apply the render pass to.
  87855. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87856. * @param engine The engine which the post process will be applied. (default: current engine)
  87857. * @param reusable If the post process can be reused on the same frame. (default: false)
  87858. */
  87859. function FilterPostProcess(name,
  87860. /** The matrix to be applied to the image */
  87861. kernelMatrix, options, camera, samplingMode, engine, reusable) {
  87862. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  87863. _this.kernelMatrix = kernelMatrix;
  87864. _this.onApply = function (effect) {
  87865. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  87866. };
  87867. return _this;
  87868. }
  87869. return FilterPostProcess;
  87870. }(BABYLON.PostProcess));
  87871. BABYLON.FilterPostProcess = FilterPostProcess;
  87872. })(BABYLON || (BABYLON = {}));
  87873. //# sourceMappingURL=babylon.filterPostProcess.js.map
  87874. var BABYLON;
  87875. (function (BABYLON) {
  87876. /**
  87877. * Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  87878. */
  87879. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  87880. __extends(VolumetricLightScatteringPostProcess, _super);
  87881. /**
  87882. * @constructor
  87883. * @param {string} name - The post-process name
  87884. * @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)
  87885. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  87886. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  87887. * @param {number} samples - The post-process quality, default 100
  87888. * @param {number} samplingMode - The post-process filtering mode
  87889. * @param {BABYLON.Engine} engine - The babylon engine
  87890. * @param {boolean} reusable - If the post-process is reusable
  87891. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  87892. */
  87893. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  87894. if (samples === void 0) { samples = 100; }
  87895. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  87896. 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;
  87897. _this._screenCoordinates = BABYLON.Vector2.Zero();
  87898. /**
  87899. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  87900. */
  87901. _this.customMeshPosition = BABYLON.Vector3.Zero();
  87902. /**
  87903. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  87904. */
  87905. _this.useCustomMeshPosition = false;
  87906. /**
  87907. * If the post-process should inverse the light scattering direction
  87908. */
  87909. _this.invert = true;
  87910. /**
  87911. * Array containing the excluded meshes not rendered in the internal pass
  87912. */
  87913. _this.excludedMeshes = new Array();
  87914. /**
  87915. * Controls the overall intensity of the post-process
  87916. */
  87917. _this.exposure = 0.3;
  87918. /**
  87919. * Dissipates each sample's contribution in range [0, 1]
  87920. */
  87921. _this.decay = 0.96815;
  87922. /**
  87923. * Controls the overall intensity of each sample
  87924. */
  87925. _this.weight = 0.58767;
  87926. /**
  87927. * Controls the density of each sample
  87928. */
  87929. _this.density = 0.926;
  87930. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  87931. engine = scene.getEngine();
  87932. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  87933. // Configure mesh
  87934. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  87935. // Configure
  87936. _this._createPass(scene, ratio.passRatio || ratio);
  87937. _this.onActivate = function (camera) {
  87938. if (!_this.isSupported) {
  87939. _this.dispose(camera);
  87940. }
  87941. _this.onActivate = null;
  87942. };
  87943. _this.onApplyObservable.add(function (effect) {
  87944. _this._updateMeshScreenCoordinates(scene);
  87945. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  87946. effect.setFloat("exposure", _this.exposure);
  87947. effect.setFloat("decay", _this.decay);
  87948. effect.setFloat("weight", _this.weight);
  87949. effect.setFloat("density", _this.density);
  87950. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  87951. });
  87952. return _this;
  87953. }
  87954. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  87955. /**
  87956. * @hidden
  87957. * VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead
  87958. */
  87959. get: function () {
  87960. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  87961. return false;
  87962. },
  87963. set: function (useDiffuseColor) {
  87964. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  87965. },
  87966. enumerable: true,
  87967. configurable: true
  87968. });
  87969. /**
  87970. * Returns the string "VolumetricLightScatteringPostProcess"
  87971. * @returns "VolumetricLightScatteringPostProcess"
  87972. */
  87973. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  87974. return "VolumetricLightScatteringPostProcess";
  87975. };
  87976. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  87977. var mesh = subMesh.getMesh();
  87978. // Render this.mesh as default
  87979. if (mesh === this.mesh && mesh.material) {
  87980. return mesh.material.isReady(mesh);
  87981. }
  87982. var defines = [];
  87983. var attribs = [BABYLON.VertexBuffer.PositionKind];
  87984. var material = subMesh.getMaterial();
  87985. // Alpha test
  87986. if (material) {
  87987. if (material.needAlphaTesting()) {
  87988. defines.push("#define ALPHATEST");
  87989. }
  87990. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  87991. attribs.push(BABYLON.VertexBuffer.UVKind);
  87992. defines.push("#define UV1");
  87993. }
  87994. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  87995. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  87996. defines.push("#define UV2");
  87997. }
  87998. }
  87999. // Bones
  88000. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  88001. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  88002. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  88003. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  88004. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  88005. }
  88006. else {
  88007. defines.push("#define NUM_BONE_INFLUENCERS 0");
  88008. }
  88009. // Instances
  88010. if (useInstances) {
  88011. defines.push("#define INSTANCES");
  88012. attribs.push("world0");
  88013. attribs.push("world1");
  88014. attribs.push("world2");
  88015. attribs.push("world3");
  88016. }
  88017. // Get correct effect
  88018. var join = defines.join("\n");
  88019. if (this._cachedDefines !== join) {
  88020. this._cachedDefines = join;
  88021. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  88022. }
  88023. return this._volumetricLightScatteringPass.isReady();
  88024. };
  88025. /**
  88026. * Sets the new light position for light scattering effect
  88027. * @param position The new custom light position
  88028. */
  88029. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  88030. this.customMeshPosition = position;
  88031. };
  88032. /**
  88033. * Returns the light position for light scattering effect
  88034. * @return {BABYLON.Vector3} The custom light position
  88035. */
  88036. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  88037. return this.customMeshPosition;
  88038. };
  88039. /**
  88040. * Disposes the internal assets and detaches the post-process from the camera
  88041. */
  88042. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  88043. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  88044. if (rttIndex !== -1) {
  88045. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  88046. }
  88047. this._volumetricLightScatteringRTT.dispose();
  88048. _super.prototype.dispose.call(this, camera);
  88049. };
  88050. /**
  88051. * Returns the render target texture used by the post-process
  88052. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  88053. */
  88054. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  88055. return this._volumetricLightScatteringRTT;
  88056. };
  88057. // Private methods
  88058. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  88059. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  88060. return true;
  88061. }
  88062. return false;
  88063. };
  88064. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  88065. var _this = this;
  88066. var engine = scene.getEngine();
  88067. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  88068. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88069. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88070. this._volumetricLightScatteringRTT.renderList = null;
  88071. this._volumetricLightScatteringRTT.renderParticles = false;
  88072. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  88073. var camera = this.getCamera();
  88074. if (camera) {
  88075. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  88076. }
  88077. else {
  88078. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  88079. }
  88080. // Custom render function for submeshes
  88081. var renderSubMesh = function (subMesh) {
  88082. var mesh = subMesh.getRenderingMesh();
  88083. if (_this._meshExcluded(mesh)) {
  88084. return;
  88085. }
  88086. var material = subMesh.getMaterial();
  88087. if (!material) {
  88088. return;
  88089. }
  88090. var scene = mesh.getScene();
  88091. var engine = scene.getEngine();
  88092. // Culling
  88093. engine.setState(material.backFaceCulling);
  88094. // Managing instances
  88095. var batch = mesh._getInstancesRenderList(subMesh._id);
  88096. if (batch.mustReturn) {
  88097. return;
  88098. }
  88099. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  88100. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  88101. var effect = _this._volumetricLightScatteringPass;
  88102. if (mesh === _this.mesh) {
  88103. if (subMesh.effect) {
  88104. effect = subMesh.effect;
  88105. }
  88106. else {
  88107. effect = material.getEffect();
  88108. }
  88109. }
  88110. engine.enableEffect(effect);
  88111. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  88112. if (mesh === _this.mesh) {
  88113. material.bind(mesh.getWorldMatrix(), mesh);
  88114. }
  88115. else {
  88116. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  88117. // Alpha test
  88118. if (material && material.needAlphaTesting()) {
  88119. var alphaTexture = material.getAlphaTestTexture();
  88120. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  88121. if (alphaTexture) {
  88122. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  88123. }
  88124. }
  88125. // Bones
  88126. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  88127. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  88128. }
  88129. }
  88130. // Draw
  88131. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  88132. }
  88133. };
  88134. // Render target texture callbacks
  88135. var savedSceneClearColor;
  88136. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  88137. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  88138. savedSceneClearColor = scene.clearColor;
  88139. scene.clearColor = sceneClearColor;
  88140. });
  88141. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  88142. scene.clearColor = savedSceneClearColor;
  88143. });
  88144. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  88145. var engine = scene.getEngine();
  88146. var index;
  88147. if (depthOnlySubMeshes.length) {
  88148. engine.setColorWrite(false);
  88149. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  88150. renderSubMesh(depthOnlySubMeshes.data[index]);
  88151. }
  88152. engine.setColorWrite(true);
  88153. }
  88154. for (index = 0; index < opaqueSubMeshes.length; index++) {
  88155. renderSubMesh(opaqueSubMeshes.data[index]);
  88156. }
  88157. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  88158. renderSubMesh(alphaTestSubMeshes.data[index]);
  88159. }
  88160. if (transparentSubMeshes.length) {
  88161. // Sort sub meshes
  88162. for (index = 0; index < transparentSubMeshes.length; index++) {
  88163. var submesh = transparentSubMeshes.data[index];
  88164. var boundingInfo = submesh.getBoundingInfo();
  88165. if (boundingInfo && scene.activeCamera) {
  88166. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  88167. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  88168. }
  88169. }
  88170. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  88171. sortedArray.sort(function (a, b) {
  88172. // Alpha index first
  88173. if (a._alphaIndex > b._alphaIndex) {
  88174. return 1;
  88175. }
  88176. if (a._alphaIndex < b._alphaIndex) {
  88177. return -1;
  88178. }
  88179. // Then distance to camera
  88180. if (a._distanceToCamera < b._distanceToCamera) {
  88181. return 1;
  88182. }
  88183. if (a._distanceToCamera > b._distanceToCamera) {
  88184. return -1;
  88185. }
  88186. return 0;
  88187. });
  88188. // Render sub meshes
  88189. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  88190. for (index = 0; index < sortedArray.length; index++) {
  88191. renderSubMesh(sortedArray[index]);
  88192. }
  88193. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  88194. }
  88195. };
  88196. };
  88197. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  88198. var transform = scene.getTransformMatrix();
  88199. var meshPosition;
  88200. if (this.useCustomMeshPosition) {
  88201. meshPosition = this.customMeshPosition;
  88202. }
  88203. else if (this.attachedNode) {
  88204. meshPosition = this.attachedNode.position;
  88205. }
  88206. else {
  88207. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  88208. }
  88209. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  88210. this._screenCoordinates.x = pos.x / this._viewPort.width;
  88211. this._screenCoordinates.y = pos.y / this._viewPort.height;
  88212. if (this.invert)
  88213. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  88214. };
  88215. // Static methods
  88216. /**
  88217. * Creates a default mesh for the Volumeric Light Scattering post-process
  88218. * @param name The mesh name
  88219. * @param scene The scene where to create the mesh
  88220. * @return {BABYLON.Mesh} the default mesh
  88221. */
  88222. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  88223. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  88224. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  88225. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  88226. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  88227. mesh.material = material;
  88228. return mesh;
  88229. };
  88230. __decorate([
  88231. BABYLON.serializeAsVector3()
  88232. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  88233. __decorate([
  88234. BABYLON.serialize()
  88235. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  88236. __decorate([
  88237. BABYLON.serialize()
  88238. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  88239. __decorate([
  88240. BABYLON.serializeAsMeshReference()
  88241. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  88242. __decorate([
  88243. BABYLON.serialize()
  88244. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  88245. __decorate([
  88246. BABYLON.serialize()
  88247. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  88248. __decorate([
  88249. BABYLON.serialize()
  88250. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  88251. __decorate([
  88252. BABYLON.serialize()
  88253. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  88254. __decorate([
  88255. BABYLON.serialize()
  88256. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  88257. return VolumetricLightScatteringPostProcess;
  88258. }(BABYLON.PostProcess));
  88259. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  88260. })(BABYLON || (BABYLON = {}));
  88261. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  88262. var BABYLON;
  88263. (function (BABYLON) {
  88264. /**
  88265. *
  88266. * This post-process allows the modification of rendered colors by using
  88267. * a 'look-up table' (LUT). This effect is also called Color Grading.
  88268. *
  88269. * The object needs to be provided an url to a texture containing the color
  88270. * look-up table: the texture must be 256 pixels wide and 16 pixels high.
  88271. * Use an image editing software to tweak the LUT to match your needs.
  88272. *
  88273. * For an example of a color LUT, see here:
  88274. * @see http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  88275. * For explanations on color grading, see here:
  88276. * @see http://udn.epicgames.com/Three/ColorGrading.html
  88277. *
  88278. */
  88279. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  88280. __extends(ColorCorrectionPostProcess, _super);
  88281. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  88282. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  88283. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  88284. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  88285. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88286. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88287. _this.onApply = function (effect) {
  88288. effect.setTexture("colorTable", _this._colorTableTexture);
  88289. };
  88290. return _this;
  88291. }
  88292. return ColorCorrectionPostProcess;
  88293. }(BABYLON.PostProcess));
  88294. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  88295. })(BABYLON || (BABYLON = {}));
  88296. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  88297. var BABYLON;
  88298. (function (BABYLON) {
  88299. /** Defines operator used for tonemapping */
  88300. var TonemappingOperator;
  88301. (function (TonemappingOperator) {
  88302. /** Hable */
  88303. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  88304. /** Reinhard */
  88305. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  88306. /** HejiDawson */
  88307. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  88308. /** Photographic */
  88309. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  88310. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  88311. ;
  88312. /**
  88313. * Defines a post process to apply tone mapping
  88314. */
  88315. var TonemapPostProcess = /** @class */ (function (_super) {
  88316. __extends(TonemapPostProcess, _super);
  88317. /**
  88318. * Creates a new TonemapPostProcess
  88319. * @param name defines the name of the postprocess
  88320. * @param _operator defines the operator to use
  88321. * @param exposureAdjustment defines the required exposure adjustement
  88322. * @param camera defines the camera to use (can be null)
  88323. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  88324. * @param engine defines the hosting engine (can be ignore if camera is set)
  88325. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  88326. */
  88327. function TonemapPostProcess(name, _operator,
  88328. /** Defines the required exposure adjustement */
  88329. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  88330. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  88331. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  88332. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  88333. _this._operator = _operator;
  88334. _this.exposureAdjustment = exposureAdjustment;
  88335. var defines = "#define ";
  88336. if (_this._operator === TonemappingOperator.Hable)
  88337. defines += "HABLE_TONEMAPPING";
  88338. else if (_this._operator === TonemappingOperator.Reinhard)
  88339. defines += "REINHARD_TONEMAPPING";
  88340. else if (_this._operator === TonemappingOperator.HejiDawson)
  88341. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  88342. else if (_this._operator === TonemappingOperator.Photographic)
  88343. defines += "PHOTOGRAPHIC_TONEMAPPING";
  88344. //sadly a second call to create the effect.
  88345. _this.updateEffect(defines);
  88346. _this.onApply = function (effect) {
  88347. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  88348. };
  88349. return _this;
  88350. }
  88351. return TonemapPostProcess;
  88352. }(BABYLON.PostProcess));
  88353. BABYLON.TonemapPostProcess = TonemapPostProcess;
  88354. })(BABYLON || (BABYLON = {}));
  88355. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  88356. var BABYLON;
  88357. (function (BABYLON) {
  88358. /**
  88359. * DisplayPassPostProcess which produces an output the same as it's input
  88360. */
  88361. var DisplayPassPostProcess = /** @class */ (function (_super) {
  88362. __extends(DisplayPassPostProcess, _super);
  88363. /**
  88364. * Creates the DisplayPassPostProcess
  88365. * @param name The name of the effect.
  88366. * @param options The required width/height ratio to downsize to before computing the render pass.
  88367. * @param camera The camera to apply the render pass to.
  88368. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88369. * @param engine The engine which the post process will be applied. (default: current engine)
  88370. * @param reusable If the post process can be reused on the same frame. (default: false)
  88371. */
  88372. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  88373. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  88374. }
  88375. return DisplayPassPostProcess;
  88376. }(BABYLON.PostProcess));
  88377. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  88378. })(BABYLON || (BABYLON = {}));
  88379. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  88380. var BABYLON;
  88381. (function (BABYLON) {
  88382. /**
  88383. * Extracts highlights from the image
  88384. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  88385. */
  88386. var HighlightsPostProcess = /** @class */ (function (_super) {
  88387. __extends(HighlightsPostProcess, _super);
  88388. /**
  88389. * Extracts highlights from the image
  88390. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  88391. * @param name The name of the effect.
  88392. * @param options The required width/height ratio to downsize to before computing the render pass.
  88393. * @param camera The camera to apply the render pass to.
  88394. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88395. * @param engine The engine which the post process will be applied. (default: current engine)
  88396. * @param reusable If the post process can be reused on the same frame. (default: false)
  88397. * @param textureType Type of texture for the post process (default: Engine.TEXTURETYPE_UNSIGNED_INT)
  88398. */
  88399. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  88400. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  88401. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  88402. }
  88403. return HighlightsPostProcess;
  88404. }(BABYLON.PostProcess));
  88405. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  88406. })(BABYLON || (BABYLON = {}));
  88407. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  88408. var BABYLON;
  88409. (function (BABYLON) {
  88410. /**
  88411. * ImageProcessingPostProcess
  88412. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#imageprocessing
  88413. */
  88414. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  88415. __extends(ImageProcessingPostProcess, _super);
  88416. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  88417. if (camera === void 0) { camera = null; }
  88418. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  88419. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  88420. _this._fromLinearSpace = true;
  88421. /**
  88422. * Defines cache preventing GC.
  88423. */
  88424. _this._defines = {
  88425. IMAGEPROCESSING: false,
  88426. VIGNETTE: false,
  88427. VIGNETTEBLENDMODEMULTIPLY: false,
  88428. VIGNETTEBLENDMODEOPAQUE: false,
  88429. TONEMAPPING: false,
  88430. TONEMAPPING_ACES: false,
  88431. CONTRAST: false,
  88432. COLORCURVES: false,
  88433. COLORGRADING: false,
  88434. COLORGRADING3D: false,
  88435. FROMLINEARSPACE: false,
  88436. SAMPLER3DGREENDEPTH: false,
  88437. SAMPLER3DBGRMAP: false,
  88438. IMAGEPROCESSINGPOSTPROCESS: false,
  88439. EXPOSURE: false,
  88440. };
  88441. // Setup the configuration as forced by the constructor. This would then not force the
  88442. // scene materials output in linear space and let untouched the default forward pass.
  88443. if (imageProcessingConfiguration) {
  88444. imageProcessingConfiguration.applyByPostProcess = true;
  88445. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  88446. // This will cause the shader to be compiled
  88447. _this.fromLinearSpace = false;
  88448. }
  88449. // Setup the default processing configuration to the scene.
  88450. else {
  88451. _this._attachImageProcessingConfiguration(null, true);
  88452. _this.imageProcessingConfiguration.applyByPostProcess = true;
  88453. }
  88454. _this.onApply = function (effect) {
  88455. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  88456. };
  88457. return _this;
  88458. }
  88459. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  88460. /**
  88461. * Gets the image processing configuration used either in this material.
  88462. */
  88463. get: function () {
  88464. return this._imageProcessingConfiguration;
  88465. },
  88466. /**
  88467. * Sets the Default image processing configuration used either in the this material.
  88468. *
  88469. * If sets to null, the scene one is in use.
  88470. */
  88471. set: function (value) {
  88472. this._attachImageProcessingConfiguration(value);
  88473. },
  88474. enumerable: true,
  88475. configurable: true
  88476. });
  88477. /**
  88478. * Attaches a new image processing configuration to the PBR Material.
  88479. * @param configuration
  88480. */
  88481. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  88482. var _this = this;
  88483. if (doNotBuild === void 0) { doNotBuild = false; }
  88484. if (configuration === this._imageProcessingConfiguration) {
  88485. return;
  88486. }
  88487. // Detaches observer.
  88488. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  88489. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  88490. }
  88491. // Pick the scene configuration if needed.
  88492. if (!configuration) {
  88493. var scene = null;
  88494. var engine = this.getEngine();
  88495. var camera = this.getCamera();
  88496. if (camera) {
  88497. scene = camera.getScene();
  88498. }
  88499. else if (engine && engine.scenes) {
  88500. var scenes = engine.scenes;
  88501. scene = scenes[scenes.length - 1];
  88502. }
  88503. else {
  88504. scene = BABYLON.Engine.LastCreatedScene;
  88505. }
  88506. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  88507. }
  88508. else {
  88509. this._imageProcessingConfiguration = configuration;
  88510. }
  88511. // Attaches observer.
  88512. if (this._imageProcessingConfiguration) {
  88513. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  88514. _this._updateParameters();
  88515. });
  88516. }
  88517. // Ensure the effect will be rebuilt.
  88518. if (!doNotBuild) {
  88519. this._updateParameters();
  88520. }
  88521. };
  88522. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  88523. /**
  88524. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  88525. */
  88526. get: function () {
  88527. return this.imageProcessingConfiguration.colorCurves;
  88528. },
  88529. /**
  88530. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  88531. */
  88532. set: function (value) {
  88533. this.imageProcessingConfiguration.colorCurves = value;
  88534. },
  88535. enumerable: true,
  88536. configurable: true
  88537. });
  88538. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  88539. /**
  88540. * Gets wether the color curves effect is enabled.
  88541. */
  88542. get: function () {
  88543. return this.imageProcessingConfiguration.colorCurvesEnabled;
  88544. },
  88545. /**
  88546. * Sets wether the color curves effect is enabled.
  88547. */
  88548. set: function (value) {
  88549. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  88550. },
  88551. enumerable: true,
  88552. configurable: true
  88553. });
  88554. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  88555. /**
  88556. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  88557. */
  88558. get: function () {
  88559. return this.imageProcessingConfiguration.colorGradingTexture;
  88560. },
  88561. /**
  88562. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  88563. */
  88564. set: function (value) {
  88565. this.imageProcessingConfiguration.colorGradingTexture = value;
  88566. },
  88567. enumerable: true,
  88568. configurable: true
  88569. });
  88570. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  88571. /**
  88572. * Gets wether the color grading effect is enabled.
  88573. */
  88574. get: function () {
  88575. return this.imageProcessingConfiguration.colorGradingEnabled;
  88576. },
  88577. /**
  88578. * Gets wether the color grading effect is enabled.
  88579. */
  88580. set: function (value) {
  88581. this.imageProcessingConfiguration.colorGradingEnabled = value;
  88582. },
  88583. enumerable: true,
  88584. configurable: true
  88585. });
  88586. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  88587. /**
  88588. * Gets exposure used in the effect.
  88589. */
  88590. get: function () {
  88591. return this.imageProcessingConfiguration.exposure;
  88592. },
  88593. /**
  88594. * Sets exposure used in the effect.
  88595. */
  88596. set: function (value) {
  88597. this.imageProcessingConfiguration.exposure = value;
  88598. },
  88599. enumerable: true,
  88600. configurable: true
  88601. });
  88602. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  88603. /**
  88604. * Gets wether tonemapping is enabled or not.
  88605. */
  88606. get: function () {
  88607. return this._imageProcessingConfiguration.toneMappingEnabled;
  88608. },
  88609. /**
  88610. * Sets wether tonemapping is enabled or not
  88611. */
  88612. set: function (value) {
  88613. this._imageProcessingConfiguration.toneMappingEnabled = value;
  88614. },
  88615. enumerable: true,
  88616. configurable: true
  88617. });
  88618. ;
  88619. ;
  88620. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  88621. /**
  88622. * Gets contrast used in the effect.
  88623. */
  88624. get: function () {
  88625. return this.imageProcessingConfiguration.contrast;
  88626. },
  88627. /**
  88628. * Sets contrast used in the effect.
  88629. */
  88630. set: function (value) {
  88631. this.imageProcessingConfiguration.contrast = value;
  88632. },
  88633. enumerable: true,
  88634. configurable: true
  88635. });
  88636. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  88637. /**
  88638. * Gets Vignette stretch size.
  88639. */
  88640. get: function () {
  88641. return this.imageProcessingConfiguration.vignetteStretch;
  88642. },
  88643. /**
  88644. * Sets Vignette stretch size.
  88645. */
  88646. set: function (value) {
  88647. this.imageProcessingConfiguration.vignetteStretch = value;
  88648. },
  88649. enumerable: true,
  88650. configurable: true
  88651. });
  88652. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  88653. /**
  88654. * Gets Vignette centre X Offset.
  88655. */
  88656. get: function () {
  88657. return this.imageProcessingConfiguration.vignetteCentreX;
  88658. },
  88659. /**
  88660. * Sets Vignette centre X Offset.
  88661. */
  88662. set: function (value) {
  88663. this.imageProcessingConfiguration.vignetteCentreX = value;
  88664. },
  88665. enumerable: true,
  88666. configurable: true
  88667. });
  88668. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  88669. /**
  88670. * Gets Vignette centre Y Offset.
  88671. */
  88672. get: function () {
  88673. return this.imageProcessingConfiguration.vignetteCentreY;
  88674. },
  88675. /**
  88676. * Sets Vignette centre Y Offset.
  88677. */
  88678. set: function (value) {
  88679. this.imageProcessingConfiguration.vignetteCentreY = value;
  88680. },
  88681. enumerable: true,
  88682. configurable: true
  88683. });
  88684. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  88685. /**
  88686. * Gets Vignette weight or intensity of the vignette effect.
  88687. */
  88688. get: function () {
  88689. return this.imageProcessingConfiguration.vignetteWeight;
  88690. },
  88691. /**
  88692. * Sets Vignette weight or intensity of the vignette effect.
  88693. */
  88694. set: function (value) {
  88695. this.imageProcessingConfiguration.vignetteWeight = value;
  88696. },
  88697. enumerable: true,
  88698. configurable: true
  88699. });
  88700. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  88701. /**
  88702. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  88703. * if vignetteEnabled is set to true.
  88704. */
  88705. get: function () {
  88706. return this.imageProcessingConfiguration.vignetteColor;
  88707. },
  88708. /**
  88709. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  88710. * if vignetteEnabled is set to true.
  88711. */
  88712. set: function (value) {
  88713. this.imageProcessingConfiguration.vignetteColor = value;
  88714. },
  88715. enumerable: true,
  88716. configurable: true
  88717. });
  88718. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  88719. /**
  88720. * Gets Camera field of view used by the Vignette effect.
  88721. */
  88722. get: function () {
  88723. return this.imageProcessingConfiguration.vignetteCameraFov;
  88724. },
  88725. /**
  88726. * Sets Camera field of view used by the Vignette effect.
  88727. */
  88728. set: function (value) {
  88729. this.imageProcessingConfiguration.vignetteCameraFov = value;
  88730. },
  88731. enumerable: true,
  88732. configurable: true
  88733. });
  88734. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  88735. /**
  88736. * Gets the vignette blend mode allowing different kind of effect.
  88737. */
  88738. get: function () {
  88739. return this.imageProcessingConfiguration.vignetteBlendMode;
  88740. },
  88741. /**
  88742. * Sets the vignette blend mode allowing different kind of effect.
  88743. */
  88744. set: function (value) {
  88745. this.imageProcessingConfiguration.vignetteBlendMode = value;
  88746. },
  88747. enumerable: true,
  88748. configurable: true
  88749. });
  88750. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  88751. /**
  88752. * Gets wether the vignette effect is enabled.
  88753. */
  88754. get: function () {
  88755. return this.imageProcessingConfiguration.vignetteEnabled;
  88756. },
  88757. /**
  88758. * Sets wether the vignette effect is enabled.
  88759. */
  88760. set: function (value) {
  88761. this.imageProcessingConfiguration.vignetteEnabled = value;
  88762. },
  88763. enumerable: true,
  88764. configurable: true
  88765. });
  88766. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  88767. /**
  88768. * Gets wether the input of the processing is in Gamma or Linear Space.
  88769. */
  88770. get: function () {
  88771. return this._fromLinearSpace;
  88772. },
  88773. /**
  88774. * Sets wether the input of the processing is in Gamma or Linear Space.
  88775. */
  88776. set: function (value) {
  88777. if (this._fromLinearSpace === value) {
  88778. return;
  88779. }
  88780. this._fromLinearSpace = value;
  88781. this._updateParameters();
  88782. },
  88783. enumerable: true,
  88784. configurable: true
  88785. });
  88786. /**
  88787. * "ImageProcessingPostProcess"
  88788. * @returns "ImageProcessingPostProcess"
  88789. */
  88790. ImageProcessingPostProcess.prototype.getClassName = function () {
  88791. return "ImageProcessingPostProcess";
  88792. };
  88793. ImageProcessingPostProcess.prototype._updateParameters = function () {
  88794. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  88795. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  88796. var defines = "";
  88797. for (var define in this._defines) {
  88798. if (this._defines[define]) {
  88799. defines += "#define " + define + ";\r\n";
  88800. }
  88801. }
  88802. var samplers = ["textureSampler"];
  88803. var uniforms = ["scale"];
  88804. if (BABYLON.ImageProcessingConfiguration) {
  88805. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  88806. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  88807. }
  88808. this.updateEffect(defines, uniforms, samplers);
  88809. };
  88810. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  88811. _super.prototype.dispose.call(this, camera);
  88812. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  88813. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  88814. }
  88815. if (this._imageProcessingConfiguration) {
  88816. this.imageProcessingConfiguration.applyByPostProcess = false;
  88817. }
  88818. };
  88819. __decorate([
  88820. BABYLON.serialize()
  88821. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  88822. return ImageProcessingPostProcess;
  88823. }(BABYLON.PostProcess));
  88824. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  88825. })(BABYLON || (BABYLON = {}));
  88826. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  88827. var BABYLON;
  88828. (function (BABYLON) {
  88829. /**
  88830. * Class used to store bone information
  88831. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  88832. */
  88833. var Bone = /** @class */ (function (_super) {
  88834. __extends(Bone, _super);
  88835. /**
  88836. * Create a new bone
  88837. * @param name defines the bone name
  88838. * @param skeleton defines the parent skeleton
  88839. * @param parentBone defines the parent (can be null if the bone is the root)
  88840. * @param localMatrix defines the local matrix
  88841. * @param restPose defines the rest pose matrix
  88842. * @param baseMatrix defines the base matrix
  88843. * @param index defines index of the bone in the hiearchy
  88844. */
  88845. function Bone(
  88846. /**
  88847. * defines the bone name
  88848. */
  88849. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  88850. if (parentBone === void 0) { parentBone = null; }
  88851. if (localMatrix === void 0) { localMatrix = null; }
  88852. if (restPose === void 0) { restPose = null; }
  88853. if (baseMatrix === void 0) { baseMatrix = null; }
  88854. if (index === void 0) { index = null; }
  88855. var _this = _super.call(this, name, skeleton.getScene()) || this;
  88856. _this.name = name;
  88857. /**
  88858. * Gets the list of child bones
  88859. */
  88860. _this.children = new Array();
  88861. /** Gets the animations associated with this bone */
  88862. _this.animations = new Array();
  88863. /**
  88864. * @hidden Internal only
  88865. * Set this value to map this bone to a different index in the transform matrices
  88866. * Set this value to -1 to exclude the bone from the transform matrices
  88867. */
  88868. _this._index = null;
  88869. _this._absoluteTransform = new BABYLON.Matrix();
  88870. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  88871. _this._scalingDeterminant = 1;
  88872. _this._worldTransform = new BABYLON.Matrix();
  88873. _this._needToDecompose = true;
  88874. _this._needToCompose = false;
  88875. _this._skeleton = skeleton;
  88876. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  88877. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  88878. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  88879. _this._index = index;
  88880. skeleton.bones.push(_this);
  88881. _this.setParent(parentBone, false);
  88882. if (baseMatrix || localMatrix) {
  88883. _this._updateDifferenceMatrix();
  88884. }
  88885. return _this;
  88886. }
  88887. Object.defineProperty(Bone.prototype, "_matrix", {
  88888. /** @hidden */
  88889. get: function () {
  88890. this._compose();
  88891. return this._localMatrix;
  88892. },
  88893. /** @hidden */
  88894. set: function (value) {
  88895. this._localMatrix.copyFrom(value);
  88896. this._needToDecompose = true;
  88897. },
  88898. enumerable: true,
  88899. configurable: true
  88900. });
  88901. // Members
  88902. /**
  88903. * Gets the parent skeleton
  88904. * @returns a skeleton
  88905. */
  88906. Bone.prototype.getSkeleton = function () {
  88907. return this._skeleton;
  88908. };
  88909. /**
  88910. * Gets parent bone
  88911. * @returns a bone or null if the bone is the root of the bone hierarchy
  88912. */
  88913. Bone.prototype.getParent = function () {
  88914. return this._parent;
  88915. };
  88916. /**
  88917. * Sets the parent bone
  88918. * @param parent defines the parent (can be null if the bone is the root)
  88919. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  88920. */
  88921. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  88922. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  88923. if (this._parent === parent) {
  88924. return;
  88925. }
  88926. if (this._parent) {
  88927. var index = this._parent.children.indexOf(this);
  88928. if (index !== -1) {
  88929. this._parent.children.splice(index, 1);
  88930. }
  88931. }
  88932. this._parent = parent;
  88933. if (this._parent) {
  88934. this._parent.children.push(this);
  88935. }
  88936. if (updateDifferenceMatrix) {
  88937. this._updateDifferenceMatrix();
  88938. }
  88939. this.markAsDirty();
  88940. };
  88941. /**
  88942. * Gets the local matrix
  88943. * @returns a matrix
  88944. */
  88945. Bone.prototype.getLocalMatrix = function () {
  88946. this._compose();
  88947. return this._localMatrix;
  88948. };
  88949. /**
  88950. * Gets the base matrix (initial matrix which remains unchanged)
  88951. * @returns a matrix
  88952. */
  88953. Bone.prototype.getBaseMatrix = function () {
  88954. return this._baseMatrix;
  88955. };
  88956. /**
  88957. * Gets the rest pose matrix
  88958. * @returns a matrix
  88959. */
  88960. Bone.prototype.getRestPose = function () {
  88961. return this._restPose;
  88962. };
  88963. /**
  88964. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  88965. */
  88966. Bone.prototype.getWorldMatrix = function () {
  88967. return this._worldTransform;
  88968. };
  88969. /**
  88970. * Sets the local matrix to rest pose matrix
  88971. */
  88972. Bone.prototype.returnToRest = function () {
  88973. this.updateMatrix(this._restPose.clone());
  88974. };
  88975. /**
  88976. * Gets the inverse of the absolute transform matrix.
  88977. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  88978. * @returns a matrix
  88979. */
  88980. Bone.prototype.getInvertedAbsoluteTransform = function () {
  88981. return this._invertedAbsoluteTransform;
  88982. };
  88983. /**
  88984. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  88985. * @returns a matrix
  88986. */
  88987. Bone.prototype.getAbsoluteTransform = function () {
  88988. return this._absoluteTransform;
  88989. };
  88990. Object.defineProperty(Bone.prototype, "position", {
  88991. // Properties (matches AbstractMesh properties)
  88992. /** Gets or sets current position (in local space) */
  88993. get: function () {
  88994. this._decompose();
  88995. return this._localPosition;
  88996. },
  88997. set: function (newPosition) {
  88998. this._decompose();
  88999. this._localPosition.copyFrom(newPosition);
  89000. this._markAsDirtyAndCompose();
  89001. },
  89002. enumerable: true,
  89003. configurable: true
  89004. });
  89005. Object.defineProperty(Bone.prototype, "rotation", {
  89006. /** Gets or sets current rotation (in local space) */
  89007. get: function () {
  89008. return this.getRotation();
  89009. },
  89010. set: function (newRotation) {
  89011. this.setRotation(newRotation);
  89012. },
  89013. enumerable: true,
  89014. configurable: true
  89015. });
  89016. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  89017. /** Gets or sets current rotation quaternion (in local space) */
  89018. get: function () {
  89019. this._decompose();
  89020. return this._localRotation;
  89021. },
  89022. set: function (newRotation) {
  89023. this.setRotationQuaternion(newRotation);
  89024. },
  89025. enumerable: true,
  89026. configurable: true
  89027. });
  89028. Object.defineProperty(Bone.prototype, "scaling", {
  89029. /** Gets or sets current scaling (in local space) */
  89030. get: function () {
  89031. return this.getScale();
  89032. },
  89033. set: function (newScaling) {
  89034. this.setScale(newScaling);
  89035. },
  89036. enumerable: true,
  89037. configurable: true
  89038. });
  89039. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  89040. /**
  89041. * Gets the animation properties override
  89042. */
  89043. get: function () {
  89044. return this._skeleton.animationPropertiesOverride;
  89045. },
  89046. enumerable: true,
  89047. configurable: true
  89048. });
  89049. // Methods
  89050. Bone.prototype._decompose = function () {
  89051. if (!this._needToDecompose) {
  89052. return;
  89053. }
  89054. this._needToDecompose = false;
  89055. if (!this._localScaling) {
  89056. this._localScaling = BABYLON.Vector3.Zero();
  89057. this._localRotation = BABYLON.Quaternion.Zero();
  89058. this._localPosition = BABYLON.Vector3.Zero();
  89059. }
  89060. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  89061. };
  89062. Bone.prototype._compose = function () {
  89063. if (!this._needToCompose) {
  89064. return;
  89065. }
  89066. this._needToCompose = false;
  89067. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  89068. };
  89069. /**
  89070. * Update the base and local matrices
  89071. * @param matrix defines the new base or local matrix
  89072. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  89073. * @param updateLocalMatrix defines if the local matrix should be updated
  89074. */
  89075. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  89076. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  89077. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  89078. this._baseMatrix.copyFrom(matrix);
  89079. if (updateDifferenceMatrix) {
  89080. this._updateDifferenceMatrix();
  89081. }
  89082. if (updateLocalMatrix) {
  89083. this._localMatrix.copyFrom(matrix);
  89084. this._markAsDirtyAndDecompose();
  89085. }
  89086. else {
  89087. this.markAsDirty();
  89088. }
  89089. };
  89090. /** @hidden */
  89091. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  89092. if (updateChildren === void 0) { updateChildren = true; }
  89093. if (!rootMatrix) {
  89094. rootMatrix = this._baseMatrix;
  89095. }
  89096. if (this._parent) {
  89097. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  89098. }
  89099. else {
  89100. this._absoluteTransform.copyFrom(rootMatrix);
  89101. }
  89102. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  89103. if (updateChildren) {
  89104. for (var index = 0; index < this.children.length; index++) {
  89105. this.children[index]._updateDifferenceMatrix();
  89106. }
  89107. }
  89108. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  89109. };
  89110. /**
  89111. * Flag the bone as dirty (Forcing it to update everything)
  89112. */
  89113. Bone.prototype.markAsDirty = function () {
  89114. this._currentRenderId++;
  89115. this._childRenderId++;
  89116. this._skeleton._markAsDirty();
  89117. };
  89118. Bone.prototype._markAsDirtyAndCompose = function () {
  89119. this.markAsDirty();
  89120. this._needToCompose = true;
  89121. };
  89122. Bone.prototype._markAsDirtyAndDecompose = function () {
  89123. this.markAsDirty();
  89124. this._needToDecompose = true;
  89125. };
  89126. /**
  89127. * Copy an animation range from another bone
  89128. * @param source defines the source bone
  89129. * @param rangeName defines the range name to copy
  89130. * @param frameOffset defines the frame offset
  89131. * @param rescaleAsRequired defines if rescaling must be applied if required
  89132. * @param skelDimensionsRatio defines the scaling ratio
  89133. * @returns true if operation was successful
  89134. */
  89135. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  89136. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  89137. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  89138. // all animation may be coming from a library skeleton, so may need to create animation
  89139. if (this.animations.length === 0) {
  89140. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  89141. this.animations[0].setKeys([]);
  89142. }
  89143. // get animation info / verify there is such a range from the source bone
  89144. var sourceRange = source.animations[0].getRange(rangeName);
  89145. if (!sourceRange) {
  89146. return false;
  89147. }
  89148. var from = sourceRange.from;
  89149. var to = sourceRange.to;
  89150. var sourceKeys = source.animations[0].getKeys();
  89151. // rescaling prep
  89152. var sourceBoneLength = source.length;
  89153. var sourceParent = source.getParent();
  89154. var parent = this.getParent();
  89155. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  89156. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  89157. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  89158. var destKeys = this.animations[0].getKeys();
  89159. // loop vars declaration
  89160. var orig;
  89161. var origTranslation;
  89162. var mat;
  89163. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  89164. orig = sourceKeys[key];
  89165. if (orig.frame >= from && orig.frame <= to) {
  89166. if (rescaleAsRequired) {
  89167. mat = orig.value.clone();
  89168. // scale based on parent ratio, when bone has parent
  89169. if (parentScalingReqd) {
  89170. origTranslation = mat.getTranslation();
  89171. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  89172. // scale based on skeleton dimension ratio when root bone, and value is passed
  89173. }
  89174. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  89175. origTranslation = mat.getTranslation();
  89176. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  89177. // use original when root bone, and no data for skelDimensionsRatio
  89178. }
  89179. else {
  89180. mat = orig.value;
  89181. }
  89182. }
  89183. else {
  89184. mat = orig.value;
  89185. }
  89186. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  89187. }
  89188. }
  89189. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  89190. return true;
  89191. };
  89192. /**
  89193. * Translate the bone in local or world space
  89194. * @param vec The amount to translate the bone
  89195. * @param space The space that the translation is in
  89196. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89197. */
  89198. Bone.prototype.translate = function (vec, space, mesh) {
  89199. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89200. var lm = this.getLocalMatrix();
  89201. if (space == BABYLON.Space.LOCAL) {
  89202. lm.m[12] += vec.x;
  89203. lm.m[13] += vec.y;
  89204. lm.m[14] += vec.z;
  89205. }
  89206. else {
  89207. var wm = null;
  89208. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  89209. if (mesh) {
  89210. wm = mesh.getWorldMatrix();
  89211. }
  89212. this._skeleton.computeAbsoluteTransforms();
  89213. var tmat = Bone._tmpMats[0];
  89214. var tvec = Bone._tmpVecs[0];
  89215. if (this._parent) {
  89216. if (mesh && wm) {
  89217. tmat.copyFrom(this._parent.getAbsoluteTransform());
  89218. tmat.multiplyToRef(wm, tmat);
  89219. }
  89220. else {
  89221. tmat.copyFrom(this._parent.getAbsoluteTransform());
  89222. }
  89223. }
  89224. tmat.m[12] = 0;
  89225. tmat.m[13] = 0;
  89226. tmat.m[14] = 0;
  89227. tmat.invert();
  89228. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  89229. lm.m[12] += tvec.x;
  89230. lm.m[13] += tvec.y;
  89231. lm.m[14] += tvec.z;
  89232. }
  89233. this._markAsDirtyAndDecompose();
  89234. };
  89235. /**
  89236. * Set the postion of the bone in local or world space
  89237. * @param position The position to set the bone
  89238. * @param space The space that the position is in
  89239. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89240. */
  89241. Bone.prototype.setPosition = function (position, space, mesh) {
  89242. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89243. var lm = this.getLocalMatrix();
  89244. if (space == BABYLON.Space.LOCAL) {
  89245. lm.m[12] = position.x;
  89246. lm.m[13] = position.y;
  89247. lm.m[14] = position.z;
  89248. }
  89249. else {
  89250. var wm = null;
  89251. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  89252. if (mesh) {
  89253. wm = mesh.getWorldMatrix();
  89254. }
  89255. this._skeleton.computeAbsoluteTransforms();
  89256. var tmat = Bone._tmpMats[0];
  89257. var vec = Bone._tmpVecs[0];
  89258. if (this._parent) {
  89259. if (mesh && wm) {
  89260. tmat.copyFrom(this._parent.getAbsoluteTransform());
  89261. tmat.multiplyToRef(wm, tmat);
  89262. }
  89263. else {
  89264. tmat.copyFrom(this._parent.getAbsoluteTransform());
  89265. }
  89266. }
  89267. tmat.invert();
  89268. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  89269. lm.m[12] = vec.x;
  89270. lm.m[13] = vec.y;
  89271. lm.m[14] = vec.z;
  89272. }
  89273. this._markAsDirtyAndDecompose();
  89274. };
  89275. /**
  89276. * Set the absolute position of the bone (world space)
  89277. * @param position The position to set the bone
  89278. * @param mesh The mesh that this bone is attached to
  89279. */
  89280. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  89281. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  89282. };
  89283. /**
  89284. * Scale the bone on the x, y and z axes (in local space)
  89285. * @param x The amount to scale the bone on the x axis
  89286. * @param y The amount to scale the bone on the y axis
  89287. * @param z The amount to scale the bone on the z axis
  89288. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  89289. */
  89290. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  89291. if (scaleChildren === void 0) { scaleChildren = false; }
  89292. var locMat = this.getLocalMatrix();
  89293. // Apply new scaling on top of current local matrix
  89294. var scaleMat = Bone._tmpMats[0];
  89295. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  89296. scaleMat.multiplyToRef(locMat, locMat);
  89297. // Invert scaling matrix and apply the inverse to all children
  89298. scaleMat.invert();
  89299. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  89300. var child = _a[_i];
  89301. var cm = child.getLocalMatrix();
  89302. cm.multiplyToRef(scaleMat, cm);
  89303. cm.m[12] *= x;
  89304. cm.m[13] *= y;
  89305. cm.m[14] *= z;
  89306. child._markAsDirtyAndDecompose();
  89307. }
  89308. this._markAsDirtyAndDecompose();
  89309. if (scaleChildren) {
  89310. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  89311. var child = _c[_b];
  89312. child.scale(x, y, z, scaleChildren);
  89313. }
  89314. }
  89315. };
  89316. /**
  89317. * Set the bone scaling in local space
  89318. * @param scale defines the scaling vector
  89319. */
  89320. Bone.prototype.setScale = function (scale) {
  89321. this._decompose();
  89322. this._localScaling.copyFrom(scale);
  89323. this._markAsDirtyAndCompose();
  89324. };
  89325. /**
  89326. * Gets the current scaling in local space
  89327. * @returns the current scaling vector
  89328. */
  89329. Bone.prototype.getScale = function () {
  89330. this._decompose();
  89331. return this._localScaling;
  89332. };
  89333. /**
  89334. * Gets the current scaling in local space and stores it in a target vector
  89335. * @param result defines the target vector
  89336. */
  89337. Bone.prototype.getScaleToRef = function (result) {
  89338. this._decompose();
  89339. result.copyFrom(this._localScaling);
  89340. };
  89341. /**
  89342. * Set the yaw, pitch, and roll of the bone in local or world space
  89343. * @param yaw The rotation of the bone on the y axis
  89344. * @param pitch The rotation of the bone on the x axis
  89345. * @param roll The rotation of the bone on the z axis
  89346. * @param space The space that the axes of rotation are in
  89347. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89348. */
  89349. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  89350. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89351. if (space === BABYLON.Space.LOCAL) {
  89352. var quat = Bone._tmpQuat;
  89353. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  89354. this.setRotationQuaternion(quat, space, mesh);
  89355. return;
  89356. }
  89357. var rotMatInv = Bone._tmpMats[0];
  89358. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  89359. return;
  89360. }
  89361. var rotMat = Bone._tmpMats[1];
  89362. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  89363. rotMatInv.multiplyToRef(rotMat, rotMat);
  89364. this._rotateWithMatrix(rotMat, space, mesh);
  89365. };
  89366. /**
  89367. * Add a rotation to the bone on an axis in local or world space
  89368. * @param axis The axis to rotate the bone on
  89369. * @param amount The amount to rotate the bone
  89370. * @param space The space that the axis is in
  89371. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89372. */
  89373. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  89374. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89375. var rmat = Bone._tmpMats[0];
  89376. rmat.m[12] = 0;
  89377. rmat.m[13] = 0;
  89378. rmat.m[14] = 0;
  89379. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  89380. this._rotateWithMatrix(rmat, space, mesh);
  89381. };
  89382. /**
  89383. * Set the rotation of the bone to a particular axis angle in local or world space
  89384. * @param axis The axis to rotate the bone on
  89385. * @param angle The angle that the bone should be rotated to
  89386. * @param space The space that the axis is in
  89387. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89388. */
  89389. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  89390. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89391. if (space === BABYLON.Space.LOCAL) {
  89392. var quat = Bone._tmpQuat;
  89393. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  89394. this.setRotationQuaternion(quat, space, mesh);
  89395. return;
  89396. }
  89397. var rotMatInv = Bone._tmpMats[0];
  89398. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  89399. return;
  89400. }
  89401. var rotMat = Bone._tmpMats[1];
  89402. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  89403. rotMatInv.multiplyToRef(rotMat, rotMat);
  89404. this._rotateWithMatrix(rotMat, space, mesh);
  89405. };
  89406. /**
  89407. * Set the euler rotation of the bone in local of world space
  89408. * @param rotation The euler rotation that the bone should be set to
  89409. * @param space The space that the rotation is in
  89410. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89411. */
  89412. Bone.prototype.setRotation = function (rotation, space, mesh) {
  89413. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89414. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  89415. };
  89416. /**
  89417. * Set the quaternion rotation of the bone in local of world space
  89418. * @param quat The quaternion rotation that the bone should be set to
  89419. * @param space The space that the rotation is in
  89420. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89421. */
  89422. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  89423. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89424. if (space === BABYLON.Space.LOCAL) {
  89425. this._decompose();
  89426. this._localRotation.copyFrom(quat);
  89427. this._markAsDirtyAndCompose();
  89428. return;
  89429. }
  89430. var rotMatInv = Bone._tmpMats[0];
  89431. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  89432. return;
  89433. }
  89434. var rotMat = Bone._tmpMats[1];
  89435. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  89436. rotMatInv.multiplyToRef(rotMat, rotMat);
  89437. this._rotateWithMatrix(rotMat, space, mesh);
  89438. };
  89439. /**
  89440. * Set the rotation matrix of the bone in local of world space
  89441. * @param rotMat The rotation matrix that the bone should be set to
  89442. * @param space The space that the rotation is in
  89443. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89444. */
  89445. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  89446. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89447. if (space === BABYLON.Space.LOCAL) {
  89448. var quat = Bone._tmpQuat;
  89449. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  89450. this.setRotationQuaternion(quat, space, mesh);
  89451. return;
  89452. }
  89453. var rotMatInv = Bone._tmpMats[0];
  89454. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  89455. return;
  89456. }
  89457. var rotMat2 = Bone._tmpMats[1];
  89458. rotMat2.copyFrom(rotMat);
  89459. rotMatInv.multiplyToRef(rotMat, rotMat2);
  89460. this._rotateWithMatrix(rotMat2, space, mesh);
  89461. };
  89462. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  89463. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89464. var lmat = this.getLocalMatrix();
  89465. var lx = lmat.m[12];
  89466. var ly = lmat.m[13];
  89467. var lz = lmat.m[14];
  89468. var parent = this.getParent();
  89469. var parentScale = Bone._tmpMats[3];
  89470. var parentScaleInv = Bone._tmpMats[4];
  89471. if (parent && space == BABYLON.Space.WORLD) {
  89472. if (mesh) {
  89473. parentScale.copyFrom(mesh.getWorldMatrix());
  89474. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  89475. }
  89476. else {
  89477. parentScale.copyFrom(parent.getAbsoluteTransform());
  89478. }
  89479. parentScaleInv.copyFrom(parentScale);
  89480. parentScaleInv.invert();
  89481. lmat.multiplyToRef(parentScale, lmat);
  89482. lmat.multiplyToRef(rmat, lmat);
  89483. lmat.multiplyToRef(parentScaleInv, lmat);
  89484. }
  89485. else {
  89486. if (space == BABYLON.Space.WORLD && mesh) {
  89487. parentScale.copyFrom(mesh.getWorldMatrix());
  89488. parentScaleInv.copyFrom(parentScale);
  89489. parentScaleInv.invert();
  89490. lmat.multiplyToRef(parentScale, lmat);
  89491. lmat.multiplyToRef(rmat, lmat);
  89492. lmat.multiplyToRef(parentScaleInv, lmat);
  89493. }
  89494. else {
  89495. lmat.multiplyToRef(rmat, lmat);
  89496. }
  89497. }
  89498. lmat.m[12] = lx;
  89499. lmat.m[13] = ly;
  89500. lmat.m[14] = lz;
  89501. this.computeAbsoluteTransforms();
  89502. this._markAsDirtyAndDecompose();
  89503. };
  89504. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  89505. var scaleMatrix = Bone._tmpMats[2];
  89506. rotMatInv.copyFrom(this.getAbsoluteTransform());
  89507. if (mesh) {
  89508. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  89509. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  89510. }
  89511. rotMatInv.invert();
  89512. if (isNaN(rotMatInv.m[0])) {
  89513. // Matrix failed to invert.
  89514. // This can happen if scale is zero for example.
  89515. return false;
  89516. }
  89517. scaleMatrix.m[0] *= this._scalingDeterminant;
  89518. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  89519. return true;
  89520. };
  89521. /**
  89522. * Get the position of the bone in local or world space
  89523. * @param space The space that the returned position is in
  89524. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89525. * @returns The position of the bone
  89526. */
  89527. Bone.prototype.getPosition = function (space, mesh) {
  89528. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89529. if (mesh === void 0) { mesh = null; }
  89530. var pos = BABYLON.Vector3.Zero();
  89531. this.getPositionToRef(space, mesh, pos);
  89532. return pos;
  89533. };
  89534. /**
  89535. * Copy the position of the bone to a vector3 in local or world space
  89536. * @param space The space that the returned position is in
  89537. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89538. * @param result The vector3 to copy the position to
  89539. */
  89540. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  89541. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89542. if (space == BABYLON.Space.LOCAL) {
  89543. var lm = this.getLocalMatrix();
  89544. result.x = lm.m[12];
  89545. result.y = lm.m[13];
  89546. result.z = lm.m[14];
  89547. }
  89548. else {
  89549. var wm = null;
  89550. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  89551. if (mesh) {
  89552. wm = mesh.getWorldMatrix();
  89553. }
  89554. this._skeleton.computeAbsoluteTransforms();
  89555. var tmat = Bone._tmpMats[0];
  89556. if (mesh && wm) {
  89557. tmat.copyFrom(this.getAbsoluteTransform());
  89558. tmat.multiplyToRef(wm, tmat);
  89559. }
  89560. else {
  89561. tmat = this.getAbsoluteTransform();
  89562. }
  89563. result.x = tmat.m[12];
  89564. result.y = tmat.m[13];
  89565. result.z = tmat.m[14];
  89566. }
  89567. };
  89568. /**
  89569. * Get the absolute position of the bone (world space)
  89570. * @param mesh The mesh that this bone is attached to
  89571. * @returns The absolute position of the bone
  89572. */
  89573. Bone.prototype.getAbsolutePosition = function (mesh) {
  89574. if (mesh === void 0) { mesh = null; }
  89575. var pos = BABYLON.Vector3.Zero();
  89576. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  89577. return pos;
  89578. };
  89579. /**
  89580. * Copy the absolute position of the bone (world space) to the result param
  89581. * @param mesh The mesh that this bone is attached to
  89582. * @param result The vector3 to copy the absolute position to
  89583. */
  89584. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  89585. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  89586. };
  89587. /**
  89588. * Compute the absolute transforms of this bone and its children
  89589. */
  89590. Bone.prototype.computeAbsoluteTransforms = function () {
  89591. this._compose();
  89592. if (this._parent) {
  89593. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  89594. }
  89595. else {
  89596. this._absoluteTransform.copyFrom(this._localMatrix);
  89597. var poseMatrix = this._skeleton.getPoseMatrix();
  89598. if (poseMatrix) {
  89599. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  89600. }
  89601. }
  89602. var children = this.children;
  89603. var len = children.length;
  89604. for (var i = 0; i < len; i++) {
  89605. children[i].computeAbsoluteTransforms();
  89606. }
  89607. };
  89608. /**
  89609. * Get the world direction from an axis that is in the local space of the bone
  89610. * @param localAxis The local direction that is used to compute the world direction
  89611. * @param mesh The mesh that this bone is attached to
  89612. * @returns The world direction
  89613. */
  89614. Bone.prototype.getDirection = function (localAxis, mesh) {
  89615. if (mesh === void 0) { mesh = null; }
  89616. var result = BABYLON.Vector3.Zero();
  89617. this.getDirectionToRef(localAxis, mesh, result);
  89618. return result;
  89619. };
  89620. /**
  89621. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  89622. * @param localAxis The local direction that is used to compute the world direction
  89623. * @param mesh The mesh that this bone is attached to
  89624. * @param result The vector3 that the world direction will be copied to
  89625. */
  89626. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  89627. if (mesh === void 0) { mesh = null; }
  89628. var wm = null;
  89629. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  89630. if (mesh) {
  89631. wm = mesh.getWorldMatrix();
  89632. }
  89633. this._skeleton.computeAbsoluteTransforms();
  89634. var mat = Bone._tmpMats[0];
  89635. mat.copyFrom(this.getAbsoluteTransform());
  89636. if (mesh && wm) {
  89637. mat.multiplyToRef(wm, mat);
  89638. }
  89639. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  89640. result.normalize();
  89641. };
  89642. /**
  89643. * Get the euler rotation of the bone in local or world space
  89644. * @param space The space that the rotation should be in
  89645. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89646. * @returns The euler rotation
  89647. */
  89648. Bone.prototype.getRotation = function (space, mesh) {
  89649. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89650. if (mesh === void 0) { mesh = null; }
  89651. var result = BABYLON.Vector3.Zero();
  89652. this.getRotationToRef(space, mesh, result);
  89653. return result;
  89654. };
  89655. /**
  89656. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  89657. * @param space The space that the rotation should be in
  89658. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89659. * @param result The vector3 that the rotation should be copied to
  89660. */
  89661. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  89662. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89663. if (mesh === void 0) { mesh = null; }
  89664. var quat = Bone._tmpQuat;
  89665. this.getRotationQuaternionToRef(space, mesh, quat);
  89666. quat.toEulerAnglesToRef(result);
  89667. };
  89668. /**
  89669. * Get the quaternion rotation of the bone in either local or world space
  89670. * @param space The space that the rotation should be in
  89671. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89672. * @returns The quaternion rotation
  89673. */
  89674. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  89675. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89676. if (mesh === void 0) { mesh = null; }
  89677. var result = BABYLON.Quaternion.Identity();
  89678. this.getRotationQuaternionToRef(space, mesh, result);
  89679. return result;
  89680. };
  89681. /**
  89682. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  89683. * @param space The space that the rotation should be in
  89684. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89685. * @param result The quaternion that the rotation should be copied to
  89686. */
  89687. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  89688. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89689. if (mesh === void 0) { mesh = null; }
  89690. if (space == BABYLON.Space.LOCAL) {
  89691. this._decompose();
  89692. result.copyFrom(this._localRotation);
  89693. }
  89694. else {
  89695. var mat = Bone._tmpMats[0];
  89696. var amat = this.getAbsoluteTransform();
  89697. if (mesh) {
  89698. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  89699. }
  89700. else {
  89701. mat.copyFrom(amat);
  89702. }
  89703. mat.m[0] *= this._scalingDeterminant;
  89704. mat.m[1] *= this._scalingDeterminant;
  89705. mat.m[2] *= this._scalingDeterminant;
  89706. mat.decompose(undefined, result, undefined);
  89707. }
  89708. };
  89709. /**
  89710. * Get the rotation matrix of the bone in local or world space
  89711. * @param space The space that the rotation should be in
  89712. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89713. * @returns The rotation matrix
  89714. */
  89715. Bone.prototype.getRotationMatrix = function (space, mesh) {
  89716. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89717. var result = BABYLON.Matrix.Identity();
  89718. this.getRotationMatrixToRef(space, mesh, result);
  89719. return result;
  89720. };
  89721. /**
  89722. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  89723. * @param space The space that the rotation should be in
  89724. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89725. * @param result The quaternion that the rotation should be copied to
  89726. */
  89727. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  89728. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89729. if (space == BABYLON.Space.LOCAL) {
  89730. this.getLocalMatrix().getRotationMatrixToRef(result);
  89731. }
  89732. else {
  89733. var mat = Bone._tmpMats[0];
  89734. var amat = this.getAbsoluteTransform();
  89735. if (mesh) {
  89736. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  89737. }
  89738. else {
  89739. mat.copyFrom(amat);
  89740. }
  89741. mat.m[0] *= this._scalingDeterminant;
  89742. mat.m[1] *= this._scalingDeterminant;
  89743. mat.m[2] *= this._scalingDeterminant;
  89744. mat.getRotationMatrixToRef(result);
  89745. }
  89746. };
  89747. /**
  89748. * Get the world position of a point that is in the local space of the bone
  89749. * @param position The local position
  89750. * @param mesh The mesh that this bone is attached to
  89751. * @returns The world position
  89752. */
  89753. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  89754. if (mesh === void 0) { mesh = null; }
  89755. var result = BABYLON.Vector3.Zero();
  89756. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  89757. return result;
  89758. };
  89759. /**
  89760. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  89761. * @param position The local position
  89762. * @param mesh The mesh that this bone is attached to
  89763. * @param result The vector3 that the world position should be copied to
  89764. */
  89765. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  89766. if (mesh === void 0) { mesh = null; }
  89767. var wm = null;
  89768. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  89769. if (mesh) {
  89770. wm = mesh.getWorldMatrix();
  89771. }
  89772. this._skeleton.computeAbsoluteTransforms();
  89773. var tmat = Bone._tmpMats[0];
  89774. if (mesh && wm) {
  89775. tmat.copyFrom(this.getAbsoluteTransform());
  89776. tmat.multiplyToRef(wm, tmat);
  89777. }
  89778. else {
  89779. tmat = this.getAbsoluteTransform();
  89780. }
  89781. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  89782. };
  89783. /**
  89784. * Get the local position of a point that is in world space
  89785. * @param position The world position
  89786. * @param mesh The mesh that this bone is attached to
  89787. * @returns The local position
  89788. */
  89789. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  89790. if (mesh === void 0) { mesh = null; }
  89791. var result = BABYLON.Vector3.Zero();
  89792. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  89793. return result;
  89794. };
  89795. /**
  89796. * Get the local position of a point that is in world space and copy it to the result param
  89797. * @param position The world position
  89798. * @param mesh The mesh that this bone is attached to
  89799. * @param result The vector3 that the local position should be copied to
  89800. */
  89801. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  89802. if (mesh === void 0) { mesh = null; }
  89803. var wm = null;
  89804. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  89805. if (mesh) {
  89806. wm = mesh.getWorldMatrix();
  89807. }
  89808. this._skeleton.computeAbsoluteTransforms();
  89809. var tmat = Bone._tmpMats[0];
  89810. tmat.copyFrom(this.getAbsoluteTransform());
  89811. if (mesh && wm) {
  89812. tmat.multiplyToRef(wm, tmat);
  89813. }
  89814. tmat.invert();
  89815. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  89816. };
  89817. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  89818. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  89819. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  89820. return Bone;
  89821. }(BABYLON.Node));
  89822. BABYLON.Bone = Bone;
  89823. })(BABYLON || (BABYLON = {}));
  89824. //# sourceMappingURL=babylon.bone.js.map
  89825. var BABYLON;
  89826. (function (BABYLON) {
  89827. /**
  89828. * Class used to apply inverse kinematics to bones
  89829. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  89830. */
  89831. var BoneIKController = /** @class */ (function () {
  89832. /**
  89833. * Creates a new BoneIKController
  89834. * @param mesh defines the mesh to control
  89835. * @param bone defines the bone to control
  89836. * @param options defines options to set up the controller
  89837. */
  89838. function BoneIKController(mesh, bone, options) {
  89839. /**
  89840. * Gets or sets the target position
  89841. */
  89842. this.targetPosition = BABYLON.Vector3.Zero();
  89843. /**
  89844. * Gets or sets the pole target position
  89845. */
  89846. this.poleTargetPosition = BABYLON.Vector3.Zero();
  89847. /**
  89848. * Gets or sets the pole target local offset
  89849. */
  89850. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  89851. /**
  89852. * Gets or sets the pole angle
  89853. */
  89854. this.poleAngle = 0;
  89855. /**
  89856. * 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)
  89857. */
  89858. this.slerpAmount = 1;
  89859. this._bone1Quat = BABYLON.Quaternion.Identity();
  89860. this._bone1Mat = BABYLON.Matrix.Identity();
  89861. this._bone2Ang = Math.PI;
  89862. this._maxAngle = Math.PI;
  89863. this._rightHandedSystem = false;
  89864. this._bendAxis = BABYLON.Vector3.Right();
  89865. this._slerping = false;
  89866. this._adjustRoll = 0;
  89867. this._bone2 = bone;
  89868. this._bone1 = bone.getParent();
  89869. if (!this._bone1) {
  89870. return;
  89871. }
  89872. this.mesh = mesh;
  89873. var bonePos = bone.getPosition();
  89874. if (bone.getAbsoluteTransform().determinant() > 0) {
  89875. this._rightHandedSystem = true;
  89876. this._bendAxis.x = 0;
  89877. this._bendAxis.y = 0;
  89878. this._bendAxis.z = -1;
  89879. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  89880. this._adjustRoll = Math.PI * .5;
  89881. this._bendAxis.z = 1;
  89882. }
  89883. }
  89884. if (this._bone1.length) {
  89885. var boneScale1 = this._bone1.getScale();
  89886. var boneScale2 = this._bone2.getScale();
  89887. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  89888. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  89889. }
  89890. else if (this._bone1.children[0]) {
  89891. mesh.computeWorldMatrix(true);
  89892. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  89893. var pos2 = this._bone2.getAbsolutePosition(mesh);
  89894. var pos3 = this._bone1.getAbsolutePosition(mesh);
  89895. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  89896. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  89897. }
  89898. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  89899. this.maxAngle = Math.PI;
  89900. if (options) {
  89901. if (options.targetMesh) {
  89902. this.targetMesh = options.targetMesh;
  89903. this.targetMesh.computeWorldMatrix(true);
  89904. }
  89905. if (options.poleTargetMesh) {
  89906. this.poleTargetMesh = options.poleTargetMesh;
  89907. this.poleTargetMesh.computeWorldMatrix(true);
  89908. }
  89909. else if (options.poleTargetBone) {
  89910. this.poleTargetBone = options.poleTargetBone;
  89911. }
  89912. else if (this._bone1.getParent()) {
  89913. this.poleTargetBone = this._bone1.getParent();
  89914. }
  89915. if (options.poleTargetLocalOffset) {
  89916. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  89917. }
  89918. if (options.poleAngle) {
  89919. this.poleAngle = options.poleAngle;
  89920. }
  89921. if (options.bendAxis) {
  89922. this._bendAxis.copyFrom(options.bendAxis);
  89923. }
  89924. if (options.maxAngle) {
  89925. this.maxAngle = options.maxAngle;
  89926. }
  89927. if (options.slerpAmount) {
  89928. this.slerpAmount = options.slerpAmount;
  89929. }
  89930. }
  89931. }
  89932. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  89933. /**
  89934. * Gets or sets maximum allowed angle
  89935. */
  89936. get: function () {
  89937. return this._maxAngle;
  89938. },
  89939. set: function (value) {
  89940. this._setMaxAngle(value);
  89941. },
  89942. enumerable: true,
  89943. configurable: true
  89944. });
  89945. BoneIKController.prototype._setMaxAngle = function (ang) {
  89946. if (ang < 0) {
  89947. ang = 0;
  89948. }
  89949. if (ang > Math.PI || ang == undefined) {
  89950. ang = Math.PI;
  89951. }
  89952. this._maxAngle = ang;
  89953. var a = this._bone1Length;
  89954. var b = this._bone2Length;
  89955. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  89956. };
  89957. /**
  89958. * Force the controller to update the bones
  89959. */
  89960. BoneIKController.prototype.update = function () {
  89961. var bone1 = this._bone1;
  89962. if (!bone1) {
  89963. return;
  89964. }
  89965. var target = this.targetPosition;
  89966. var poleTarget = this.poleTargetPosition;
  89967. var mat1 = BoneIKController._tmpMats[0];
  89968. var mat2 = BoneIKController._tmpMats[1];
  89969. if (this.targetMesh) {
  89970. target.copyFrom(this.targetMesh.getAbsolutePosition());
  89971. }
  89972. if (this.poleTargetBone) {
  89973. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  89974. }
  89975. else if (this.poleTargetMesh) {
  89976. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  89977. }
  89978. var bonePos = BoneIKController._tmpVecs[0];
  89979. var zaxis = BoneIKController._tmpVecs[1];
  89980. var xaxis = BoneIKController._tmpVecs[2];
  89981. var yaxis = BoneIKController._tmpVecs[3];
  89982. var upAxis = BoneIKController._tmpVecs[4];
  89983. var _tmpQuat = BoneIKController._tmpQuat;
  89984. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  89985. poleTarget.subtractToRef(bonePos, upAxis);
  89986. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  89987. upAxis.y = 1;
  89988. }
  89989. else {
  89990. upAxis.normalize();
  89991. }
  89992. target.subtractToRef(bonePos, yaxis);
  89993. yaxis.normalize();
  89994. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  89995. zaxis.normalize();
  89996. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  89997. xaxis.normalize();
  89998. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  89999. var a = this._bone1Length;
  90000. var b = this._bone2Length;
  90001. var c = BABYLON.Vector3.Distance(bonePos, target);
  90002. if (this._maxReach > 0) {
  90003. c = Math.min(this._maxReach, c);
  90004. }
  90005. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  90006. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  90007. if (acosa > 1) {
  90008. acosa = 1;
  90009. }
  90010. if (acosb > 1) {
  90011. acosb = 1;
  90012. }
  90013. if (acosa < -1) {
  90014. acosa = -1;
  90015. }
  90016. if (acosb < -1) {
  90017. acosb = -1;
  90018. }
  90019. var angA = Math.acos(acosa);
  90020. var angB = Math.acos(acosb);
  90021. var angC = -angA - angB;
  90022. if (this._rightHandedSystem) {
  90023. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  90024. mat2.multiplyToRef(mat1, mat1);
  90025. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  90026. mat2.multiplyToRef(mat1, mat1);
  90027. }
  90028. else {
  90029. var _tmpVec = BoneIKController._tmpVecs[5];
  90030. _tmpVec.copyFrom(this._bendAxis);
  90031. _tmpVec.x *= -1;
  90032. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  90033. mat2.multiplyToRef(mat1, mat1);
  90034. }
  90035. if (this.poleAngle) {
  90036. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  90037. mat1.multiplyToRef(mat2, mat1);
  90038. }
  90039. if (this._bone1) {
  90040. if (this.slerpAmount < 1) {
  90041. if (!this._slerping) {
  90042. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  90043. }
  90044. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  90045. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  90046. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  90047. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  90048. this._slerping = true;
  90049. }
  90050. else {
  90051. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  90052. this._bone1Mat.copyFrom(mat1);
  90053. this._slerping = false;
  90054. }
  90055. }
  90056. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  90057. this._bone2Ang = angC;
  90058. };
  90059. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  90060. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  90061. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  90062. return BoneIKController;
  90063. }());
  90064. BABYLON.BoneIKController = BoneIKController;
  90065. })(BABYLON || (BABYLON = {}));
  90066. //# sourceMappingURL=babylon.boneIKController.js.map
  90067. var BABYLON;
  90068. (function (BABYLON) {
  90069. /**
  90070. * Class used to make a bone look toward a point in space
  90071. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  90072. */
  90073. var BoneLookController = /** @class */ (function () {
  90074. /**
  90075. * Create a BoneLookController
  90076. * @param mesh the mesh that the bone belongs to
  90077. * @param bone the bone that will be looking to the target
  90078. * @param target the target Vector3 to look at
  90079. * @param settings optional settings:
  90080. * * maxYaw: the maximum angle the bone will yaw to
  90081. * * minYaw: the minimum angle the bone will yaw to
  90082. * * maxPitch: the maximum angle the bone will pitch to
  90083. * * minPitch: the minimum angle the bone will yaw to
  90084. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  90085. * * upAxis: the up axis of the coordinate system
  90086. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  90087. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  90088. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  90089. * * adjustYaw: used to make an adjustment to the yaw of the bone
  90090. * * adjustPitch: used to make an adjustment to the pitch of the bone
  90091. * * adjustRoll: used to make an adjustment to the roll of the bone
  90092. **/
  90093. function BoneLookController(mesh, bone, target, options) {
  90094. /**
  90095. * The up axis of the coordinate system that is used when the bone is rotated
  90096. */
  90097. this.upAxis = BABYLON.Vector3.Up();
  90098. /**
  90099. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  90100. */
  90101. this.upAxisSpace = BABYLON.Space.LOCAL;
  90102. /**
  90103. * Used to make an adjustment to the yaw of the bone
  90104. */
  90105. this.adjustYaw = 0;
  90106. /**
  90107. * Used to make an adjustment to the pitch of the bone
  90108. */
  90109. this.adjustPitch = 0;
  90110. /**
  90111. * Used to make an adjustment to the roll of the bone
  90112. */
  90113. this.adjustRoll = 0;
  90114. /**
  90115. * 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)
  90116. */
  90117. this.slerpAmount = 1;
  90118. this._boneQuat = BABYLON.Quaternion.Identity();
  90119. this._slerping = false;
  90120. this._firstFrameSkipped = false;
  90121. this._fowardAxis = BABYLON.Vector3.Forward();
  90122. this.mesh = mesh;
  90123. this.bone = bone;
  90124. this.target = target;
  90125. if (options) {
  90126. if (options.adjustYaw) {
  90127. this.adjustYaw = options.adjustYaw;
  90128. }
  90129. if (options.adjustPitch) {
  90130. this.adjustPitch = options.adjustPitch;
  90131. }
  90132. if (options.adjustRoll) {
  90133. this.adjustRoll = options.adjustRoll;
  90134. }
  90135. if (options.maxYaw != null) {
  90136. this.maxYaw = options.maxYaw;
  90137. }
  90138. else {
  90139. this.maxYaw = Math.PI;
  90140. }
  90141. if (options.minYaw != null) {
  90142. this.minYaw = options.minYaw;
  90143. }
  90144. else {
  90145. this.minYaw = -Math.PI;
  90146. }
  90147. if (options.maxPitch != null) {
  90148. this.maxPitch = options.maxPitch;
  90149. }
  90150. else {
  90151. this.maxPitch = Math.PI;
  90152. }
  90153. if (options.minPitch != null) {
  90154. this.minPitch = options.minPitch;
  90155. }
  90156. else {
  90157. this.minPitch = -Math.PI;
  90158. }
  90159. if (options.slerpAmount != null) {
  90160. this.slerpAmount = options.slerpAmount;
  90161. }
  90162. if (options.upAxis != null) {
  90163. this.upAxis = options.upAxis;
  90164. }
  90165. if (options.upAxisSpace != null) {
  90166. this.upAxisSpace = options.upAxisSpace;
  90167. }
  90168. if (options.yawAxis != null || options.pitchAxis != null) {
  90169. var newYawAxis = BABYLON.Axis.Y;
  90170. var newPitchAxis = BABYLON.Axis.X;
  90171. if (options.yawAxis != null) {
  90172. newYawAxis = options.yawAxis.clone();
  90173. newYawAxis.normalize();
  90174. }
  90175. if (options.pitchAxis != null) {
  90176. newPitchAxis = options.pitchAxis.clone();
  90177. newPitchAxis.normalize();
  90178. }
  90179. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  90180. this._transformYawPitch = BABYLON.Matrix.Identity();
  90181. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  90182. this._transformYawPitchInv = this._transformYawPitch.clone();
  90183. this._transformYawPitch.invert();
  90184. }
  90185. }
  90186. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  90187. this.upAxisSpace = BABYLON.Space.LOCAL;
  90188. }
  90189. }
  90190. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  90191. /**
  90192. * Gets or sets the minimum yaw angle that the bone can look to
  90193. */
  90194. get: function () {
  90195. return this._minYaw;
  90196. },
  90197. set: function (value) {
  90198. this._minYaw = value;
  90199. this._minYawSin = Math.sin(value);
  90200. this._minYawCos = Math.cos(value);
  90201. if (this._maxYaw != null) {
  90202. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  90203. this._yawRange = this._maxYaw - this._minYaw;
  90204. }
  90205. },
  90206. enumerable: true,
  90207. configurable: true
  90208. });
  90209. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  90210. /**
  90211. * Gets or sets the maximum yaw angle that the bone can look to
  90212. */
  90213. get: function () {
  90214. return this._maxYaw;
  90215. },
  90216. set: function (value) {
  90217. this._maxYaw = value;
  90218. this._maxYawSin = Math.sin(value);
  90219. this._maxYawCos = Math.cos(value);
  90220. if (this._minYaw != null) {
  90221. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  90222. this._yawRange = this._maxYaw - this._minYaw;
  90223. }
  90224. },
  90225. enumerable: true,
  90226. configurable: true
  90227. });
  90228. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  90229. /**
  90230. * Gets or sets the minimum pitch angle that the bone can look to
  90231. */
  90232. get: function () {
  90233. return this._minPitch;
  90234. },
  90235. set: function (value) {
  90236. this._minPitch = value;
  90237. this._minPitchTan = Math.tan(value);
  90238. },
  90239. enumerable: true,
  90240. configurable: true
  90241. });
  90242. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  90243. /**
  90244. * Gets or sets the maximum pitch angle that the bone can look to
  90245. */
  90246. get: function () {
  90247. return this._maxPitch;
  90248. },
  90249. set: function (value) {
  90250. this._maxPitch = value;
  90251. this._maxPitchTan = Math.tan(value);
  90252. },
  90253. enumerable: true,
  90254. configurable: true
  90255. });
  90256. /**
  90257. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  90258. */
  90259. BoneLookController.prototype.update = function () {
  90260. //skip the first frame when slerping so that the mesh rotation is correct
  90261. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  90262. this._firstFrameSkipped = true;
  90263. return;
  90264. }
  90265. var bone = this.bone;
  90266. var bonePos = BoneLookController._tmpVecs[0];
  90267. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  90268. var target = this.target;
  90269. var _tmpMat1 = BoneLookController._tmpMats[0];
  90270. var _tmpMat2 = BoneLookController._tmpMats[1];
  90271. var mesh = this.mesh;
  90272. var parentBone = bone.getParent();
  90273. var upAxis = BoneLookController._tmpVecs[1];
  90274. upAxis.copyFrom(this.upAxis);
  90275. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  90276. if (this._transformYawPitch) {
  90277. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  90278. }
  90279. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  90280. }
  90281. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  90282. mesh.getDirectionToRef(upAxis, upAxis);
  90283. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  90284. upAxis.normalize();
  90285. }
  90286. }
  90287. var checkYaw = false;
  90288. var checkPitch = false;
  90289. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  90290. checkYaw = true;
  90291. }
  90292. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  90293. checkPitch = true;
  90294. }
  90295. if (checkYaw || checkPitch) {
  90296. var spaceMat = BoneLookController._tmpMats[2];
  90297. var spaceMatInv = BoneLookController._tmpMats[3];
  90298. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  90299. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  90300. }
  90301. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  90302. spaceMat.copyFrom(mesh.getWorldMatrix());
  90303. }
  90304. else {
  90305. var forwardAxis = BoneLookController._tmpVecs[2];
  90306. forwardAxis.copyFrom(this._fowardAxis);
  90307. if (this._transformYawPitch) {
  90308. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  90309. }
  90310. if (parentBone) {
  90311. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  90312. }
  90313. else {
  90314. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  90315. }
  90316. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  90317. rightAxis.normalize();
  90318. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  90319. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  90320. }
  90321. spaceMat.invertToRef(spaceMatInv);
  90322. var xzlen = null;
  90323. if (checkPitch) {
  90324. var localTarget = BoneLookController._tmpVecs[3];
  90325. target.subtractToRef(bonePos, localTarget);
  90326. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  90327. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  90328. var pitch = Math.atan2(localTarget.y, xzlen);
  90329. var newPitch = pitch;
  90330. if (pitch > this._maxPitch) {
  90331. localTarget.y = this._maxPitchTan * xzlen;
  90332. newPitch = this._maxPitch;
  90333. }
  90334. else if (pitch < this._minPitch) {
  90335. localTarget.y = this._minPitchTan * xzlen;
  90336. newPitch = this._minPitch;
  90337. }
  90338. if (pitch != newPitch) {
  90339. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  90340. localTarget.addInPlace(bonePos);
  90341. target = localTarget;
  90342. }
  90343. }
  90344. if (checkYaw) {
  90345. var localTarget = BoneLookController._tmpVecs[4];
  90346. target.subtractToRef(bonePos, localTarget);
  90347. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  90348. var yaw = Math.atan2(localTarget.x, localTarget.z);
  90349. var newYaw = yaw;
  90350. if (yaw > this._maxYaw || yaw < this._minYaw) {
  90351. if (xzlen == null) {
  90352. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  90353. }
  90354. if (this._yawRange > Math.PI) {
  90355. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  90356. localTarget.z = this._maxYawCos * xzlen;
  90357. localTarget.x = this._maxYawSin * xzlen;
  90358. newYaw = this._maxYaw;
  90359. }
  90360. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  90361. localTarget.z = this._minYawCos * xzlen;
  90362. localTarget.x = this._minYawSin * xzlen;
  90363. newYaw = this._minYaw;
  90364. }
  90365. }
  90366. else {
  90367. if (yaw > this._maxYaw) {
  90368. localTarget.z = this._maxYawCos * xzlen;
  90369. localTarget.x = this._maxYawSin * xzlen;
  90370. newYaw = this._maxYaw;
  90371. }
  90372. else if (yaw < this._minYaw) {
  90373. localTarget.z = this._minYawCos * xzlen;
  90374. localTarget.x = this._minYawSin * xzlen;
  90375. newYaw = this._minYaw;
  90376. }
  90377. }
  90378. }
  90379. if (this._slerping && this._yawRange > Math.PI) {
  90380. //are we going to be crossing into the min/max region?
  90381. var boneFwd = BoneLookController._tmpVecs[8];
  90382. boneFwd.copyFrom(BABYLON.Axis.Z);
  90383. if (this._transformYawPitch) {
  90384. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  90385. }
  90386. var boneRotMat = BoneLookController._tmpMats[4];
  90387. this._boneQuat.toRotationMatrix(boneRotMat);
  90388. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  90389. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  90390. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  90391. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  90392. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  90393. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  90394. if (angBtwTar > angBtwMidYaw) {
  90395. if (xzlen == null) {
  90396. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  90397. }
  90398. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  90399. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  90400. if (angBtwMin < angBtwMax) {
  90401. newYaw = boneYaw + Math.PI * .75;
  90402. localTarget.z = Math.cos(newYaw) * xzlen;
  90403. localTarget.x = Math.sin(newYaw) * xzlen;
  90404. }
  90405. else {
  90406. newYaw = boneYaw - Math.PI * .75;
  90407. localTarget.z = Math.cos(newYaw) * xzlen;
  90408. localTarget.x = Math.sin(newYaw) * xzlen;
  90409. }
  90410. }
  90411. }
  90412. if (yaw != newYaw) {
  90413. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  90414. localTarget.addInPlace(bonePos);
  90415. target = localTarget;
  90416. }
  90417. }
  90418. }
  90419. var zaxis = BoneLookController._tmpVecs[5];
  90420. var xaxis = BoneLookController._tmpVecs[6];
  90421. var yaxis = BoneLookController._tmpVecs[7];
  90422. var _tmpQuat = BoneLookController._tmpQuat;
  90423. target.subtractToRef(bonePos, zaxis);
  90424. zaxis.normalize();
  90425. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  90426. xaxis.normalize();
  90427. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  90428. yaxis.normalize();
  90429. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  90430. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  90431. return;
  90432. }
  90433. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  90434. return;
  90435. }
  90436. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  90437. return;
  90438. }
  90439. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  90440. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  90441. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  90442. }
  90443. if (this.slerpAmount < 1) {
  90444. if (!this._slerping) {
  90445. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  90446. }
  90447. if (this._transformYawPitch) {
  90448. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  90449. }
  90450. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  90451. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  90452. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  90453. this._slerping = true;
  90454. }
  90455. else {
  90456. if (this._transformYawPitch) {
  90457. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  90458. }
  90459. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  90460. this._slerping = false;
  90461. }
  90462. };
  90463. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  90464. var angDiff = ang2 - ang1;
  90465. angDiff %= Math.PI * 2;
  90466. if (angDiff > Math.PI) {
  90467. angDiff -= Math.PI * 2;
  90468. }
  90469. else if (angDiff < -Math.PI) {
  90470. angDiff += Math.PI * 2;
  90471. }
  90472. return angDiff;
  90473. };
  90474. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  90475. ang1 %= (2 * Math.PI);
  90476. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  90477. ang2 %= (2 * Math.PI);
  90478. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  90479. var ab = 0;
  90480. if (ang1 < ang2) {
  90481. ab = ang2 - ang1;
  90482. }
  90483. else {
  90484. ab = ang1 - ang2;
  90485. }
  90486. if (ab > Math.PI) {
  90487. ab = Math.PI * 2 - ab;
  90488. }
  90489. return ab;
  90490. };
  90491. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  90492. ang %= (2 * Math.PI);
  90493. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  90494. ang1 %= (2 * Math.PI);
  90495. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  90496. ang2 %= (2 * Math.PI);
  90497. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  90498. if (ang1 < ang2) {
  90499. if (ang > ang1 && ang < ang2) {
  90500. return true;
  90501. }
  90502. }
  90503. else {
  90504. if (ang > ang2 && ang < ang1) {
  90505. return true;
  90506. }
  90507. }
  90508. return false;
  90509. };
  90510. 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()];
  90511. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  90512. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  90513. return BoneLookController;
  90514. }());
  90515. BABYLON.BoneLookController = BoneLookController;
  90516. })(BABYLON || (BABYLON = {}));
  90517. //# sourceMappingURL=babylon.boneLookController.js.map
  90518. var BABYLON;
  90519. (function (BABYLON) {
  90520. /**
  90521. * Class used to handle skinning animations
  90522. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  90523. */
  90524. var Skeleton = /** @class */ (function () {
  90525. /**
  90526. * Creates a new skeleton
  90527. * @param name defines the skeleton name
  90528. * @param id defines the skeleton Id
  90529. * @param scene defines the hosting scene
  90530. */
  90531. function Skeleton(
  90532. /** defines the skeleton name */
  90533. name,
  90534. /** defines the skeleton Id */
  90535. id, scene) {
  90536. this.name = name;
  90537. this.id = id;
  90538. /**
  90539. * Gets the list of child bones
  90540. */
  90541. this.bones = new Array();
  90542. /**
  90543. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  90544. */
  90545. this.needInitialSkinMatrix = false;
  90546. this._isDirty = true;
  90547. this._meshesWithPoseMatrix = new Array();
  90548. this._identity = BABYLON.Matrix.Identity();
  90549. this._ranges = {};
  90550. this._lastAbsoluteTransformsUpdateId = -1;
  90551. /**
  90552. * Specifies if the skeleton should be serialized
  90553. */
  90554. this.doNotSerialize = false;
  90555. this._animationPropertiesOverride = null;
  90556. // Events
  90557. /**
  90558. * An observable triggered before computing the skeleton's matrices
  90559. */
  90560. this.onBeforeComputeObservable = new BABYLON.Observable();
  90561. this.bones = [];
  90562. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90563. scene.skeletons.push(this);
  90564. //make sure it will recalculate the matrix next time prepare is called.
  90565. this._isDirty = true;
  90566. }
  90567. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  90568. /**
  90569. * Gets or sets the animation properties override
  90570. */
  90571. get: function () {
  90572. if (!this._animationPropertiesOverride) {
  90573. return this._scene.animationPropertiesOverride;
  90574. }
  90575. return this._animationPropertiesOverride;
  90576. },
  90577. set: function (value) {
  90578. this._animationPropertiesOverride = value;
  90579. },
  90580. enumerable: true,
  90581. configurable: true
  90582. });
  90583. // Members
  90584. /**
  90585. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  90586. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  90587. * @returns a Float32Array containing matrices data
  90588. */
  90589. Skeleton.prototype.getTransformMatrices = function (mesh) {
  90590. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  90591. return mesh._bonesTransformMatrices;
  90592. }
  90593. if (!this._transformMatrices) {
  90594. this.prepare();
  90595. }
  90596. return this._transformMatrices;
  90597. };
  90598. /**
  90599. * Gets the current hosting scene
  90600. * @returns a scene object
  90601. */
  90602. Skeleton.prototype.getScene = function () {
  90603. return this._scene;
  90604. };
  90605. // Methods
  90606. /**
  90607. * Gets a string representing the current skeleton data
  90608. * @param fullDetails defines a boolean indicating if we want a verbose version
  90609. * @returns a string representing the current skeleton data
  90610. */
  90611. Skeleton.prototype.toString = function (fullDetails) {
  90612. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  90613. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  90614. if (fullDetails) {
  90615. ret += ", Ranges: {";
  90616. var first = true;
  90617. for (var name_1 in this._ranges) {
  90618. if (first) {
  90619. ret += ", ";
  90620. first = false;
  90621. }
  90622. ret += name_1;
  90623. }
  90624. ret += "}";
  90625. }
  90626. return ret;
  90627. };
  90628. /**
  90629. * Get bone's index searching by name
  90630. * @param name defines bone's name to search for
  90631. * @return the indice of the bone. Returns -1 if not found
  90632. */
  90633. Skeleton.prototype.getBoneIndexByName = function (name) {
  90634. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  90635. if (this.bones[boneIndex].name === name) {
  90636. return boneIndex;
  90637. }
  90638. }
  90639. return -1;
  90640. };
  90641. /**
  90642. * Creater a new animation range
  90643. * @param name defines the name of the range
  90644. * @param from defines the start key
  90645. * @param to defines the end key
  90646. */
  90647. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  90648. // check name not already in use
  90649. if (!this._ranges[name]) {
  90650. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  90651. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  90652. if (this.bones[i].animations[0]) {
  90653. this.bones[i].animations[0].createRange(name, from, to);
  90654. }
  90655. }
  90656. }
  90657. };
  90658. /**
  90659. * Delete a specific animation range
  90660. * @param name defines the name of the range
  90661. * @param deleteFrames defines if frames must be removed as well
  90662. */
  90663. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  90664. if (deleteFrames === void 0) { deleteFrames = true; }
  90665. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  90666. if (this.bones[i].animations[0]) {
  90667. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  90668. }
  90669. }
  90670. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  90671. };
  90672. /**
  90673. * Gets a specific animation range
  90674. * @param name defines the name of the range to look for
  90675. * @returns the requested animation range or null if not found
  90676. */
  90677. Skeleton.prototype.getAnimationRange = function (name) {
  90678. return this._ranges[name];
  90679. };
  90680. /**
  90681. * Gets the list of all animation ranges defined on this skeleton
  90682. * @returns an array
  90683. */
  90684. Skeleton.prototype.getAnimationRanges = function () {
  90685. var animationRanges = [];
  90686. var name;
  90687. var i = 0;
  90688. for (name in this._ranges) {
  90689. animationRanges[i] = this._ranges[name];
  90690. i++;
  90691. }
  90692. return animationRanges;
  90693. };
  90694. /**
  90695. * Copy animation range from a source skeleton.
  90696. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  90697. * @param source defines the source skeleton
  90698. * @param name defines the name of the range to copy
  90699. * @param rescaleAsRequired defines if rescaling must be applied if required
  90700. * @returns true if operation was successful
  90701. */
  90702. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  90703. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  90704. if (this._ranges[name] || !source.getAnimationRange(name)) {
  90705. return false;
  90706. }
  90707. var ret = true;
  90708. var frameOffset = this._getHighestAnimationFrame() + 1;
  90709. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  90710. var boneDict = {};
  90711. var sourceBones = source.bones;
  90712. var nBones;
  90713. var i;
  90714. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  90715. boneDict[sourceBones[i].name] = sourceBones[i];
  90716. }
  90717. if (this.bones.length !== sourceBones.length) {
  90718. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  90719. ret = false;
  90720. }
  90721. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  90722. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  90723. var boneName = this.bones[i].name;
  90724. var sourceBone = boneDict[boneName];
  90725. if (sourceBone) {
  90726. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  90727. }
  90728. else {
  90729. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  90730. ret = false;
  90731. }
  90732. }
  90733. // do not call createAnimationRange(), since it also is done to bones, which was already done
  90734. var range = source.getAnimationRange(name);
  90735. if (range) {
  90736. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  90737. }
  90738. return ret;
  90739. };
  90740. /**
  90741. * Forces the skeleton to go to rest pose
  90742. */
  90743. Skeleton.prototype.returnToRest = function () {
  90744. for (var index = 0; index < this.bones.length; index++) {
  90745. this.bones[index].returnToRest();
  90746. }
  90747. };
  90748. Skeleton.prototype._getHighestAnimationFrame = function () {
  90749. var ret = 0;
  90750. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  90751. if (this.bones[i].animations[0]) {
  90752. var highest = this.bones[i].animations[0].getHighestFrame();
  90753. if (ret < highest) {
  90754. ret = highest;
  90755. }
  90756. }
  90757. }
  90758. return ret;
  90759. };
  90760. /**
  90761. * Begin a specific animation range
  90762. * @param name defines the name of the range to start
  90763. * @param loop defines if looping must be turned on (false by default)
  90764. * @param speedRatio defines the speed ratio to apply (1 by default)
  90765. * @param onAnimationEnd defines a callback which will be called when animation will end
  90766. * @returns a new animatable
  90767. */
  90768. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  90769. var range = this.getAnimationRange(name);
  90770. if (!range) {
  90771. return null;
  90772. }
  90773. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  90774. };
  90775. /** @hidden */
  90776. Skeleton.prototype._markAsDirty = function () {
  90777. this._isDirty = true;
  90778. };
  90779. /** @hidden */
  90780. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  90781. this._meshesWithPoseMatrix.push(mesh);
  90782. };
  90783. /** @hidden */
  90784. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  90785. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  90786. if (index > -1) {
  90787. this._meshesWithPoseMatrix.splice(index, 1);
  90788. }
  90789. };
  90790. /** @hidden */
  90791. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  90792. this.onBeforeComputeObservable.notifyObservers(this);
  90793. for (var index = 0; index < this.bones.length; index++) {
  90794. var bone = this.bones[index];
  90795. var parentBone = bone.getParent();
  90796. if (parentBone) {
  90797. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  90798. }
  90799. else {
  90800. if (initialSkinMatrix) {
  90801. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  90802. }
  90803. else {
  90804. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  90805. }
  90806. }
  90807. if (bone._index !== -1) {
  90808. var mappedIndex = bone._index === null ? index : bone._index;
  90809. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  90810. }
  90811. }
  90812. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  90813. };
  90814. /**
  90815. * Build all resources required to render a skeleton
  90816. */
  90817. Skeleton.prototype.prepare = function () {
  90818. if (!this._isDirty) {
  90819. return;
  90820. }
  90821. if (this.needInitialSkinMatrix) {
  90822. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  90823. var mesh = this._meshesWithPoseMatrix[index];
  90824. var poseMatrix = mesh.getPoseMatrix();
  90825. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  90826. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  90827. }
  90828. if (this._synchronizedWithMesh !== mesh) {
  90829. this._synchronizedWithMesh = mesh;
  90830. // Prepare bones
  90831. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  90832. var bone = this.bones[boneIndex];
  90833. if (!bone.getParent()) {
  90834. var matrix = bone.getBaseMatrix();
  90835. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  90836. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  90837. }
  90838. }
  90839. }
  90840. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  90841. }
  90842. }
  90843. else {
  90844. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  90845. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  90846. }
  90847. this._computeTransformMatrices(this._transformMatrices, null);
  90848. }
  90849. this._isDirty = false;
  90850. this._scene._activeBones.addCount(this.bones.length, false);
  90851. };
  90852. /**
  90853. * Gets the list of animatables currently running for this skeleton
  90854. * @returns an array of animatables
  90855. */
  90856. Skeleton.prototype.getAnimatables = function () {
  90857. if (!this._animatables || this._animatables.length !== this.bones.length) {
  90858. this._animatables = [];
  90859. for (var index = 0; index < this.bones.length; index++) {
  90860. this._animatables.push(this.bones[index]);
  90861. }
  90862. }
  90863. return this._animatables;
  90864. };
  90865. /**
  90866. * Clone the current skeleton
  90867. * @param name defines the name of the new skeleton
  90868. * @param id defines the id of the enw skeleton
  90869. * @returns the new skeleton
  90870. */
  90871. Skeleton.prototype.clone = function (name, id) {
  90872. var result = new Skeleton(name, id || name, this._scene);
  90873. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  90874. for (var index = 0; index < this.bones.length; index++) {
  90875. var source = this.bones[index];
  90876. var parentBone = null;
  90877. var parent_1 = source.getParent();
  90878. if (parent_1) {
  90879. var parentIndex = this.bones.indexOf(parent_1);
  90880. parentBone = result.bones[parentIndex];
  90881. }
  90882. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  90883. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  90884. }
  90885. if (this._ranges) {
  90886. result._ranges = {};
  90887. for (var rangeName in this._ranges) {
  90888. var range = this._ranges[rangeName];
  90889. if (range) {
  90890. result._ranges[rangeName] = range.clone();
  90891. }
  90892. }
  90893. }
  90894. this._isDirty = true;
  90895. return result;
  90896. };
  90897. /**
  90898. * Enable animation blending for this skeleton
  90899. * @param blendingSpeed defines the blending speed to apply
  90900. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  90901. */
  90902. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  90903. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  90904. this.bones.forEach(function (bone) {
  90905. bone.animations.forEach(function (animation) {
  90906. animation.enableBlending = true;
  90907. animation.blendingSpeed = blendingSpeed;
  90908. });
  90909. });
  90910. };
  90911. /**
  90912. * Releases all resources associated with the current skeleton
  90913. */
  90914. Skeleton.prototype.dispose = function () {
  90915. this._meshesWithPoseMatrix = [];
  90916. // Animations
  90917. this.getScene().stopAnimation(this);
  90918. // Remove from scene
  90919. this.getScene().removeSkeleton(this);
  90920. };
  90921. /**
  90922. * Serialize the skeleton in a JSON object
  90923. * @returns a JSON object
  90924. */
  90925. Skeleton.prototype.serialize = function () {
  90926. var serializationObject = {};
  90927. serializationObject.name = this.name;
  90928. serializationObject.id = this.id;
  90929. if (this.dimensionsAtRest) {
  90930. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  90931. }
  90932. serializationObject.bones = [];
  90933. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  90934. for (var index = 0; index < this.bones.length; index++) {
  90935. var bone = this.bones[index];
  90936. var parent_2 = bone.getParent();
  90937. var serializedBone = {
  90938. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  90939. name: bone.name,
  90940. matrix: bone.getBaseMatrix().toArray(),
  90941. rest: bone.getRestPose().toArray()
  90942. };
  90943. serializationObject.bones.push(serializedBone);
  90944. if (bone.length) {
  90945. serializedBone.length = bone.length;
  90946. }
  90947. if (bone.metadata) {
  90948. serializedBone.metadata = bone.metadata;
  90949. }
  90950. if (bone.animations && bone.animations.length > 0) {
  90951. serializedBone.animation = bone.animations[0].serialize();
  90952. }
  90953. serializationObject.ranges = [];
  90954. for (var name in this._ranges) {
  90955. var source = this._ranges[name];
  90956. if (!source) {
  90957. continue;
  90958. }
  90959. var range = {};
  90960. range.name = name;
  90961. range.from = source.from;
  90962. range.to = source.to;
  90963. serializationObject.ranges.push(range);
  90964. }
  90965. }
  90966. return serializationObject;
  90967. };
  90968. /**
  90969. * Creates a new skeleton from serialized data
  90970. * @param parsedSkeleton defines the serialized data
  90971. * @param scene defines the hosting scene
  90972. * @returns a new skeleton
  90973. */
  90974. Skeleton.Parse = function (parsedSkeleton, scene) {
  90975. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  90976. if (parsedSkeleton.dimensionsAtRest) {
  90977. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  90978. }
  90979. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  90980. var index;
  90981. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  90982. var parsedBone = parsedSkeleton.bones[index];
  90983. var parentBone = null;
  90984. if (parsedBone.parentBoneIndex > -1) {
  90985. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  90986. }
  90987. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  90988. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  90989. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  90990. bone.id = parsedBone.id;
  90991. }
  90992. if (parsedBone.length) {
  90993. bone.length = parsedBone.length;
  90994. }
  90995. if (parsedBone.metadata) {
  90996. bone.metadata = parsedBone.metadata;
  90997. }
  90998. if (parsedBone.animation) {
  90999. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  91000. }
  91001. }
  91002. // placed after bones, so createAnimationRange can cascade down
  91003. if (parsedSkeleton.ranges) {
  91004. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  91005. var data = parsedSkeleton.ranges[index];
  91006. skeleton.createAnimationRange(data.name, data.from, data.to);
  91007. }
  91008. }
  91009. return skeleton;
  91010. };
  91011. /**
  91012. * Compute all node absolute transforms
  91013. * @param forceUpdate defines if computation must be done even if cache is up to date
  91014. */
  91015. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  91016. if (forceUpdate === void 0) { forceUpdate = false; }
  91017. var renderId = this._scene.getRenderId();
  91018. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  91019. this.bones[0].computeAbsoluteTransforms();
  91020. this._lastAbsoluteTransformsUpdateId = renderId;
  91021. }
  91022. };
  91023. /**
  91024. * Gets the root pose matrix
  91025. * @returns a matrix
  91026. */
  91027. Skeleton.prototype.getPoseMatrix = function () {
  91028. var poseMatrix = null;
  91029. if (this._meshesWithPoseMatrix.length > 0) {
  91030. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  91031. }
  91032. return poseMatrix;
  91033. };
  91034. /**
  91035. * Sorts bones per internal index
  91036. */
  91037. Skeleton.prototype.sortBones = function () {
  91038. var bones = new Array();
  91039. var visited = new Array(this.bones.length);
  91040. for (var index = 0; index < this.bones.length; index++) {
  91041. this._sortBones(index, bones, visited);
  91042. }
  91043. this.bones = bones;
  91044. };
  91045. Skeleton.prototype._sortBones = function (index, bones, visited) {
  91046. if (visited[index]) {
  91047. return;
  91048. }
  91049. visited[index] = true;
  91050. var bone = this.bones[index];
  91051. if (bone._index === undefined) {
  91052. bone._index = index;
  91053. }
  91054. var parentBone = bone.getParent();
  91055. if (parentBone) {
  91056. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  91057. }
  91058. bones.push(bone);
  91059. };
  91060. return Skeleton;
  91061. }());
  91062. BABYLON.Skeleton = Skeleton;
  91063. })(BABYLON || (BABYLON = {}));
  91064. //# sourceMappingURL=babylon.skeleton.js.map
  91065. var BABYLON;
  91066. (function (BABYLON) {
  91067. ;
  91068. /**
  91069. * This groups tools to convert HDR texture to native colors array.
  91070. */
  91071. var HDRTools = /** @class */ (function () {
  91072. function HDRTools() {
  91073. }
  91074. HDRTools.Ldexp = function (mantissa, exponent) {
  91075. if (exponent > 1023) {
  91076. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  91077. }
  91078. if (exponent < -1074) {
  91079. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  91080. }
  91081. return mantissa * Math.pow(2, exponent);
  91082. };
  91083. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  91084. if (exponent > 0) { /*nonzero pixel*/
  91085. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  91086. float32array[index + 0] = red * exponent;
  91087. float32array[index + 1] = green * exponent;
  91088. float32array[index + 2] = blue * exponent;
  91089. }
  91090. else {
  91091. float32array[index + 0] = 0;
  91092. float32array[index + 1] = 0;
  91093. float32array[index + 2] = 0;
  91094. }
  91095. };
  91096. HDRTools.readStringLine = function (uint8array, startIndex) {
  91097. var line = "";
  91098. var character = "";
  91099. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  91100. character = String.fromCharCode(uint8array[i]);
  91101. if (character == "\n") {
  91102. break;
  91103. }
  91104. line += character;
  91105. }
  91106. return line;
  91107. };
  91108. /**
  91109. * Reads header information from an RGBE texture stored in a native array.
  91110. * More information on this format are available here:
  91111. * https://en.wikipedia.org/wiki/RGBE_image_format
  91112. *
  91113. * @param uint8array The binary file stored in native array.
  91114. * @return The header information.
  91115. */
  91116. HDRTools.RGBE_ReadHeader = function (uint8array) {
  91117. var height = 0;
  91118. var width = 0;
  91119. var line = this.readStringLine(uint8array, 0);
  91120. if (line[0] != '#' || line[1] != '?') {
  91121. throw "Bad HDR Format.";
  91122. }
  91123. var endOfHeader = false;
  91124. var findFormat = false;
  91125. var lineIndex = 0;
  91126. do {
  91127. lineIndex += (line.length + 1);
  91128. line = this.readStringLine(uint8array, lineIndex);
  91129. if (line == "FORMAT=32-bit_rle_rgbe") {
  91130. findFormat = true;
  91131. }
  91132. else if (line.length == 0) {
  91133. endOfHeader = true;
  91134. }
  91135. } while (!endOfHeader);
  91136. if (!findFormat) {
  91137. throw "HDR Bad header format, unsupported FORMAT";
  91138. }
  91139. lineIndex += (line.length + 1);
  91140. line = this.readStringLine(uint8array, lineIndex);
  91141. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  91142. var match = sizeRegexp.exec(line);
  91143. // TODO. Support +Y and -X if needed.
  91144. if (!match || match.length < 3) {
  91145. throw "HDR Bad header format, no size";
  91146. }
  91147. width = parseInt(match[2]);
  91148. height = parseInt(match[1]);
  91149. if (width < 8 || width > 0x7fff) {
  91150. throw "HDR Bad header format, unsupported size";
  91151. }
  91152. lineIndex += (line.length + 1);
  91153. return {
  91154. height: height,
  91155. width: width,
  91156. dataPosition: lineIndex
  91157. };
  91158. };
  91159. /**
  91160. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  91161. * This RGBE texture needs to store the information as a panorama.
  91162. *
  91163. * More information on this format are available here:
  91164. * https://en.wikipedia.org/wiki/RGBE_image_format
  91165. *
  91166. * @param buffer The binary file stored in an array buffer.
  91167. * @param size The expected size of the extracted cubemap.
  91168. * @return The Cube Map information.
  91169. */
  91170. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  91171. var uint8array = new Uint8Array(buffer);
  91172. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  91173. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  91174. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  91175. return cubeMapData;
  91176. };
  91177. /**
  91178. * Returns the pixels data extracted from an RGBE texture.
  91179. * This pixels will be stored left to right up to down in the R G B order in one array.
  91180. *
  91181. * More information on this format are available here:
  91182. * https://en.wikipedia.org/wiki/RGBE_image_format
  91183. *
  91184. * @param uint8array The binary file stored in an array buffer.
  91185. * @param hdrInfo The header information of the file.
  91186. * @return The pixels data in RGB right to left up to down order.
  91187. */
  91188. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  91189. // Keep for multi format supports.
  91190. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  91191. };
  91192. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  91193. var num_scanlines = hdrInfo.height;
  91194. var scanline_width = hdrInfo.width;
  91195. var a, b, c, d, count;
  91196. var dataIndex = hdrInfo.dataPosition;
  91197. var index = 0, endIndex = 0, i = 0;
  91198. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  91199. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  91200. // 3 channels of 4 bytes per pixel in float.
  91201. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  91202. var resultArray = new Float32Array(resultBuffer);
  91203. // read in each successive scanline
  91204. while (num_scanlines > 0) {
  91205. a = uint8array[dataIndex++];
  91206. b = uint8array[dataIndex++];
  91207. c = uint8array[dataIndex++];
  91208. d = uint8array[dataIndex++];
  91209. if (a != 2 || b != 2 || (c & 0x80)) {
  91210. // this file is not run length encoded
  91211. throw "HDR Bad header format, not RLE";
  91212. }
  91213. if (((c << 8) | d) != scanline_width) {
  91214. throw "HDR Bad header format, wrong scan line width";
  91215. }
  91216. index = 0;
  91217. // read each of the four channels for the scanline into the buffer
  91218. for (i = 0; i < 4; i++) {
  91219. endIndex = (i + 1) * scanline_width;
  91220. while (index < endIndex) {
  91221. a = uint8array[dataIndex++];
  91222. b = uint8array[dataIndex++];
  91223. if (a > 128) {
  91224. // a run of the same value
  91225. count = a - 128;
  91226. if ((count == 0) || (count > endIndex - index)) {
  91227. throw "HDR Bad Format, bad scanline data (run)";
  91228. }
  91229. while (count-- > 0) {
  91230. scanLineArray[index++] = b;
  91231. }
  91232. }
  91233. else {
  91234. // a non-run
  91235. count = a;
  91236. if ((count == 0) || (count > endIndex - index)) {
  91237. throw "HDR Bad Format, bad scanline data (non-run)";
  91238. }
  91239. scanLineArray[index++] = b;
  91240. if (--count > 0) {
  91241. for (var j = 0; j < count; j++) {
  91242. scanLineArray[index++] = uint8array[dataIndex++];
  91243. }
  91244. }
  91245. }
  91246. }
  91247. }
  91248. // now convert data from buffer into floats
  91249. for (i = 0; i < scanline_width; i++) {
  91250. a = scanLineArray[i];
  91251. b = scanLineArray[i + scanline_width];
  91252. c = scanLineArray[i + 2 * scanline_width];
  91253. d = scanLineArray[i + 3 * scanline_width];
  91254. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  91255. }
  91256. num_scanlines--;
  91257. }
  91258. return resultArray;
  91259. };
  91260. return HDRTools;
  91261. }());
  91262. BABYLON.HDRTools = HDRTools;
  91263. })(BABYLON || (BABYLON = {}));
  91264. //# sourceMappingURL=babylon.hdr.js.map
  91265. var BABYLON;
  91266. (function (BABYLON) {
  91267. /**
  91268. * This represents a texture coming from an HDR input.
  91269. *
  91270. * The only supported format is currently panorama picture stored in RGBE format.
  91271. * Example of such files can be found on HDRLib: http://hdrlib.com/
  91272. */
  91273. var HDRCubeTexture = /** @class */ (function (_super) {
  91274. __extends(HDRCubeTexture, _super);
  91275. /**
  91276. * Instantiates an HDRTexture from the following parameters.
  91277. *
  91278. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  91279. * @param scene The scene the texture will be used in
  91280. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  91281. * @param noMipmap Forces to not generate the mipmap if true
  91282. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  91283. * @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)
  91284. * @param reserved Reserved flag for internal use.
  91285. */
  91286. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  91287. if (noMipmap === void 0) { noMipmap = false; }
  91288. if (generateHarmonics === void 0) { generateHarmonics = true; }
  91289. if (gammaSpace === void 0) { gammaSpace = false; }
  91290. if (reserved === void 0) { reserved = false; }
  91291. if (onLoad === void 0) { onLoad = null; }
  91292. if (onError === void 0) { onError = null; }
  91293. var _this = _super.call(this, scene) || this;
  91294. _this._generateHarmonics = true;
  91295. _this._onLoad = null;
  91296. _this._onError = null;
  91297. /**
  91298. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  91299. */
  91300. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  91301. _this._isBlocking = true;
  91302. _this._rotationY = 0;
  91303. /**
  91304. * Gets or sets the center of the bounding box associated with the cube texture
  91305. * It must define where the camera used to render the texture was set
  91306. */
  91307. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  91308. if (!url) {
  91309. return _this;
  91310. }
  91311. _this.name = url;
  91312. _this.url = url;
  91313. _this.hasAlpha = false;
  91314. _this.isCube = true;
  91315. _this._textureMatrix = BABYLON.Matrix.Identity();
  91316. _this._onLoad = onLoad;
  91317. _this._onError = onError;
  91318. _this.gammaSpace = gammaSpace;
  91319. _this._noMipmap = noMipmap;
  91320. _this._size = size;
  91321. _this._texture = _this._getFromCache(url, _this._noMipmap);
  91322. if (!_this._texture) {
  91323. if (!scene.useDelayedTextureLoading) {
  91324. _this.loadTexture();
  91325. }
  91326. else {
  91327. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  91328. }
  91329. }
  91330. return _this;
  91331. }
  91332. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  91333. /**
  91334. * Gets wether or not the texture is blocking during loading.
  91335. */
  91336. get: function () {
  91337. return this._isBlocking;
  91338. },
  91339. /**
  91340. * Sets wether or not the texture is blocking during loading.
  91341. */
  91342. set: function (value) {
  91343. this._isBlocking = value;
  91344. },
  91345. enumerable: true,
  91346. configurable: true
  91347. });
  91348. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  91349. /**
  91350. * Gets texture matrix rotation angle around Y axis radians.
  91351. */
  91352. get: function () {
  91353. return this._rotationY;
  91354. },
  91355. /**
  91356. * Sets texture matrix rotation angle around Y axis in radians.
  91357. */
  91358. set: function (value) {
  91359. this._rotationY = value;
  91360. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  91361. },
  91362. enumerable: true,
  91363. configurable: true
  91364. });
  91365. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  91366. get: function () {
  91367. return this._boundingBoxSize;
  91368. },
  91369. /**
  91370. * Gets or sets the size of the bounding box associated with the cube texture
  91371. * When defined, the cubemap will switch to local mode
  91372. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  91373. * @example https://www.babylonjs-playground.com/#RNASML
  91374. */
  91375. set: function (value) {
  91376. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  91377. return;
  91378. }
  91379. this._boundingBoxSize = value;
  91380. var scene = this.getScene();
  91381. if (scene) {
  91382. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  91383. }
  91384. },
  91385. enumerable: true,
  91386. configurable: true
  91387. });
  91388. /**
  91389. * Occurs when the file is raw .hdr file.
  91390. */
  91391. HDRCubeTexture.prototype.loadTexture = function () {
  91392. var _this = this;
  91393. var callback = function (buffer) {
  91394. _this.lodGenerationOffset = 0.0;
  91395. _this.lodGenerationScale = 0.8;
  91396. var scene = _this.getScene();
  91397. if (!scene) {
  91398. return null;
  91399. }
  91400. // Extract the raw linear data.
  91401. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  91402. // Generate harmonics if needed.
  91403. if (_this._generateHarmonics) {
  91404. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  91405. _this.sphericalPolynomial = sphericalPolynomial;
  91406. }
  91407. var results = [];
  91408. var byteArray = null;
  91409. // Push each faces.
  91410. for (var j = 0; j < 6; j++) {
  91411. // Create uintarray fallback.
  91412. if (!scene.getEngine().getCaps().textureFloat) {
  91413. // 3 channels of 1 bytes per pixel in bytes.
  91414. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  91415. byteArray = new Uint8Array(byteBuffer);
  91416. }
  91417. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  91418. // If special cases.
  91419. if (_this.gammaSpace || byteArray) {
  91420. for (var i = 0; i < _this._size * _this._size; i++) {
  91421. // Put in gamma space if requested.
  91422. if (_this.gammaSpace) {
  91423. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  91424. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  91425. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  91426. }
  91427. // Convert to int texture for fallback.
  91428. if (byteArray) {
  91429. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  91430. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  91431. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  91432. // May use luminance instead if the result is not accurate.
  91433. var max = Math.max(Math.max(r, g), b);
  91434. if (max > 255) {
  91435. var scale = 255 / max;
  91436. r *= scale;
  91437. g *= scale;
  91438. b *= scale;
  91439. }
  91440. byteArray[(i * 3) + 0] = r;
  91441. byteArray[(i * 3) + 1] = g;
  91442. byteArray[(i * 3) + 2] = b;
  91443. }
  91444. }
  91445. }
  91446. if (byteArray) {
  91447. results.push(byteArray);
  91448. }
  91449. else {
  91450. results.push(dataFace);
  91451. }
  91452. }
  91453. return results;
  91454. };
  91455. var scene = this.getScene();
  91456. if (scene) {
  91457. 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);
  91458. }
  91459. };
  91460. HDRCubeTexture.prototype.clone = function () {
  91461. var scene = this.getScene();
  91462. if (!scene) {
  91463. return this;
  91464. }
  91465. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  91466. // Base texture
  91467. newTexture.level = this.level;
  91468. newTexture.wrapU = this.wrapU;
  91469. newTexture.wrapV = this.wrapV;
  91470. newTexture.coordinatesIndex = this.coordinatesIndex;
  91471. newTexture.coordinatesMode = this.coordinatesMode;
  91472. return newTexture;
  91473. };
  91474. // Methods
  91475. HDRCubeTexture.prototype.delayLoad = function () {
  91476. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  91477. return;
  91478. }
  91479. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  91480. this._texture = this._getFromCache(this.url, this._noMipmap);
  91481. if (!this._texture) {
  91482. this.loadTexture();
  91483. }
  91484. };
  91485. /**
  91486. * Get the texture reflection matrix used to rotate/transform the reflection.
  91487. * @returns the reflection matrix
  91488. */
  91489. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  91490. return this._textureMatrix;
  91491. };
  91492. /**
  91493. * Set the texture reflection matrix used to rotate/transform the reflection.
  91494. * @param value Define the reflection matrix to set
  91495. */
  91496. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  91497. this._textureMatrix = value;
  91498. };
  91499. /**
  91500. * Parses a JSON representation of an HDR Texture in order to create the texture
  91501. * @param parsedTexture Define the JSON representation
  91502. * @param scene Define the scene the texture should be created in
  91503. * @param rootUrl Define the root url in case we need to load relative dependencies
  91504. * @returns the newly created texture after parsing
  91505. */
  91506. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  91507. var texture = null;
  91508. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  91509. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  91510. texture.name = parsedTexture.name;
  91511. texture.hasAlpha = parsedTexture.hasAlpha;
  91512. texture.level = parsedTexture.level;
  91513. texture.coordinatesMode = parsedTexture.coordinatesMode;
  91514. texture.isBlocking = parsedTexture.isBlocking;
  91515. }
  91516. if (texture) {
  91517. if (parsedTexture.boundingBoxPosition) {
  91518. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  91519. }
  91520. if (parsedTexture.boundingBoxSize) {
  91521. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  91522. }
  91523. if (parsedTexture.rotationY) {
  91524. texture.rotationY = parsedTexture.rotationY;
  91525. }
  91526. }
  91527. return texture;
  91528. };
  91529. HDRCubeTexture.prototype.serialize = function () {
  91530. if (!this.name) {
  91531. return null;
  91532. }
  91533. var serializationObject = {};
  91534. serializationObject.name = this.name;
  91535. serializationObject.hasAlpha = this.hasAlpha;
  91536. serializationObject.isCube = true;
  91537. serializationObject.level = this.level;
  91538. serializationObject.size = this._size;
  91539. serializationObject.coordinatesMode = this.coordinatesMode;
  91540. serializationObject.useInGammaSpace = this.gammaSpace;
  91541. serializationObject.generateHarmonics = this._generateHarmonics;
  91542. serializationObject.customType = "BABYLON.HDRCubeTexture";
  91543. serializationObject.noMipmap = this._noMipmap;
  91544. serializationObject.isBlocking = this._isBlocking;
  91545. serializationObject.rotationY = this._rotationY;
  91546. return serializationObject;
  91547. };
  91548. HDRCubeTexture._facesMapping = [
  91549. "right",
  91550. "left",
  91551. "up",
  91552. "down",
  91553. "front",
  91554. "back"
  91555. ];
  91556. return HDRCubeTexture;
  91557. }(BABYLON.BaseTexture));
  91558. BABYLON.HDRCubeTexture = HDRCubeTexture;
  91559. })(BABYLON || (BABYLON = {}));
  91560. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  91561. var BABYLON;
  91562. (function (BABYLON) {
  91563. /**
  91564. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  91565. */
  91566. var PanoramaToCubeMapTools = /** @class */ (function () {
  91567. function PanoramaToCubeMapTools() {
  91568. }
  91569. /**
  91570. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  91571. *
  91572. * @param float32Array The source data.
  91573. * @param inputWidth The width of the input panorama.
  91574. * @param inputhHeight The height of the input panorama.
  91575. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  91576. * @return The cubemap data
  91577. */
  91578. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  91579. if (!float32Array) {
  91580. throw "ConvertPanoramaToCubemap: input cannot be null";
  91581. }
  91582. if (float32Array.length != inputWidth * inputHeight * 3) {
  91583. throw "ConvertPanoramaToCubemap: input size is wrong";
  91584. }
  91585. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  91586. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  91587. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  91588. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  91589. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  91590. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  91591. return {
  91592. front: textureFront,
  91593. back: textureBack,
  91594. left: textureLeft,
  91595. right: textureRight,
  91596. up: textureUp,
  91597. down: textureDown,
  91598. size: size,
  91599. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  91600. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  91601. gammaSpace: false,
  91602. };
  91603. };
  91604. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  91605. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  91606. var textureArray = new Float32Array(buffer);
  91607. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  91608. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  91609. var dy = 1 / texSize;
  91610. var fy = 0;
  91611. for (var y = 0; y < texSize; y++) {
  91612. var xv1 = faceData[0];
  91613. var xv2 = faceData[2];
  91614. for (var x = 0; x < texSize; x++) {
  91615. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  91616. v.normalize();
  91617. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  91618. // 3 channels per pixels
  91619. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  91620. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  91621. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  91622. xv1 = xv1.add(rotDX1);
  91623. xv2 = xv2.add(rotDX2);
  91624. }
  91625. fy += dy;
  91626. }
  91627. return textureArray;
  91628. };
  91629. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  91630. var theta = Math.atan2(vDir.z, vDir.x);
  91631. var phi = Math.acos(vDir.y);
  91632. while (theta < -Math.PI)
  91633. theta += 2 * Math.PI;
  91634. while (theta > Math.PI)
  91635. theta -= 2 * Math.PI;
  91636. var dx = theta / Math.PI;
  91637. var dy = phi / Math.PI;
  91638. // recenter.
  91639. dx = dx * 0.5 + 0.5;
  91640. var px = Math.round(dx * inputWidth);
  91641. if (px < 0)
  91642. px = 0;
  91643. else if (px >= inputWidth)
  91644. px = inputWidth - 1;
  91645. var py = Math.round(dy * inputHeight);
  91646. if (py < 0)
  91647. py = 0;
  91648. else if (py >= inputHeight)
  91649. py = inputHeight - 1;
  91650. var inputY = (inputHeight - py - 1);
  91651. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  91652. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  91653. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  91654. return {
  91655. r: r,
  91656. g: g,
  91657. b: b
  91658. };
  91659. };
  91660. PanoramaToCubeMapTools.FACE_FRONT = [
  91661. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  91662. new BABYLON.Vector3(1.0, -1.0, -1.0),
  91663. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  91664. new BABYLON.Vector3(1.0, 1.0, -1.0)
  91665. ];
  91666. PanoramaToCubeMapTools.FACE_BACK = [
  91667. new BABYLON.Vector3(1.0, -1.0, 1.0),
  91668. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  91669. new BABYLON.Vector3(1.0, 1.0, 1.0),
  91670. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  91671. ];
  91672. PanoramaToCubeMapTools.FACE_RIGHT = [
  91673. new BABYLON.Vector3(1.0, -1.0, -1.0),
  91674. new BABYLON.Vector3(1.0, -1.0, 1.0),
  91675. new BABYLON.Vector3(1.0, 1.0, -1.0),
  91676. new BABYLON.Vector3(1.0, 1.0, 1.0)
  91677. ];
  91678. PanoramaToCubeMapTools.FACE_LEFT = [
  91679. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  91680. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  91681. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  91682. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  91683. ];
  91684. PanoramaToCubeMapTools.FACE_DOWN = [
  91685. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  91686. new BABYLON.Vector3(1.0, 1.0, -1.0),
  91687. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  91688. new BABYLON.Vector3(1.0, 1.0, 1.0)
  91689. ];
  91690. PanoramaToCubeMapTools.FACE_UP = [
  91691. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  91692. new BABYLON.Vector3(1.0, -1.0, 1.0),
  91693. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  91694. new BABYLON.Vector3(1.0, -1.0, -1.0)
  91695. ];
  91696. return PanoramaToCubeMapTools;
  91697. }());
  91698. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  91699. })(BABYLON || (BABYLON = {}));
  91700. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  91701. var BABYLON;
  91702. (function (BABYLON) {
  91703. var IndexedVector2 = /** @class */ (function (_super) {
  91704. __extends(IndexedVector2, _super);
  91705. function IndexedVector2(original, index) {
  91706. var _this = _super.call(this, original.x, original.y) || this;
  91707. _this.index = index;
  91708. return _this;
  91709. }
  91710. return IndexedVector2;
  91711. }(BABYLON.Vector2));
  91712. var PolygonPoints = /** @class */ (function () {
  91713. function PolygonPoints() {
  91714. this.elements = new Array();
  91715. }
  91716. PolygonPoints.prototype.add = function (originalPoints) {
  91717. var _this = this;
  91718. var result = new Array();
  91719. originalPoints.forEach(function (point) {
  91720. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  91721. var newPoint = new IndexedVector2(point, _this.elements.length);
  91722. result.push(newPoint);
  91723. _this.elements.push(newPoint);
  91724. }
  91725. });
  91726. return result;
  91727. };
  91728. PolygonPoints.prototype.computeBounds = function () {
  91729. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  91730. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  91731. this.elements.forEach(function (point) {
  91732. // x
  91733. if (point.x < lmin.x) {
  91734. lmin.x = point.x;
  91735. }
  91736. else if (point.x > lmax.x) {
  91737. lmax.x = point.x;
  91738. }
  91739. // y
  91740. if (point.y < lmin.y) {
  91741. lmin.y = point.y;
  91742. }
  91743. else if (point.y > lmax.y) {
  91744. lmax.y = point.y;
  91745. }
  91746. });
  91747. return {
  91748. min: lmin,
  91749. max: lmax,
  91750. width: lmax.x - lmin.x,
  91751. height: lmax.y - lmin.y
  91752. };
  91753. };
  91754. return PolygonPoints;
  91755. }());
  91756. var Polygon = /** @class */ (function () {
  91757. function Polygon() {
  91758. }
  91759. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  91760. return [
  91761. new BABYLON.Vector2(xmin, ymin),
  91762. new BABYLON.Vector2(xmax, ymin),
  91763. new BABYLON.Vector2(xmax, ymax),
  91764. new BABYLON.Vector2(xmin, ymax)
  91765. ];
  91766. };
  91767. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  91768. if (cx === void 0) { cx = 0; }
  91769. if (cy === void 0) { cy = 0; }
  91770. if (numberOfSides === void 0) { numberOfSides = 32; }
  91771. var result = new Array();
  91772. var angle = 0;
  91773. var increment = (Math.PI * 2) / numberOfSides;
  91774. for (var i = 0; i < numberOfSides; i++) {
  91775. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  91776. angle -= increment;
  91777. }
  91778. return result;
  91779. };
  91780. Polygon.Parse = function (input) {
  91781. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  91782. var i, result = [];
  91783. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  91784. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  91785. }
  91786. return result;
  91787. };
  91788. Polygon.StartingAt = function (x, y) {
  91789. return BABYLON.Path2.StartingAt(x, y);
  91790. };
  91791. return Polygon;
  91792. }());
  91793. BABYLON.Polygon = Polygon;
  91794. var PolygonMeshBuilder = /** @class */ (function () {
  91795. function PolygonMeshBuilder(name, contours, scene) {
  91796. this._points = new PolygonPoints();
  91797. this._outlinepoints = new PolygonPoints();
  91798. this._holes = new Array();
  91799. this._epoints = new Array();
  91800. this._eholes = new Array();
  91801. this._name = name;
  91802. this._scene = scene;
  91803. var points;
  91804. if (contours instanceof BABYLON.Path2) {
  91805. points = contours.getPoints();
  91806. }
  91807. else {
  91808. points = contours;
  91809. }
  91810. this._addToepoint(points);
  91811. this._points.add(points);
  91812. this._outlinepoints.add(points);
  91813. if (typeof earcut === 'undefined') {
  91814. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  91815. }
  91816. }
  91817. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  91818. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  91819. var p = points_1[_i];
  91820. this._epoints.push(p.x, p.y);
  91821. }
  91822. };
  91823. PolygonMeshBuilder.prototype.addHole = function (hole) {
  91824. this._points.add(hole);
  91825. var holepoints = new PolygonPoints();
  91826. holepoints.add(hole);
  91827. this._holes.push(holepoints);
  91828. this._eholes.push(this._epoints.length / 2);
  91829. this._addToepoint(hole);
  91830. return this;
  91831. };
  91832. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  91833. var _this = this;
  91834. if (updatable === void 0) { updatable = false; }
  91835. if (depth === void 0) { depth = 0; }
  91836. var result = new BABYLON.Mesh(this._name, this._scene);
  91837. var normals = new Array();
  91838. var positions = new Array();
  91839. var uvs = new Array();
  91840. var bounds = this._points.computeBounds();
  91841. this._points.elements.forEach(function (p) {
  91842. normals.push(0, 1.0, 0);
  91843. positions.push(p.x, 0, p.y);
  91844. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  91845. });
  91846. var indices = new Array();
  91847. var res = earcut(this._epoints, this._eholes, 2);
  91848. for (var i = 0; i < res.length; i++) {
  91849. indices.push(res[i]);
  91850. }
  91851. if (depth > 0) {
  91852. var positionscount = (positions.length / 3); //get the current pointcount
  91853. this._points.elements.forEach(function (p) {
  91854. normals.push(0, -1.0, 0);
  91855. positions.push(p.x, -depth, p.y);
  91856. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  91857. });
  91858. var totalCount = indices.length;
  91859. for (var i = 0; i < totalCount; i += 3) {
  91860. var i0 = indices[i + 0];
  91861. var i1 = indices[i + 1];
  91862. var i2 = indices[i + 2];
  91863. indices.push(i2 + positionscount);
  91864. indices.push(i1 + positionscount);
  91865. indices.push(i0 + positionscount);
  91866. }
  91867. //Add the sides
  91868. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  91869. this._holes.forEach(function (hole) {
  91870. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  91871. });
  91872. }
  91873. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  91874. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  91875. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  91876. result.setIndices(indices);
  91877. return result;
  91878. };
  91879. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  91880. var StartIndex = positions.length / 3;
  91881. var ulength = 0;
  91882. for (var i = 0; i < points.elements.length; i++) {
  91883. var p = points.elements[i];
  91884. var p1;
  91885. if ((i + 1) > points.elements.length - 1) {
  91886. p1 = points.elements[0];
  91887. }
  91888. else {
  91889. p1 = points.elements[i + 1];
  91890. }
  91891. positions.push(p.x, 0, p.y);
  91892. positions.push(p.x, -depth, p.y);
  91893. positions.push(p1.x, 0, p1.y);
  91894. positions.push(p1.x, -depth, p1.y);
  91895. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  91896. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  91897. var v3 = v2.subtract(v1);
  91898. var v4 = new BABYLON.Vector3(0, 1, 0);
  91899. var vn = BABYLON.Vector3.Cross(v3, v4);
  91900. vn = vn.normalize();
  91901. uvs.push(ulength / bounds.width, 0);
  91902. uvs.push(ulength / bounds.width, 1);
  91903. ulength += v3.length();
  91904. uvs.push((ulength / bounds.width), 0);
  91905. uvs.push((ulength / bounds.width), 1);
  91906. if (!flip) {
  91907. normals.push(-vn.x, -vn.y, -vn.z);
  91908. normals.push(-vn.x, -vn.y, -vn.z);
  91909. normals.push(-vn.x, -vn.y, -vn.z);
  91910. normals.push(-vn.x, -vn.y, -vn.z);
  91911. indices.push(StartIndex);
  91912. indices.push(StartIndex + 1);
  91913. indices.push(StartIndex + 2);
  91914. indices.push(StartIndex + 1);
  91915. indices.push(StartIndex + 3);
  91916. indices.push(StartIndex + 2);
  91917. }
  91918. else {
  91919. normals.push(vn.x, vn.y, vn.z);
  91920. normals.push(vn.x, vn.y, vn.z);
  91921. normals.push(vn.x, vn.y, vn.z);
  91922. normals.push(vn.x, vn.y, vn.z);
  91923. indices.push(StartIndex);
  91924. indices.push(StartIndex + 2);
  91925. indices.push(StartIndex + 1);
  91926. indices.push(StartIndex + 1);
  91927. indices.push(StartIndex + 2);
  91928. indices.push(StartIndex + 3);
  91929. }
  91930. StartIndex += 4;
  91931. }
  91932. ;
  91933. };
  91934. return PolygonMeshBuilder;
  91935. }());
  91936. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  91937. })(BABYLON || (BABYLON = {}));
  91938. //# sourceMappingURL=babylon.polygonMesh.js.map
  91939. var BABYLON;
  91940. (function (BABYLON) {
  91941. /**
  91942. * Unique ID when we import meshes from Babylon to CSG
  91943. */
  91944. var currentCSGMeshId = 0;
  91945. /**
  91946. * Represents a vertex of a polygon. Use your own vertex class instead of this
  91947. * one to provide additional features like texture coordinates and vertex
  91948. * colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  91949. * `flip()`, and `interpolate()` methods that behave analogous to the ones
  91950. * defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  91951. * functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  91952. * is not used anywhere else.
  91953. * Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  91954. */
  91955. var Vertex = /** @class */ (function () {
  91956. /**
  91957. * Initializes the vertex
  91958. * @param pos The position of the vertex
  91959. * @param normal The normal of the vertex
  91960. * @param uv The texture coordinate of the vertex
  91961. */
  91962. function Vertex(
  91963. /**
  91964. * The position of the vertex
  91965. */
  91966. pos,
  91967. /**
  91968. * The normal of the vertex
  91969. */
  91970. normal,
  91971. /**
  91972. * The texture coordinate of the vertex
  91973. */
  91974. uv) {
  91975. this.pos = pos;
  91976. this.normal = normal;
  91977. this.uv = uv;
  91978. }
  91979. /**
  91980. * Make a clone, or deep copy, of the vertex
  91981. * @returns A new Vertex
  91982. */
  91983. Vertex.prototype.clone = function () {
  91984. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  91985. };
  91986. /**
  91987. * Invert all orientation-specific data (e.g. vertex normal). Called when the
  91988. * orientation of a polygon is flipped.
  91989. */
  91990. Vertex.prototype.flip = function () {
  91991. this.normal = this.normal.scale(-1);
  91992. };
  91993. /**
  91994. * Create a new vertex between this vertex and `other` by linearly
  91995. * interpolating all properties using a parameter of `t`. Subclasses should
  91996. * override this to interpolate additional properties.
  91997. * @param other the vertex to interpolate against
  91998. * @param t The factor used to linearly interpolate between the vertices
  91999. */
  92000. Vertex.prototype.interpolate = function (other, t) {
  92001. 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));
  92002. };
  92003. return Vertex;
  92004. }());
  92005. /**
  92006. * Represents a plane in 3D space.
  92007. */
  92008. var Plane = /** @class */ (function () {
  92009. /**
  92010. * Initializes the plane
  92011. * @param normal The normal for the plane
  92012. * @param w
  92013. */
  92014. function Plane(normal, w) {
  92015. this.normal = normal;
  92016. this.w = w;
  92017. }
  92018. /**
  92019. * Construct a plane from three points
  92020. * @param a Point a
  92021. * @param b Point b
  92022. * @param c Point c
  92023. */
  92024. Plane.FromPoints = function (a, b, c) {
  92025. var v0 = c.subtract(a);
  92026. var v1 = b.subtract(a);
  92027. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  92028. return null;
  92029. }
  92030. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  92031. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  92032. };
  92033. /**
  92034. * Clone, or make a deep copy of the plane
  92035. * @returns a new Plane
  92036. */
  92037. Plane.prototype.clone = function () {
  92038. return new Plane(this.normal.clone(), this.w);
  92039. };
  92040. /**
  92041. * Flip the face of the plane
  92042. */
  92043. Plane.prototype.flip = function () {
  92044. this.normal.scaleInPlace(-1);
  92045. this.w = -this.w;
  92046. };
  92047. /**
  92048. * Split `polygon` by this plane if needed, then put the polygon or polygon
  92049. * fragments in the appropriate lists. Coplanar polygons go into either
  92050. `* coplanarFront` or `coplanarBack` depending on their orientation with
  92051. * respect to this plane. Polygons in front or in back of this plane go into
  92052. * either `front` or `back`
  92053. * @param polygon The polygon to be split
  92054. * @param coplanarFront Will contain polygons coplanar with the plane that are oriented to the front of the plane
  92055. * @param coplanarBack Will contain polygons coplanar with the plane that are oriented to the back of the plane
  92056. * @param front Will contain the polygons in front of the plane
  92057. * @param back Will contain the polygons begind the plane
  92058. */
  92059. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  92060. var COPLANAR = 0;
  92061. var FRONT = 1;
  92062. var BACK = 2;
  92063. var SPANNING = 3;
  92064. // Classify each point as well as the entire polygon into one of the above
  92065. // four classes.
  92066. var polygonType = 0;
  92067. var types = [];
  92068. var i;
  92069. var t;
  92070. for (i = 0; i < polygon.vertices.length; i++) {
  92071. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  92072. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  92073. polygonType |= type;
  92074. types.push(type);
  92075. }
  92076. // Put the polygon in the correct list, splitting it when necessary
  92077. switch (polygonType) {
  92078. case COPLANAR:
  92079. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  92080. break;
  92081. case FRONT:
  92082. front.push(polygon);
  92083. break;
  92084. case BACK:
  92085. back.push(polygon);
  92086. break;
  92087. case SPANNING:
  92088. var f = [], b = [];
  92089. for (i = 0; i < polygon.vertices.length; i++) {
  92090. var j = (i + 1) % polygon.vertices.length;
  92091. var ti = types[i], tj = types[j];
  92092. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  92093. if (ti !== BACK)
  92094. f.push(vi);
  92095. if (ti !== FRONT)
  92096. b.push(ti !== BACK ? vi.clone() : vi);
  92097. if ((ti | tj) === SPANNING) {
  92098. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  92099. var v = vi.interpolate(vj, t);
  92100. f.push(v);
  92101. b.push(v.clone());
  92102. }
  92103. }
  92104. var poly;
  92105. if (f.length >= 3) {
  92106. poly = new Polygon(f, polygon.shared);
  92107. if (poly.plane)
  92108. front.push(poly);
  92109. }
  92110. if (b.length >= 3) {
  92111. poly = new Polygon(b, polygon.shared);
  92112. if (poly.plane)
  92113. back.push(poly);
  92114. }
  92115. break;
  92116. }
  92117. };
  92118. /**
  92119. * `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  92120. * point is on the plane
  92121. */
  92122. Plane.EPSILON = 1e-5;
  92123. return Plane;
  92124. }());
  92125. /**
  92126. * Represents a convex polygon. The vertices used to initialize a polygon must
  92127. * be coplanar and form a convex loop.
  92128. *
  92129. * Each convex polygon has a `shared` property, which is shared between all
  92130. * polygons that are clones of each other or were split from the same polygon.
  92131. * This can be used to define per-polygon properties (such as surface color)
  92132. */
  92133. var Polygon = /** @class */ (function () {
  92134. /**
  92135. * Initializes the polygon
  92136. * @param vertices The vertices of the polygon
  92137. * @param shared The properties shared across all polygons
  92138. */
  92139. function Polygon(vertices, shared) {
  92140. this.vertices = vertices;
  92141. this.shared = shared;
  92142. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  92143. }
  92144. /**
  92145. * Clones, or makes a deep copy, or the polygon
  92146. */
  92147. Polygon.prototype.clone = function () {
  92148. var vertices = this.vertices.map(function (v) { return v.clone(); });
  92149. return new Polygon(vertices, this.shared);
  92150. };
  92151. /**
  92152. * Flips the faces of the polygon
  92153. */
  92154. Polygon.prototype.flip = function () {
  92155. this.vertices.reverse().map(function (v) { v.flip(); });
  92156. this.plane.flip();
  92157. };
  92158. return Polygon;
  92159. }());
  92160. /**
  92161. * Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  92162. * by picking a polygon to split along. That polygon (and all other coplanar
  92163. * polygons) are added directly to that node and the other polygons are added to
  92164. * the front and/or back subtrees. This is not a leafy BSP tree since there is
  92165. * no distinction between internal and leaf nodes
  92166. */
  92167. var Node = /** @class */ (function () {
  92168. /**
  92169. * Initializes the node
  92170. * @param polygons A collection of polygons held in the node
  92171. */
  92172. function Node(polygons) {
  92173. this.plane = null;
  92174. this.front = null;
  92175. this.back = null;
  92176. this.polygons = new Array();
  92177. if (polygons) {
  92178. this.build(polygons);
  92179. }
  92180. }
  92181. /**
  92182. * Clones, or makes a deep copy, of the node
  92183. * @returns The cloned node
  92184. */
  92185. Node.prototype.clone = function () {
  92186. var node = new Node();
  92187. node.plane = this.plane && this.plane.clone();
  92188. node.front = this.front && this.front.clone();
  92189. node.back = this.back && this.back.clone();
  92190. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  92191. return node;
  92192. };
  92193. /**
  92194. * Convert solid space to empty space and empty space to solid space
  92195. */
  92196. Node.prototype.invert = function () {
  92197. for (var i = 0; i < this.polygons.length; i++) {
  92198. this.polygons[i].flip();
  92199. }
  92200. if (this.plane) {
  92201. this.plane.flip();
  92202. }
  92203. if (this.front) {
  92204. this.front.invert();
  92205. }
  92206. if (this.back) {
  92207. this.back.invert();
  92208. }
  92209. var temp = this.front;
  92210. this.front = this.back;
  92211. this.back = temp;
  92212. };
  92213. /**
  92214. * Recursively remove all polygons in `polygons` that are inside this BSP
  92215. * tree.
  92216. * @param polygons Polygons to remove from the BSP
  92217. * @returns Polygons clipped from the BSP
  92218. */
  92219. Node.prototype.clipPolygons = function (polygons) {
  92220. if (!this.plane)
  92221. return polygons.slice();
  92222. var front = new Array(), back = new Array();
  92223. for (var i = 0; i < polygons.length; i++) {
  92224. this.plane.splitPolygon(polygons[i], front, back, front, back);
  92225. }
  92226. if (this.front) {
  92227. front = this.front.clipPolygons(front);
  92228. }
  92229. if (this.back) {
  92230. back = this.back.clipPolygons(back);
  92231. }
  92232. else {
  92233. back = [];
  92234. }
  92235. return front.concat(back);
  92236. };
  92237. /**
  92238. * Remove all polygons in this BSP tree that are inside the other BSP tree
  92239. * `bsp`.
  92240. * @param bsp BSP containing polygons to remove from this BSP
  92241. */
  92242. Node.prototype.clipTo = function (bsp) {
  92243. this.polygons = bsp.clipPolygons(this.polygons);
  92244. if (this.front)
  92245. this.front.clipTo(bsp);
  92246. if (this.back)
  92247. this.back.clipTo(bsp);
  92248. };
  92249. /**
  92250. * Return a list of all polygons in this BSP tree
  92251. * @returns List of all polygons in this BSP tree
  92252. */
  92253. Node.prototype.allPolygons = function () {
  92254. var polygons = this.polygons.slice();
  92255. if (this.front)
  92256. polygons = polygons.concat(this.front.allPolygons());
  92257. if (this.back)
  92258. polygons = polygons.concat(this.back.allPolygons());
  92259. return polygons;
  92260. };
  92261. /**
  92262. * Build a BSP tree out of `polygons`. When called on an existing tree, the
  92263. * new polygons are filtered down to the bottom of the tree and become new
  92264. * nodes there. Each set of polygons is partitioned using the first polygon
  92265. * (no heuristic is used to pick a good split)
  92266. * @param polygons Polygons used to construct the BSP tree
  92267. */
  92268. Node.prototype.build = function (polygons) {
  92269. if (!polygons.length)
  92270. return;
  92271. if (!this.plane)
  92272. this.plane = polygons[0].plane.clone();
  92273. var front = new Array(), back = new Array();
  92274. for (var i = 0; i < polygons.length; i++) {
  92275. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  92276. }
  92277. if (front.length) {
  92278. if (!this.front)
  92279. this.front = new Node();
  92280. this.front.build(front);
  92281. }
  92282. if (back.length) {
  92283. if (!this.back)
  92284. this.back = new Node();
  92285. this.back.build(back);
  92286. }
  92287. };
  92288. return Node;
  92289. }());
  92290. /**
  92291. * Class for building Constructive Solid Geometry
  92292. */
  92293. var CSG = /** @class */ (function () {
  92294. function CSG() {
  92295. this.polygons = new Array();
  92296. }
  92297. /**
  92298. * Convert the BABYLON.Mesh to BABYLON.CSG
  92299. * @param mesh The BABYLON.Mesh to convert to BABYLON.CSG
  92300. * @returns A new BABYLON.CSG from the BABYLON.Mesh
  92301. */
  92302. CSG.FromMesh = function (mesh) {
  92303. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  92304. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  92305. if (mesh instanceof BABYLON.Mesh) {
  92306. mesh.computeWorldMatrix(true);
  92307. matrix = mesh.getWorldMatrix();
  92308. meshPosition = mesh.position.clone();
  92309. meshRotation = mesh.rotation.clone();
  92310. if (mesh.rotationQuaternion) {
  92311. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  92312. }
  92313. meshScaling = mesh.scaling.clone();
  92314. }
  92315. else {
  92316. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  92317. }
  92318. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  92319. var subMeshes = mesh.subMeshes;
  92320. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  92321. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  92322. vertices = [];
  92323. for (var j = 0; j < 3; j++) {
  92324. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  92325. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  92326. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  92327. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  92328. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  92329. vertex = new Vertex(position, normal, uv);
  92330. vertices.push(vertex);
  92331. }
  92332. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  92333. // To handle the case of degenerated triangle
  92334. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  92335. if (polygon.plane)
  92336. polygons.push(polygon);
  92337. }
  92338. }
  92339. var csg = CSG.FromPolygons(polygons);
  92340. csg.matrix = matrix;
  92341. csg.position = meshPosition;
  92342. csg.rotation = meshRotation;
  92343. csg.scaling = meshScaling;
  92344. csg.rotationQuaternion = meshRotationQuaternion;
  92345. currentCSGMeshId++;
  92346. return csg;
  92347. };
  92348. /**
  92349. * Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  92350. * @param polygons Polygons used to construct a BABYLON.CSG solid
  92351. */
  92352. CSG.FromPolygons = function (polygons) {
  92353. var csg = new CSG();
  92354. csg.polygons = polygons;
  92355. return csg;
  92356. };
  92357. /**
  92358. * Clones, or makes a deep copy, of the BABYLON.CSG
  92359. * @returns A new BABYLON.CSG
  92360. */
  92361. CSG.prototype.clone = function () {
  92362. var csg = new CSG();
  92363. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  92364. csg.copyTransformAttributes(this);
  92365. return csg;
  92366. };
  92367. /**
  92368. * Unions this CSG with another CSG
  92369. * @param csg The CSG to union against this CSG
  92370. * @returns The unioned CSG
  92371. */
  92372. CSG.prototype.union = function (csg) {
  92373. var a = new Node(this.clone().polygons);
  92374. var b = new Node(csg.clone().polygons);
  92375. a.clipTo(b);
  92376. b.clipTo(a);
  92377. b.invert();
  92378. b.clipTo(a);
  92379. b.invert();
  92380. a.build(b.allPolygons());
  92381. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  92382. };
  92383. /**
  92384. * Unions this CSG with another CSG in place
  92385. * @param csg The CSG to union against this CSG
  92386. */
  92387. CSG.prototype.unionInPlace = function (csg) {
  92388. var a = new Node(this.polygons);
  92389. var b = new Node(csg.polygons);
  92390. a.clipTo(b);
  92391. b.clipTo(a);
  92392. b.invert();
  92393. b.clipTo(a);
  92394. b.invert();
  92395. a.build(b.allPolygons());
  92396. this.polygons = a.allPolygons();
  92397. };
  92398. /**
  92399. * Subtracts this CSG with another CSG
  92400. * @param csg The CSG to subtract against this CSG
  92401. * @returns A new BABYLON.CSG
  92402. */
  92403. CSG.prototype.subtract = function (csg) {
  92404. var a = new Node(this.clone().polygons);
  92405. var b = new Node(csg.clone().polygons);
  92406. a.invert();
  92407. a.clipTo(b);
  92408. b.clipTo(a);
  92409. b.invert();
  92410. b.clipTo(a);
  92411. b.invert();
  92412. a.build(b.allPolygons());
  92413. a.invert();
  92414. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  92415. };
  92416. /**
  92417. * Subtracts this CSG with another CSG in place
  92418. * @param csg The CSG to subtact against this CSG
  92419. */
  92420. CSG.prototype.subtractInPlace = function (csg) {
  92421. var a = new Node(this.polygons);
  92422. var b = new Node(csg.polygons);
  92423. a.invert();
  92424. a.clipTo(b);
  92425. b.clipTo(a);
  92426. b.invert();
  92427. b.clipTo(a);
  92428. b.invert();
  92429. a.build(b.allPolygons());
  92430. a.invert();
  92431. this.polygons = a.allPolygons();
  92432. };
  92433. /**
  92434. * Intersect this CSG with another CSG
  92435. * @param csg The CSG to intersect against this CSG
  92436. * @returns A new BABYLON.CSG
  92437. */
  92438. CSG.prototype.intersect = function (csg) {
  92439. var a = new Node(this.clone().polygons);
  92440. var b = new Node(csg.clone().polygons);
  92441. a.invert();
  92442. b.clipTo(a);
  92443. b.invert();
  92444. a.clipTo(b);
  92445. b.clipTo(a);
  92446. a.build(b.allPolygons());
  92447. a.invert();
  92448. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  92449. };
  92450. /**
  92451. * Intersects this CSG with another CSG in place
  92452. * @param csg The CSG to intersect against this CSG
  92453. */
  92454. CSG.prototype.intersectInPlace = function (csg) {
  92455. var a = new Node(this.polygons);
  92456. var b = new Node(csg.polygons);
  92457. a.invert();
  92458. b.clipTo(a);
  92459. b.invert();
  92460. a.clipTo(b);
  92461. b.clipTo(a);
  92462. a.build(b.allPolygons());
  92463. a.invert();
  92464. this.polygons = a.allPolygons();
  92465. };
  92466. /**
  92467. * Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  92468. * not modified.
  92469. * @returns A new BABYLON.CSG solid with solid and empty space switched
  92470. */
  92471. CSG.prototype.inverse = function () {
  92472. var csg = this.clone();
  92473. csg.inverseInPlace();
  92474. return csg;
  92475. };
  92476. /**
  92477. * Inverses the BABYLON.CSG in place
  92478. */
  92479. CSG.prototype.inverseInPlace = function () {
  92480. this.polygons.map(function (p) { p.flip(); });
  92481. };
  92482. /**
  92483. * This is used to keep meshes transformations so they can be restored
  92484. * when we build back a Babylon Mesh
  92485. * NB : All CSG operations are performed in world coordinates
  92486. * @param csg The BABYLON.CSG to copy the transform attributes from
  92487. * @returns This BABYLON.CSG
  92488. */
  92489. CSG.prototype.copyTransformAttributes = function (csg) {
  92490. this.matrix = csg.matrix;
  92491. this.position = csg.position;
  92492. this.rotation = csg.rotation;
  92493. this.scaling = csg.scaling;
  92494. this.rotationQuaternion = csg.rotationQuaternion;
  92495. return this;
  92496. };
  92497. /**
  92498. * Build Raw mesh from CSG
  92499. * Coordinates here are in world space
  92500. * @param name The name of the mesh geometry
  92501. * @param scene The BABYLON.Scene
  92502. * @param keepSubMeshes Specifies if the submeshes should be kept
  92503. * @returns A new BABYLON.Mesh
  92504. */
  92505. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  92506. var matrix = this.matrix.clone();
  92507. matrix.invert();
  92508. 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;
  92509. if (keepSubMeshes) {
  92510. // Sort Polygons, since subMeshes are indices range
  92511. polygons.sort(function (a, b) {
  92512. if (a.shared.meshId === b.shared.meshId) {
  92513. return a.shared.subMeshId - b.shared.subMeshId;
  92514. }
  92515. else {
  92516. return a.shared.meshId - b.shared.meshId;
  92517. }
  92518. });
  92519. }
  92520. for (var i = 0, il = polygons.length; i < il; i++) {
  92521. polygon = polygons[i];
  92522. // Building SubMeshes
  92523. if (!subMesh_dict[polygon.shared.meshId]) {
  92524. subMesh_dict[polygon.shared.meshId] = {};
  92525. }
  92526. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  92527. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  92528. indexStart: +Infinity,
  92529. indexEnd: -Infinity,
  92530. materialIndex: polygon.shared.materialIndex
  92531. };
  92532. }
  92533. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  92534. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  92535. polygonIndices[0] = 0;
  92536. polygonIndices[1] = j - 1;
  92537. polygonIndices[2] = j;
  92538. for (var k = 0; k < 3; k++) {
  92539. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  92540. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  92541. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  92542. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  92543. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  92544. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  92545. // Check if 2 points can be merged
  92546. if (!(typeof vertex_idx !== 'undefined' &&
  92547. normals[vertex_idx * 3] === localNormal.x &&
  92548. normals[vertex_idx * 3 + 1] === localNormal.y &&
  92549. normals[vertex_idx * 3 + 2] === localNormal.z &&
  92550. uvs[vertex_idx * 2] === uv.x &&
  92551. uvs[vertex_idx * 2 + 1] === uv.y)) {
  92552. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  92553. uvs.push(uv.x, uv.y);
  92554. normals.push(normal.x, normal.y, normal.z);
  92555. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  92556. }
  92557. indices.push(vertex_idx);
  92558. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  92559. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  92560. currentIndex++;
  92561. }
  92562. }
  92563. }
  92564. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  92565. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  92566. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  92567. mesh.setIndices(indices, null);
  92568. if (keepSubMeshes) {
  92569. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  92570. var materialIndexOffset = 0, materialMaxIndex;
  92571. mesh.subMeshes = new Array();
  92572. for (var m in subMesh_dict) {
  92573. materialMaxIndex = -1;
  92574. for (var sm in subMesh_dict[m]) {
  92575. subMesh_obj = subMesh_dict[m][sm];
  92576. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  92577. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  92578. }
  92579. materialIndexOffset += ++materialMaxIndex;
  92580. }
  92581. }
  92582. return mesh;
  92583. };
  92584. /**
  92585. * Build Mesh from CSG taking material and transforms into account
  92586. * @param name The name of the BABYLON.Mesh
  92587. * @param material The material of the BABYLON.Mesh
  92588. * @param scene The BABYLON.Scene
  92589. * @param keepSubMeshes Specifies if submeshes should be kept
  92590. * @returns The new BABYLON.Mesh
  92591. */
  92592. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  92593. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  92594. mesh.material = material;
  92595. mesh.position.copyFrom(this.position);
  92596. mesh.rotation.copyFrom(this.rotation);
  92597. if (this.rotationQuaternion) {
  92598. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  92599. }
  92600. mesh.scaling.copyFrom(this.scaling);
  92601. mesh.computeWorldMatrix(true);
  92602. return mesh;
  92603. };
  92604. return CSG;
  92605. }());
  92606. BABYLON.CSG = CSG;
  92607. })(BABYLON || (BABYLON = {}));
  92608. //# sourceMappingURL=babylon.csg.js.map
  92609. var BABYLON;
  92610. (function (BABYLON) {
  92611. /**
  92612. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  92613. * It controls one of the indiviual texture used in the effect.
  92614. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  92615. */
  92616. var LensFlare = /** @class */ (function () {
  92617. /**
  92618. * Instantiates a new Lens Flare.
  92619. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  92620. * It controls one of the indiviual texture used in the effect.
  92621. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  92622. * @param size Define the size of the lens flare in the system (a floating value between 0 and 1)
  92623. * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  92624. * @param color Define the lens color
  92625. * @param imgUrl Define the lens texture url
  92626. * @param system Define the `lensFlareSystem` this flare is part of
  92627. */
  92628. function LensFlare(
  92629. /**
  92630. * Define the size of the lens flare in the system (a floating value between 0 and 1)
  92631. */
  92632. size,
  92633. /**
  92634. * Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  92635. */
  92636. position, color, imgUrl, system) {
  92637. this.size = size;
  92638. this.position = position;
  92639. /**
  92640. * Define the alpha mode to render this particular lens.
  92641. */
  92642. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  92643. this.color = color || new BABYLON.Color3(1, 1, 1);
  92644. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  92645. this._system = system;
  92646. system.lensFlares.push(this);
  92647. }
  92648. /**
  92649. * Creates a new Lens Flare.
  92650. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  92651. * It controls one of the indiviual texture used in the effect.
  92652. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  92653. * @param size Define the size of the lens flare (a floating value between 0 and 1)
  92654. * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  92655. * @param color Define the lens color
  92656. * @param imgUrl Define the lens texture url
  92657. * @param system Define the `lensFlareSystem` this flare is part of
  92658. * @returns The newly created Lens Flare
  92659. */
  92660. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  92661. return new LensFlare(size, position, color, imgUrl, system);
  92662. };
  92663. /**
  92664. * Dispose and release the lens flare with its associated resources.
  92665. */
  92666. LensFlare.prototype.dispose = function () {
  92667. if (this.texture) {
  92668. this.texture.dispose();
  92669. }
  92670. // Remove from scene
  92671. var index = this._system.lensFlares.indexOf(this);
  92672. this._system.lensFlares.splice(index, 1);
  92673. };
  92674. ;
  92675. return LensFlare;
  92676. }());
  92677. BABYLON.LensFlare = LensFlare;
  92678. })(BABYLON || (BABYLON = {}));
  92679. //# sourceMappingURL=babylon.lensFlare.js.map
  92680. var BABYLON;
  92681. (function (BABYLON) {
  92682. // Adds the parser to the scene parsers.
  92683. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  92684. // Lens flares
  92685. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  92686. if (!container.lensFlareSystems) {
  92687. container.lensFlareSystems = new Array();
  92688. }
  92689. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  92690. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  92691. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  92692. container.lensFlareSystems.push(lf);
  92693. }
  92694. }
  92695. });
  92696. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  92697. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  92698. if (this.lensFlareSystems[index].name === name) {
  92699. return this.lensFlareSystems[index];
  92700. }
  92701. }
  92702. return null;
  92703. };
  92704. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  92705. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  92706. if (this.lensFlareSystems[index].id === id) {
  92707. return this.lensFlareSystems[index];
  92708. }
  92709. }
  92710. return null;
  92711. };
  92712. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  92713. var index = this.lensFlareSystems.indexOf(toRemove);
  92714. if (index !== -1) {
  92715. this.lensFlareSystems.splice(index, 1);
  92716. }
  92717. return index;
  92718. };
  92719. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  92720. this.lensFlareSystems.push(newLensFlareSystem);
  92721. };
  92722. /**
  92723. * Defines the lens flare scene component responsible to manage any lens flares
  92724. * in a given scene.
  92725. */
  92726. var LensFlareSystemSceneComponent = /** @class */ (function () {
  92727. /**
  92728. * Creates a new instance of the component for the given scene
  92729. * @param scene Defines the scene to register the component in
  92730. */
  92731. function LensFlareSystemSceneComponent(scene) {
  92732. /**
  92733. * The component name helpfull to identify the component in the list of scene components.
  92734. */
  92735. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  92736. this.scene = scene;
  92737. scene.lensFlareSystems = new Array();
  92738. }
  92739. /**
  92740. * Registers the component in a given scene
  92741. */
  92742. LensFlareSystemSceneComponent.prototype.register = function () {
  92743. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  92744. };
  92745. /**
  92746. * Rebuilds the elements related to this component in case of
  92747. * context lost for instance.
  92748. */
  92749. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  92750. // Nothing to do for lens flare
  92751. };
  92752. /**
  92753. * Adds all the element from the container to the scene
  92754. * @param container the container holding the elements
  92755. */
  92756. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  92757. var _this = this;
  92758. if (!container.lensFlareSystems) {
  92759. return;
  92760. }
  92761. container.lensFlareSystems.forEach(function (o) {
  92762. _this.scene.addLensFlareSystem(o);
  92763. });
  92764. };
  92765. /**
  92766. * Removes all the elements in the container from the scene
  92767. * @param container contains the elements to remove
  92768. */
  92769. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  92770. var _this = this;
  92771. if (!container.lensFlareSystems) {
  92772. return;
  92773. }
  92774. container.lensFlareSystems.forEach(function (o) {
  92775. _this.scene.removeLensFlareSystem(o);
  92776. });
  92777. };
  92778. /**
  92779. * Serializes the component data to the specified json object
  92780. * @param serializationObject The object to serialize to
  92781. */
  92782. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  92783. // Lens flares
  92784. serializationObject.lensFlareSystems = [];
  92785. var lensFlareSystems = this.scene.lensFlareSystems;
  92786. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  92787. var lensFlareSystem = lensFlareSystems_1[_i];
  92788. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  92789. }
  92790. };
  92791. /**
  92792. * Disposes the component and the associated ressources.
  92793. */
  92794. LensFlareSystemSceneComponent.prototype.dispose = function () {
  92795. var lensFlareSystems = this.scene.lensFlareSystems;
  92796. while (lensFlareSystems.length) {
  92797. lensFlareSystems[0].dispose();
  92798. }
  92799. };
  92800. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  92801. // Lens flares
  92802. if (this.scene.lensFlaresEnabled) {
  92803. var lensFlareSystems = this.scene.lensFlareSystems;
  92804. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  92805. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  92806. var lensFlareSystem = lensFlareSystems_2[_i];
  92807. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  92808. lensFlareSystem.render();
  92809. }
  92810. }
  92811. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  92812. }
  92813. };
  92814. return LensFlareSystemSceneComponent;
  92815. }());
  92816. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  92817. })(BABYLON || (BABYLON = {}));
  92818. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  92819. var BABYLON;
  92820. (function (BABYLON) {
  92821. /**
  92822. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  92823. * It is usually composed of several `BABYLON.lensFlare`.
  92824. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  92825. */
  92826. var LensFlareSystem = /** @class */ (function () {
  92827. /**
  92828. * Instantiates a lens flare system.
  92829. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  92830. * It is usually composed of several `BABYLON.lensFlare`.
  92831. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  92832. * @param name Define the name of the lens flare system in the scene
  92833. * @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh).
  92834. * @param scene Define the scene the lens flare system belongs to
  92835. */
  92836. function LensFlareSystem(
  92837. /**
  92838. * Define the name of the lens flare system
  92839. */
  92840. name, emitter, scene) {
  92841. this.name = name;
  92842. /**
  92843. * List of lens flares used in this system.
  92844. */
  92845. this.lensFlares = new Array();
  92846. /**
  92847. * Define a limit from the border the lens flare can be visible.
  92848. */
  92849. this.borderLimit = 300;
  92850. /**
  92851. * Define a viewport border we do not want to see the lens flare in.
  92852. */
  92853. this.viewportBorder = 0;
  92854. /**
  92855. * Restricts the rendering of the effect to only the camera rendering this layer mask.
  92856. */
  92857. this.layerMask = 0x0FFFFFFF;
  92858. this._vertexBuffers = {};
  92859. this._isEnabled = true;
  92860. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  92861. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  92862. if (!component) {
  92863. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  92864. scene._addComponent(component);
  92865. }
  92866. this._emitter = emitter;
  92867. this.id = name;
  92868. scene.lensFlareSystems.push(this);
  92869. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  92870. var engine = scene.getEngine();
  92871. // VBO
  92872. var vertices = [];
  92873. vertices.push(1, 1);
  92874. vertices.push(-1, 1);
  92875. vertices.push(-1, -1);
  92876. vertices.push(1, -1);
  92877. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  92878. // Indices
  92879. var indices = [];
  92880. indices.push(0);
  92881. indices.push(1);
  92882. indices.push(2);
  92883. indices.push(0);
  92884. indices.push(2);
  92885. indices.push(3);
  92886. this._indexBuffer = engine.createIndexBuffer(indices);
  92887. // Effects
  92888. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  92889. }
  92890. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  92891. /**
  92892. * Define if the lens flare system is enabled.
  92893. */
  92894. get: function () {
  92895. return this._isEnabled;
  92896. },
  92897. set: function (value) {
  92898. this._isEnabled = value;
  92899. },
  92900. enumerable: true,
  92901. configurable: true
  92902. });
  92903. /**
  92904. * Get the scene the effects belongs to.
  92905. * @returns the scene holding the lens flare system
  92906. */
  92907. LensFlareSystem.prototype.getScene = function () {
  92908. return this._scene;
  92909. };
  92910. /**
  92911. * Get the emitter of the lens flare system.
  92912. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  92913. * @returns the emitter of the lens flare system
  92914. */
  92915. LensFlareSystem.prototype.getEmitter = function () {
  92916. return this._emitter;
  92917. };
  92918. /**
  92919. * Set the emitter of the lens flare system.
  92920. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  92921. * @param newEmitter Define the new emitter of the system
  92922. */
  92923. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  92924. this._emitter = newEmitter;
  92925. };
  92926. /**
  92927. * Get the lens flare system emitter position.
  92928. * The emitter defines the source of the lens flares (it can be a camera, a light or a mesh).
  92929. * @returns the position
  92930. */
  92931. LensFlareSystem.prototype.getEmitterPosition = function () {
  92932. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  92933. };
  92934. /**
  92935. * @hidden
  92936. */
  92937. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  92938. var position = this.getEmitterPosition();
  92939. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  92940. this._positionX = position.x;
  92941. this._positionY = position.y;
  92942. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  92943. if (this.viewportBorder > 0) {
  92944. globalViewport.x -= this.viewportBorder;
  92945. globalViewport.y -= this.viewportBorder;
  92946. globalViewport.width += this.viewportBorder * 2;
  92947. globalViewport.height += this.viewportBorder * 2;
  92948. position.x += this.viewportBorder;
  92949. position.y += this.viewportBorder;
  92950. this._positionX += this.viewportBorder;
  92951. this._positionY += this.viewportBorder;
  92952. }
  92953. if (position.z > 0) {
  92954. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  92955. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  92956. return true;
  92957. }
  92958. return true;
  92959. }
  92960. return false;
  92961. };
  92962. /** @hidden */
  92963. LensFlareSystem.prototype._isVisible = function () {
  92964. if (!this._isEnabled || !this._scene.activeCamera) {
  92965. return false;
  92966. }
  92967. var emitterPosition = this.getEmitterPosition();
  92968. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  92969. var distance = direction.length();
  92970. direction.normalize();
  92971. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  92972. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  92973. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  92974. };
  92975. /**
  92976. * @hidden
  92977. */
  92978. LensFlareSystem.prototype.render = function () {
  92979. if (!this._effect.isReady() || !this._scene.activeCamera)
  92980. return false;
  92981. var engine = this._scene.getEngine();
  92982. var viewport = this._scene.activeCamera.viewport;
  92983. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  92984. // Position
  92985. if (!this.computeEffectivePosition(globalViewport)) {
  92986. return false;
  92987. }
  92988. // Visibility
  92989. if (!this._isVisible()) {
  92990. return false;
  92991. }
  92992. // Intensity
  92993. var awayX;
  92994. var awayY;
  92995. if (this._positionX < this.borderLimit + globalViewport.x) {
  92996. awayX = this.borderLimit + globalViewport.x - this._positionX;
  92997. }
  92998. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  92999. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  93000. }
  93001. else {
  93002. awayX = 0;
  93003. }
  93004. if (this._positionY < this.borderLimit + globalViewport.y) {
  93005. awayY = this.borderLimit + globalViewport.y - this._positionY;
  93006. }
  93007. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  93008. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  93009. }
  93010. else {
  93011. awayY = 0;
  93012. }
  93013. var away = (awayX > awayY) ? awayX : awayY;
  93014. away -= this.viewportBorder;
  93015. if (away > this.borderLimit) {
  93016. away = this.borderLimit;
  93017. }
  93018. var intensity = 1.0 - (away / this.borderLimit);
  93019. if (intensity < 0) {
  93020. return false;
  93021. }
  93022. if (intensity > 1.0) {
  93023. intensity = 1.0;
  93024. }
  93025. if (this.viewportBorder > 0) {
  93026. globalViewport.x += this.viewportBorder;
  93027. globalViewport.y += this.viewportBorder;
  93028. globalViewport.width -= this.viewportBorder * 2;
  93029. globalViewport.height -= this.viewportBorder * 2;
  93030. this._positionX -= this.viewportBorder;
  93031. this._positionY -= this.viewportBorder;
  93032. }
  93033. // Position
  93034. var centerX = globalViewport.x + globalViewport.width / 2;
  93035. var centerY = globalViewport.y + globalViewport.height / 2;
  93036. var distX = centerX - this._positionX;
  93037. var distY = centerY - this._positionY;
  93038. // Effects
  93039. engine.enableEffect(this._effect);
  93040. engine.setState(false);
  93041. engine.setDepthBuffer(false);
  93042. // VBOs
  93043. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  93044. // Flares
  93045. for (var index = 0; index < this.lensFlares.length; index++) {
  93046. var flare = this.lensFlares[index];
  93047. engine.setAlphaMode(flare.alphaMode);
  93048. var x = centerX - (distX * flare.position);
  93049. var y = centerY - (distY * flare.position);
  93050. var cw = flare.size;
  93051. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  93052. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  93053. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  93054. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  93055. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  93056. // Texture
  93057. this._effect.setTexture("textureSampler", flare.texture);
  93058. // Color
  93059. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  93060. // Draw order
  93061. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93062. }
  93063. engine.setDepthBuffer(true);
  93064. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  93065. return true;
  93066. };
  93067. /**
  93068. * Dispose and release the lens flare with its associated resources.
  93069. */
  93070. LensFlareSystem.prototype.dispose = function () {
  93071. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93072. if (vertexBuffer) {
  93073. vertexBuffer.dispose();
  93074. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  93075. }
  93076. if (this._indexBuffer) {
  93077. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  93078. this._indexBuffer = null;
  93079. }
  93080. while (this.lensFlares.length) {
  93081. this.lensFlares[0].dispose();
  93082. }
  93083. // Remove from scene
  93084. var index = this._scene.lensFlareSystems.indexOf(this);
  93085. this._scene.lensFlareSystems.splice(index, 1);
  93086. };
  93087. /**
  93088. * Parse a lens flare system from a JSON repressentation
  93089. * @param parsedLensFlareSystem Define the JSON to parse
  93090. * @param scene Define the scene the parsed system should be instantiated in
  93091. * @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures
  93092. * @returns the parsed system
  93093. */
  93094. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  93095. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  93096. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  93097. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  93098. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  93099. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  93100. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  93101. var parsedFlare = parsedLensFlareSystem.flares[index];
  93102. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  93103. }
  93104. return lensFlareSystem;
  93105. };
  93106. /**
  93107. * Serialize the current Lens Flare System into a JSON representation.
  93108. * @returns the serialized JSON
  93109. */
  93110. LensFlareSystem.prototype.serialize = function () {
  93111. var serializationObject = {};
  93112. serializationObject.id = this.id;
  93113. serializationObject.name = this.name;
  93114. serializationObject.emitterId = this.getEmitter().id;
  93115. serializationObject.borderLimit = this.borderLimit;
  93116. serializationObject.flares = [];
  93117. for (var index = 0; index < this.lensFlares.length; index++) {
  93118. var flare = this.lensFlares[index];
  93119. serializationObject.flares.push({
  93120. size: flare.size,
  93121. position: flare.position,
  93122. color: flare.color.asArray(),
  93123. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  93124. });
  93125. }
  93126. return serializationObject;
  93127. };
  93128. return LensFlareSystem;
  93129. }());
  93130. BABYLON.LensFlareSystem = LensFlareSystem;
  93131. })(BABYLON || (BABYLON = {}));
  93132. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  93133. var BABYLON;
  93134. (function (BABYLON) {
  93135. /**
  93136. * This is a holder class for the physics joint created by the physics plugin.
  93137. * It holds a set of functions to control the underlying joint.
  93138. */
  93139. var PhysicsJoint = /** @class */ (function () {
  93140. function PhysicsJoint(type, jointData) {
  93141. this.type = type;
  93142. this.jointData = jointData;
  93143. jointData.nativeParams = jointData.nativeParams || {};
  93144. }
  93145. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  93146. get: function () {
  93147. return this._physicsJoint;
  93148. },
  93149. set: function (newJoint) {
  93150. if (this._physicsJoint) {
  93151. //remove from the wolrd
  93152. }
  93153. this._physicsJoint = newJoint;
  93154. },
  93155. enumerable: true,
  93156. configurable: true
  93157. });
  93158. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  93159. set: function (physicsPlugin) {
  93160. this._physicsPlugin = physicsPlugin;
  93161. },
  93162. enumerable: true,
  93163. configurable: true
  93164. });
  93165. /**
  93166. * Execute a function that is physics-plugin specific.
  93167. * @param {Function} func the function that will be executed.
  93168. * It accepts two parameters: the physics world and the physics joint.
  93169. */
  93170. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  93171. func(this._physicsPlugin.world, this._physicsJoint);
  93172. };
  93173. //TODO check if the native joints are the same
  93174. //Joint Types
  93175. PhysicsJoint.DistanceJoint = 0;
  93176. PhysicsJoint.HingeJoint = 1;
  93177. PhysicsJoint.BallAndSocketJoint = 2;
  93178. PhysicsJoint.WheelJoint = 3;
  93179. PhysicsJoint.SliderJoint = 4;
  93180. //OIMO
  93181. PhysicsJoint.PrismaticJoint = 5;
  93182. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  93183. PhysicsJoint.UniversalJoint = 6;
  93184. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  93185. //Cannon
  93186. //Similar to a Ball-Joint. Different in params
  93187. PhysicsJoint.PointToPointJoint = 8;
  93188. //Cannon only at the moment
  93189. PhysicsJoint.SpringJoint = 9;
  93190. PhysicsJoint.LockJoint = 10;
  93191. return PhysicsJoint;
  93192. }());
  93193. BABYLON.PhysicsJoint = PhysicsJoint;
  93194. /**
  93195. * A class representing a physics distance joint.
  93196. */
  93197. var DistanceJoint = /** @class */ (function (_super) {
  93198. __extends(DistanceJoint, _super);
  93199. function DistanceJoint(jointData) {
  93200. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  93201. }
  93202. /**
  93203. * Update the predefined distance.
  93204. */
  93205. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  93206. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  93207. };
  93208. return DistanceJoint;
  93209. }(PhysicsJoint));
  93210. BABYLON.DistanceJoint = DistanceJoint;
  93211. var MotorEnabledJoint = /** @class */ (function (_super) {
  93212. __extends(MotorEnabledJoint, _super);
  93213. function MotorEnabledJoint(type, jointData) {
  93214. return _super.call(this, type, jointData) || this;
  93215. }
  93216. /**
  93217. * Set the motor values.
  93218. * Attention, this function is plugin specific. Engines won't react 100% the same.
  93219. * @param {number} force the force to apply
  93220. * @param {number} maxForce max force for this motor.
  93221. */
  93222. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  93223. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  93224. };
  93225. /**
  93226. * Set the motor's limits.
  93227. * Attention, this function is plugin specific. Engines won't react 100% the same.
  93228. */
  93229. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  93230. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  93231. };
  93232. return MotorEnabledJoint;
  93233. }(PhysicsJoint));
  93234. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  93235. /**
  93236. * This class represents a single hinge physics joint
  93237. */
  93238. var HingeJoint = /** @class */ (function (_super) {
  93239. __extends(HingeJoint, _super);
  93240. function HingeJoint(jointData) {
  93241. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  93242. }
  93243. /**
  93244. * Set the motor values.
  93245. * Attention, this function is plugin specific. Engines won't react 100% the same.
  93246. * @param {number} force the force to apply
  93247. * @param {number} maxForce max force for this motor.
  93248. */
  93249. HingeJoint.prototype.setMotor = function (force, maxForce) {
  93250. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  93251. };
  93252. /**
  93253. * Set the motor's limits.
  93254. * Attention, this function is plugin specific. Engines won't react 100% the same.
  93255. */
  93256. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  93257. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  93258. };
  93259. return HingeJoint;
  93260. }(MotorEnabledJoint));
  93261. BABYLON.HingeJoint = HingeJoint;
  93262. /**
  93263. * This class represents a dual hinge physics joint (same as wheel joint)
  93264. */
  93265. var Hinge2Joint = /** @class */ (function (_super) {
  93266. __extends(Hinge2Joint, _super);
  93267. function Hinge2Joint(jointData) {
  93268. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  93269. }
  93270. /**
  93271. * Set the motor values.
  93272. * Attention, this function is plugin specific. Engines won't react 100% the same.
  93273. * @param {number} force the force to apply
  93274. * @param {number} maxForce max force for this motor.
  93275. * @param {motorIndex} the motor's index, 0 or 1.
  93276. */
  93277. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  93278. if (motorIndex === void 0) { motorIndex = 0; }
  93279. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  93280. };
  93281. /**
  93282. * Set the motor limits.
  93283. * Attention, this function is plugin specific. Engines won't react 100% the same.
  93284. * @param {number} upperLimit the upper limit
  93285. * @param {number} lowerLimit lower limit
  93286. * @param {motorIndex} the motor's index, 0 or 1.
  93287. */
  93288. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  93289. if (motorIndex === void 0) { motorIndex = 0; }
  93290. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  93291. };
  93292. return Hinge2Joint;
  93293. }(MotorEnabledJoint));
  93294. BABYLON.Hinge2Joint = Hinge2Joint;
  93295. })(BABYLON || (BABYLON = {}));
  93296. //# sourceMappingURL=babylon.physicsJoint.js.map
  93297. var BABYLON;
  93298. (function (BABYLON) {
  93299. var PhysicsImpostor = /** @class */ (function () {
  93300. function PhysicsImpostor(object, type, _options, _scene) {
  93301. if (_options === void 0) { _options = { mass: 0 }; }
  93302. var _this = this;
  93303. this.object = object;
  93304. this.type = type;
  93305. this._options = _options;
  93306. this._scene = _scene;
  93307. this._bodyUpdateRequired = false;
  93308. this._onBeforePhysicsStepCallbacks = new Array();
  93309. this._onAfterPhysicsStepCallbacks = new Array();
  93310. this._onPhysicsCollideCallbacks = [];
  93311. this._deltaPosition = BABYLON.Vector3.Zero();
  93312. this._isDisposed = false;
  93313. //temp variables for parent rotation calculations
  93314. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  93315. this._tmpQuat = new BABYLON.Quaternion();
  93316. this._tmpQuat2 = new BABYLON.Quaternion();
  93317. /**
  93318. * this function is executed by the physics engine.
  93319. */
  93320. this.beforeStep = function () {
  93321. if (!_this._physicsEngine) {
  93322. return;
  93323. }
  93324. _this.object.translate(_this._deltaPosition, -1);
  93325. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  93326. _this.object.computeWorldMatrix(false);
  93327. if (_this.object.parent && _this.object.rotationQuaternion) {
  93328. _this.getParentsRotation();
  93329. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  93330. }
  93331. else {
  93332. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  93333. }
  93334. if (!_this._options.disableBidirectionalTransformation) {
  93335. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  93336. }
  93337. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  93338. func(_this);
  93339. });
  93340. };
  93341. /**
  93342. * this function is executed by the physics engine.
  93343. */
  93344. this.afterStep = function () {
  93345. if (!_this._physicsEngine) {
  93346. return;
  93347. }
  93348. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  93349. func(_this);
  93350. });
  93351. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  93352. // object has now its world rotation. needs to be converted to local.
  93353. if (_this.object.parent && _this.object.rotationQuaternion) {
  93354. _this.getParentsRotation();
  93355. _this._tmpQuat.conjugateInPlace();
  93356. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  93357. }
  93358. // take the position set and make it the absolute position of this object.
  93359. _this.object.setAbsolutePosition(_this.object.position);
  93360. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  93361. _this.object.translate(_this._deltaPosition, 1);
  93362. };
  93363. /**
  93364. * Legacy collision detection event support
  93365. */
  93366. this.onCollideEvent = null;
  93367. //event and body object due to cannon's event-based architecture.
  93368. this.onCollide = function (e) {
  93369. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  93370. return;
  93371. }
  93372. if (!_this._physicsEngine) {
  93373. return;
  93374. }
  93375. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  93376. if (otherImpostor) {
  93377. // Legacy collision detection event support
  93378. if (_this.onCollideEvent) {
  93379. _this.onCollideEvent(_this, otherImpostor);
  93380. }
  93381. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  93382. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  93383. }).forEach(function (obj) {
  93384. obj.callback(_this, otherImpostor);
  93385. });
  93386. }
  93387. };
  93388. //sanity check!
  93389. if (!this.object) {
  93390. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  93391. return;
  93392. }
  93393. //legacy support for old syntax.
  93394. if (!this._scene && object.getScene) {
  93395. this._scene = object.getScene();
  93396. }
  93397. if (!this._scene) {
  93398. return;
  93399. }
  93400. this._physicsEngine = this._scene.getPhysicsEngine();
  93401. if (!this._physicsEngine) {
  93402. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  93403. }
  93404. else {
  93405. //set the object's quaternion, if not set
  93406. if (!this.object.rotationQuaternion) {
  93407. if (this.object.rotation) {
  93408. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  93409. }
  93410. else {
  93411. this.object.rotationQuaternion = new BABYLON.Quaternion();
  93412. }
  93413. }
  93414. //default options params
  93415. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  93416. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  93417. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  93418. this._joints = [];
  93419. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  93420. if (!this.object.parent || this._options.ignoreParent) {
  93421. this._init();
  93422. }
  93423. else if (this.object.parent.physicsImpostor) {
  93424. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  93425. }
  93426. }
  93427. }
  93428. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  93429. get: function () {
  93430. return this._isDisposed;
  93431. },
  93432. enumerable: true,
  93433. configurable: true
  93434. });
  93435. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  93436. get: function () {
  93437. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  93438. },
  93439. set: function (value) {
  93440. this.setMass(value);
  93441. },
  93442. enumerable: true,
  93443. configurable: true
  93444. });
  93445. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  93446. get: function () {
  93447. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  93448. },
  93449. set: function (value) {
  93450. if (!this._physicsEngine) {
  93451. return;
  93452. }
  93453. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  93454. },
  93455. enumerable: true,
  93456. configurable: true
  93457. });
  93458. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  93459. get: function () {
  93460. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  93461. },
  93462. set: function (value) {
  93463. if (!this._physicsEngine) {
  93464. return;
  93465. }
  93466. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  93467. },
  93468. enumerable: true,
  93469. configurable: true
  93470. });
  93471. /**
  93472. * This function will completly initialize this impostor.
  93473. * It will create a new body - but only if this mesh has no parent.
  93474. * If it has, this impostor will not be used other than to define the impostor
  93475. * of the child mesh.
  93476. * @hidden
  93477. */
  93478. PhysicsImpostor.prototype._init = function () {
  93479. if (!this._physicsEngine) {
  93480. return;
  93481. }
  93482. this._physicsEngine.removeImpostor(this);
  93483. this.physicsBody = null;
  93484. this._parent = this._parent || this._getPhysicsParent();
  93485. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  93486. this._physicsEngine.addImpostor(this);
  93487. }
  93488. };
  93489. PhysicsImpostor.prototype._getPhysicsParent = function () {
  93490. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  93491. var parentMesh = this.object.parent;
  93492. return parentMesh.physicsImpostor;
  93493. }
  93494. return null;
  93495. };
  93496. /**
  93497. * Should a new body be generated.
  93498. */
  93499. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  93500. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  93501. };
  93502. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  93503. this.forceUpdate();
  93504. };
  93505. /**
  93506. * Force a regeneration of this or the parent's impostor's body.
  93507. * Use under cautious - This will remove all joints already implemented.
  93508. */
  93509. PhysicsImpostor.prototype.forceUpdate = function () {
  93510. this._init();
  93511. if (this.parent && !this._options.ignoreParent) {
  93512. this.parent.forceUpdate();
  93513. }
  93514. };
  93515. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  93516. /*public get mesh(): AbstractMesh {
  93517. return this._mesh;
  93518. }*/
  93519. /**
  93520. * Gets the body that holds this impostor. Either its own, or its parent.
  93521. */
  93522. get: function () {
  93523. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  93524. },
  93525. /**
  93526. * Set the physics body. Used mainly by the physics engine/plugin
  93527. */
  93528. set: function (physicsBody) {
  93529. if (this._physicsBody && this._physicsEngine) {
  93530. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  93531. }
  93532. this._physicsBody = physicsBody;
  93533. this.resetUpdateFlags();
  93534. },
  93535. enumerable: true,
  93536. configurable: true
  93537. });
  93538. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  93539. get: function () {
  93540. return !this._options.ignoreParent && this._parent ? this._parent : null;
  93541. },
  93542. set: function (value) {
  93543. this._parent = value;
  93544. },
  93545. enumerable: true,
  93546. configurable: true
  93547. });
  93548. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  93549. this._bodyUpdateRequired = false;
  93550. };
  93551. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  93552. if (this.object.getBoundingInfo) {
  93553. var q = this.object.rotationQuaternion;
  93554. //reset rotation
  93555. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  93556. //calculate the world matrix with no rotation
  93557. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  93558. var boundingInfo = this.object.getBoundingInfo();
  93559. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  93560. //bring back the rotation
  93561. this.object.rotationQuaternion = q;
  93562. //calculate the world matrix with the new rotation
  93563. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  93564. return size;
  93565. }
  93566. else {
  93567. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  93568. }
  93569. };
  93570. PhysicsImpostor.prototype.getObjectCenter = function () {
  93571. if (this.object.getBoundingInfo) {
  93572. var boundingInfo = this.object.getBoundingInfo();
  93573. return boundingInfo.boundingBox.centerWorld;
  93574. }
  93575. else {
  93576. return this.object.position;
  93577. }
  93578. };
  93579. /**
  93580. * Get a specific parametes from the options parameter.
  93581. */
  93582. PhysicsImpostor.prototype.getParam = function (paramName) {
  93583. return this._options[paramName];
  93584. };
  93585. /**
  93586. * Sets a specific parameter in the options given to the physics plugin
  93587. */
  93588. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  93589. this._options[paramName] = value;
  93590. this._bodyUpdateRequired = true;
  93591. };
  93592. /**
  93593. * Specifically change the body's mass option. Won't recreate the physics body object
  93594. */
  93595. PhysicsImpostor.prototype.setMass = function (mass) {
  93596. if (this.getParam("mass") !== mass) {
  93597. this.setParam("mass", mass);
  93598. }
  93599. if (this._physicsEngine) {
  93600. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  93601. }
  93602. };
  93603. PhysicsImpostor.prototype.getLinearVelocity = function () {
  93604. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  93605. };
  93606. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  93607. if (this._physicsEngine) {
  93608. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  93609. }
  93610. };
  93611. PhysicsImpostor.prototype.getAngularVelocity = function () {
  93612. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  93613. };
  93614. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  93615. if (this._physicsEngine) {
  93616. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  93617. }
  93618. };
  93619. /**
  93620. * Execute a function with the physics plugin native code.
  93621. * Provide a function the will have two variables - the world object and the physics body object.
  93622. */
  93623. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  93624. if (this._physicsEngine) {
  93625. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  93626. }
  93627. };
  93628. /**
  93629. * Register a function that will be executed before the physics world is stepping forward.
  93630. */
  93631. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  93632. this._onBeforePhysicsStepCallbacks.push(func);
  93633. };
  93634. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  93635. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  93636. if (index > -1) {
  93637. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  93638. }
  93639. else {
  93640. BABYLON.Tools.Warn("Function to remove was not found");
  93641. }
  93642. };
  93643. /**
  93644. * Register a function that will be executed after the physics step
  93645. */
  93646. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  93647. this._onAfterPhysicsStepCallbacks.push(func);
  93648. };
  93649. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  93650. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  93651. if (index > -1) {
  93652. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  93653. }
  93654. else {
  93655. BABYLON.Tools.Warn("Function to remove was not found");
  93656. }
  93657. };
  93658. /**
  93659. * register a function that will be executed when this impostor collides against a different body.
  93660. */
  93661. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  93662. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  93663. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  93664. };
  93665. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  93666. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  93667. var index = -1;
  93668. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  93669. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  93670. // chcek the arrays match
  93671. var sameList = cbDef.otherImpostors.every(function (impostor) {
  93672. return collidedAgainstList.indexOf(impostor) > -1;
  93673. });
  93674. if (sameList) {
  93675. index = idx;
  93676. }
  93677. return sameList;
  93678. }
  93679. return false;
  93680. });
  93681. if (found) {
  93682. this._onPhysicsCollideCallbacks.splice(index, 1);
  93683. }
  93684. else {
  93685. BABYLON.Tools.Warn("Function to remove was not found");
  93686. }
  93687. };
  93688. PhysicsImpostor.prototype.getParentsRotation = function () {
  93689. var parent = this.object.parent;
  93690. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  93691. while (parent) {
  93692. if (parent.rotationQuaternion) {
  93693. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  93694. }
  93695. else {
  93696. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  93697. }
  93698. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  93699. parent = parent.parent;
  93700. }
  93701. return this._tmpQuat;
  93702. };
  93703. /**
  93704. * Apply a force
  93705. */
  93706. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  93707. if (this._physicsEngine) {
  93708. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  93709. }
  93710. return this;
  93711. };
  93712. /**
  93713. * Apply an impulse
  93714. */
  93715. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  93716. if (this._physicsEngine) {
  93717. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  93718. }
  93719. return this;
  93720. };
  93721. /**
  93722. * A help function to create a joint.
  93723. */
  93724. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  93725. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  93726. this.addJoint(otherImpostor, joint);
  93727. return this;
  93728. };
  93729. /**
  93730. * Add a joint to this impostor with a different impostor.
  93731. */
  93732. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  93733. this._joints.push({
  93734. otherImpostor: otherImpostor,
  93735. joint: joint
  93736. });
  93737. if (this._physicsEngine) {
  93738. this._physicsEngine.addJoint(this, otherImpostor, joint);
  93739. }
  93740. return this;
  93741. };
  93742. /**
  93743. * Will keep this body still, in a sleep mode.
  93744. */
  93745. PhysicsImpostor.prototype.sleep = function () {
  93746. if (this._physicsEngine) {
  93747. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  93748. }
  93749. return this;
  93750. };
  93751. /**
  93752. * Wake the body up.
  93753. */
  93754. PhysicsImpostor.prototype.wakeUp = function () {
  93755. if (this._physicsEngine) {
  93756. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  93757. }
  93758. return this;
  93759. };
  93760. PhysicsImpostor.prototype.clone = function (newObject) {
  93761. if (!newObject)
  93762. return null;
  93763. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  93764. };
  93765. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  93766. var _this = this;
  93767. //no dispose if no physics engine is available.
  93768. if (!this._physicsEngine) {
  93769. return;
  93770. }
  93771. this._joints.forEach(function (j) {
  93772. if (_this._physicsEngine) {
  93773. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  93774. }
  93775. });
  93776. //dispose the physics body
  93777. this._physicsEngine.removeImpostor(this);
  93778. if (this.parent) {
  93779. this.parent.forceUpdate();
  93780. }
  93781. else {
  93782. /*this._object.getChildMeshes().forEach(function(mesh) {
  93783. if (mesh.physicsImpostor) {
  93784. if (disposeChildren) {
  93785. mesh.physicsImpostor.dispose();
  93786. mesh.physicsImpostor = null;
  93787. }
  93788. }
  93789. })*/
  93790. }
  93791. this._isDisposed = true;
  93792. };
  93793. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  93794. this._deltaPosition.copyFrom(position);
  93795. };
  93796. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  93797. if (!this._deltaRotation) {
  93798. this._deltaRotation = new BABYLON.Quaternion();
  93799. }
  93800. this._deltaRotation.copyFrom(rotation);
  93801. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  93802. };
  93803. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  93804. if (this._physicsEngine) {
  93805. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  93806. }
  93807. return this;
  93808. };
  93809. PhysicsImpostor.prototype.getRadius = function () {
  93810. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  93811. };
  93812. /**
  93813. * Sync a bone with this impostor
  93814. * @param bone The bone to sync to the impostor.
  93815. * @param boneMesh The mesh that the bone is influencing.
  93816. * @param jointPivot The pivot of the joint / bone in local space.
  93817. * @param distToJoint Optional distance from the impostor to the joint.
  93818. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  93819. */
  93820. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  93821. var tempVec = PhysicsImpostor._tmpVecs[0];
  93822. var mesh = this.object;
  93823. if (mesh.rotationQuaternion) {
  93824. if (adjustRotation) {
  93825. var tempQuat = PhysicsImpostor._tmpQuat;
  93826. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  93827. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  93828. }
  93829. else {
  93830. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  93831. }
  93832. }
  93833. tempVec.x = 0;
  93834. tempVec.y = 0;
  93835. tempVec.z = 0;
  93836. if (jointPivot) {
  93837. tempVec.x = jointPivot.x;
  93838. tempVec.y = jointPivot.y;
  93839. tempVec.z = jointPivot.z;
  93840. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  93841. if (distToJoint === undefined || distToJoint === null) {
  93842. distToJoint = jointPivot.length();
  93843. }
  93844. tempVec.x *= distToJoint;
  93845. tempVec.y *= distToJoint;
  93846. tempVec.z *= distToJoint;
  93847. }
  93848. if (bone.getParent()) {
  93849. tempVec.addInPlace(mesh.getAbsolutePosition());
  93850. bone.setAbsolutePosition(tempVec, boneMesh);
  93851. }
  93852. else {
  93853. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  93854. boneMesh.position.x -= tempVec.x;
  93855. boneMesh.position.y -= tempVec.y;
  93856. boneMesh.position.z -= tempVec.z;
  93857. }
  93858. };
  93859. /**
  93860. * Sync impostor to a bone
  93861. * @param bone The bone that the impostor will be synced to.
  93862. * @param boneMesh The mesh that the bone is influencing.
  93863. * @param jointPivot The pivot of the joint / bone in local space.
  93864. * @param distToJoint Optional distance from the impostor to the joint.
  93865. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  93866. * @param boneAxis Optional vector3 axis the bone is aligned with
  93867. */
  93868. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  93869. var mesh = this.object;
  93870. if (mesh.rotationQuaternion) {
  93871. if (adjustRotation) {
  93872. var tempQuat = PhysicsImpostor._tmpQuat;
  93873. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  93874. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  93875. }
  93876. else {
  93877. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  93878. }
  93879. }
  93880. var pos = PhysicsImpostor._tmpVecs[0];
  93881. var boneDir = PhysicsImpostor._tmpVecs[1];
  93882. if (!boneAxis) {
  93883. boneAxis = PhysicsImpostor._tmpVecs[2];
  93884. boneAxis.x = 0;
  93885. boneAxis.y = 1;
  93886. boneAxis.z = 0;
  93887. }
  93888. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  93889. bone.getAbsolutePositionToRef(boneMesh, pos);
  93890. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  93891. distToJoint = jointPivot.length();
  93892. }
  93893. if (distToJoint !== undefined && distToJoint !== null) {
  93894. pos.x += boneDir.x * distToJoint;
  93895. pos.y += boneDir.y * distToJoint;
  93896. pos.z += boneDir.z * distToJoint;
  93897. }
  93898. mesh.setAbsolutePosition(pos);
  93899. };
  93900. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  93901. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  93902. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  93903. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  93904. //Impostor types
  93905. PhysicsImpostor.NoImpostor = 0;
  93906. PhysicsImpostor.SphereImpostor = 1;
  93907. PhysicsImpostor.BoxImpostor = 2;
  93908. PhysicsImpostor.PlaneImpostor = 3;
  93909. PhysicsImpostor.MeshImpostor = 4;
  93910. PhysicsImpostor.CylinderImpostor = 7;
  93911. PhysicsImpostor.ParticleImpostor = 8;
  93912. PhysicsImpostor.HeightmapImpostor = 9;
  93913. return PhysicsImpostor;
  93914. }());
  93915. BABYLON.PhysicsImpostor = PhysicsImpostor;
  93916. })(BABYLON || (BABYLON = {}));
  93917. //# sourceMappingURL=babylon.physicsImpostor.js.map
  93918. var BABYLON;
  93919. (function (BABYLON) {
  93920. /**
  93921. * Class used to control physics engine
  93922. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  93923. */
  93924. var PhysicsEngine = /** @class */ (function () {
  93925. /**
  93926. * Creates a new Physics Engine
  93927. * @param gravity defines the gravity vector used by the simulation
  93928. * @param _physicsPlugin defines the plugin to use (CannonJS by default)
  93929. */
  93930. function PhysicsEngine(gravity, _physicsPlugin) {
  93931. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  93932. this._physicsPlugin = _physicsPlugin;
  93933. this._impostors = [];
  93934. this._joints = [];
  93935. if (!this._physicsPlugin.isSupported()) {
  93936. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  93937. + "Please make sure it is included.");
  93938. }
  93939. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  93940. this.setGravity(gravity);
  93941. this.setTimeStep();
  93942. }
  93943. /**
  93944. * Sets the gravity vector used by the simulation
  93945. * @param gravity defines the gravity vector to use
  93946. */
  93947. PhysicsEngine.prototype.setGravity = function (gravity) {
  93948. this.gravity = gravity;
  93949. this._physicsPlugin.setGravity(this.gravity);
  93950. };
  93951. /**
  93952. * Set the time step of the physics engine.
  93953. * Default is 1/60.
  93954. * To slow it down, enter 1/600 for example.
  93955. * To speed it up, 1/30
  93956. * @param newTimeStep defines the new timestep to apply to this world.
  93957. */
  93958. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  93959. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  93960. this._physicsPlugin.setTimeStep(newTimeStep);
  93961. };
  93962. /**
  93963. * Get the time step of the physics engine.
  93964. * @returns the current time step
  93965. */
  93966. PhysicsEngine.prototype.getTimeStep = function () {
  93967. return this._physicsPlugin.getTimeStep();
  93968. };
  93969. /**
  93970. * Release all resources
  93971. */
  93972. PhysicsEngine.prototype.dispose = function () {
  93973. this._impostors.forEach(function (impostor) {
  93974. impostor.dispose();
  93975. });
  93976. this._physicsPlugin.dispose();
  93977. };
  93978. /**
  93979. * Gets the name of the current physics plugin
  93980. * @returns the name of the plugin
  93981. */
  93982. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  93983. return this._physicsPlugin.name;
  93984. };
  93985. /**
  93986. * Adding a new impostor for the impostor tracking.
  93987. * This will be done by the impostor itself.
  93988. * @param impostor the impostor to add
  93989. */
  93990. PhysicsEngine.prototype.addImpostor = function (impostor) {
  93991. impostor.uniqueId = this._impostors.push(impostor);
  93992. //if no parent, generate the body
  93993. if (!impostor.parent) {
  93994. this._physicsPlugin.generatePhysicsBody(impostor);
  93995. }
  93996. };
  93997. /**
  93998. * Remove an impostor from the engine.
  93999. * This impostor and its mesh will not longer be updated by the physics engine.
  94000. * @param impostor the impostor to remove
  94001. */
  94002. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  94003. var index = this._impostors.indexOf(impostor);
  94004. if (index > -1) {
  94005. var removed = this._impostors.splice(index, 1);
  94006. //Is it needed?
  94007. if (removed.length) {
  94008. //this will also remove it from the world.
  94009. removed[0].physicsBody = null;
  94010. }
  94011. }
  94012. };
  94013. /**
  94014. * Add a joint to the physics engine
  94015. * @param mainImpostor defines the main impostor to which the joint is added.
  94016. * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
  94017. * @param joint defines the joint that will connect both impostors.
  94018. */
  94019. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  94020. var impostorJoint = {
  94021. mainImpostor: mainImpostor,
  94022. connectedImpostor: connectedImpostor,
  94023. joint: joint
  94024. };
  94025. joint.physicsPlugin = this._physicsPlugin;
  94026. this._joints.push(impostorJoint);
  94027. this._physicsPlugin.generateJoint(impostorJoint);
  94028. };
  94029. /**
  94030. * Removes a joint from the simulation
  94031. * @param mainImpostor defines the impostor used with the joint
  94032. * @param connectedImpostor defines the other impostor connected to the main one by the joint
  94033. * @param joint defines the joint to remove
  94034. */
  94035. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  94036. var matchingJoints = this._joints.filter(function (impostorJoint) {
  94037. return (impostorJoint.connectedImpostor === connectedImpostor
  94038. && impostorJoint.joint === joint
  94039. && impostorJoint.mainImpostor === mainImpostor);
  94040. });
  94041. if (matchingJoints.length) {
  94042. this._physicsPlugin.removeJoint(matchingJoints[0]);
  94043. //TODO remove it from the list as well
  94044. }
  94045. };
  94046. /**
  94047. * Called by the scene. No need to call it.
  94048. * @param delta defines the timespam between frames
  94049. */
  94050. PhysicsEngine.prototype._step = function (delta) {
  94051. var _this = this;
  94052. //check if any mesh has no body / requires an update
  94053. this._impostors.forEach(function (impostor) {
  94054. if (impostor.isBodyInitRequired()) {
  94055. _this._physicsPlugin.generatePhysicsBody(impostor);
  94056. }
  94057. });
  94058. if (delta > 0.1) {
  94059. delta = 0.1;
  94060. }
  94061. else if (delta <= 0) {
  94062. delta = 1.0 / 60.0;
  94063. }
  94064. this._physicsPlugin.executeStep(delta, this._impostors);
  94065. };
  94066. /**
  94067. * Gets the current plugin used to run the simulation
  94068. * @returns current plugin
  94069. */
  94070. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  94071. return this._physicsPlugin;
  94072. };
  94073. /**
  94074. * Gets the list of physic impostors
  94075. * @returns an array of PhysicsImpostor
  94076. */
  94077. PhysicsEngine.prototype.getImpostors = function () {
  94078. return this._impostors;
  94079. };
  94080. /**
  94081. * Gets the impostor for a physics enabled object
  94082. * @param object defines the object impersonated by the impostor
  94083. * @returns the PhysicsImpostor or null if not found
  94084. */
  94085. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  94086. for (var i = 0; i < this._impostors.length; ++i) {
  94087. if (this._impostors[i].object === object) {
  94088. return this._impostors[i];
  94089. }
  94090. }
  94091. return null;
  94092. };
  94093. /**
  94094. * Gets the impostor for a physics body object
  94095. * @param body defines physics body used by the impostor
  94096. * @returns the PhysicsImpostor or null if not found
  94097. */
  94098. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  94099. for (var i = 0; i < this._impostors.length; ++i) {
  94100. if (this._impostors[i].physicsBody === body) {
  94101. return this._impostors[i];
  94102. }
  94103. }
  94104. return null;
  94105. };
  94106. /**
  94107. * Global value used to control the smallest number supported by the simulation
  94108. */
  94109. PhysicsEngine.Epsilon = 0.001;
  94110. return PhysicsEngine;
  94111. }());
  94112. BABYLON.PhysicsEngine = PhysicsEngine;
  94113. })(BABYLON || (BABYLON = {}));
  94114. //# sourceMappingURL=babylon.physicsEngine.js.map
  94115. var BABYLON;
  94116. (function (BABYLON) {
  94117. var PhysicsHelper = /** @class */ (function () {
  94118. function PhysicsHelper(scene) {
  94119. this._scene = scene;
  94120. this._physicsEngine = this._scene.getPhysicsEngine();
  94121. if (!this._physicsEngine) {
  94122. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  94123. }
  94124. }
  94125. /**
  94126. * @param {Vector3} origin the origin of the explosion
  94127. * @param {number} radius the explosion radius
  94128. * @param {number} strength the explosion strength
  94129. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  94130. */
  94131. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  94132. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  94133. if (!this._physicsEngine) {
  94134. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  94135. return null;
  94136. }
  94137. var impostors = this._physicsEngine.getImpostors();
  94138. if (impostors.length === 0) {
  94139. return null;
  94140. }
  94141. var event = new PhysicsRadialExplosionEvent(this._scene);
  94142. impostors.forEach(function (impostor) {
  94143. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  94144. if (!impostorForceAndContactPoint) {
  94145. return;
  94146. }
  94147. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  94148. });
  94149. event.dispose(false);
  94150. return event;
  94151. };
  94152. /**
  94153. * @param {Vector3} origin the origin of the explosion
  94154. * @param {number} radius the explosion radius
  94155. * @param {number} strength the explosion strength
  94156. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  94157. */
  94158. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  94159. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  94160. if (!this._physicsEngine) {
  94161. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  94162. return null;
  94163. }
  94164. var impostors = this._physicsEngine.getImpostors();
  94165. if (impostors.length === 0) {
  94166. return null;
  94167. }
  94168. var event = new PhysicsRadialExplosionEvent(this._scene);
  94169. impostors.forEach(function (impostor) {
  94170. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  94171. if (!impostorForceAndContactPoint) {
  94172. return;
  94173. }
  94174. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  94175. });
  94176. event.dispose(false);
  94177. return event;
  94178. };
  94179. /**
  94180. * @param {Vector3} origin the origin of the explosion
  94181. * @param {number} radius the explosion radius
  94182. * @param {number} strength the explosion strength
  94183. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  94184. */
  94185. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  94186. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  94187. if (!this._physicsEngine) {
  94188. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  94189. return null;
  94190. }
  94191. var impostors = this._physicsEngine.getImpostors();
  94192. if (impostors.length === 0) {
  94193. return null;
  94194. }
  94195. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  94196. event.dispose(false);
  94197. return event;
  94198. };
  94199. /**
  94200. * @param {Vector3} origin the origin of the updraft
  94201. * @param {number} radius the radius of the updraft
  94202. * @param {number} strength the strength of the updraft
  94203. * @param {number} height the height of the updraft
  94204. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  94205. */
  94206. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  94207. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  94208. if (!this._physicsEngine) {
  94209. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  94210. return null;
  94211. }
  94212. if (this._physicsEngine.getImpostors().length === 0) {
  94213. return null;
  94214. }
  94215. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  94216. event.dispose(false);
  94217. return event;
  94218. };
  94219. /**
  94220. * @param {Vector3} origin the of the vortex
  94221. * @param {number} radius the radius of the vortex
  94222. * @param {number} strength the strength of the vortex
  94223. * @param {number} height the height of the vortex
  94224. */
  94225. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  94226. if (!this._physicsEngine) {
  94227. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  94228. return null;
  94229. }
  94230. if (this._physicsEngine.getImpostors().length === 0) {
  94231. return null;
  94232. }
  94233. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  94234. event.dispose(false);
  94235. return event;
  94236. };
  94237. return PhysicsHelper;
  94238. }());
  94239. BABYLON.PhysicsHelper = PhysicsHelper;
  94240. /***** Radial explosion *****/
  94241. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  94242. function PhysicsRadialExplosionEvent(scene) {
  94243. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  94244. this._rays = [];
  94245. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  94246. this._scene = scene;
  94247. }
  94248. /**
  94249. * Returns the data related to the radial explosion event (sphere & rays).
  94250. * @returns {PhysicsRadialExplosionEventData}
  94251. */
  94252. PhysicsRadialExplosionEvent.prototype.getData = function () {
  94253. this._dataFetched = true;
  94254. return {
  94255. sphere: this._sphere,
  94256. rays: this._rays,
  94257. };
  94258. };
  94259. /**
  94260. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  94261. * @param impostor
  94262. * @param {Vector3} origin the origin of the explosion
  94263. * @param {number} radius the explosion radius
  94264. * @param {number} strength the explosion strength
  94265. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  94266. * @returns {Nullable<PhysicsForceAndContactPoint>}
  94267. */
  94268. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  94269. if (impostor.mass === 0) {
  94270. return null;
  94271. }
  94272. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  94273. return null;
  94274. }
  94275. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  94276. return null;
  94277. }
  94278. var impostorObjectCenter = impostor.getObjectCenter();
  94279. var direction = impostorObjectCenter.subtract(origin);
  94280. var ray = new BABYLON.Ray(origin, direction, radius);
  94281. this._rays.push(ray);
  94282. var hit = ray.intersectsMesh(impostor.object);
  94283. var contactPoint = hit.pickedPoint;
  94284. if (!contactPoint) {
  94285. return null;
  94286. }
  94287. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  94288. if (distanceFromOrigin > radius) {
  94289. return null;
  94290. }
  94291. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  94292. ? strength
  94293. : strength * (1 - (distanceFromOrigin / radius));
  94294. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  94295. return { force: force, contactPoint: contactPoint };
  94296. };
  94297. /**
  94298. * Disposes the sphere.
  94299. * @param {bolean} force
  94300. */
  94301. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  94302. var _this = this;
  94303. if (force === void 0) { force = true; }
  94304. if (force) {
  94305. this._sphere.dispose();
  94306. }
  94307. else {
  94308. setTimeout(function () {
  94309. if (!_this._dataFetched) {
  94310. _this._sphere.dispose();
  94311. }
  94312. }, 0);
  94313. }
  94314. };
  94315. /*** Helpers ***/
  94316. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  94317. if (!this._sphere) {
  94318. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  94319. this._sphere.isVisible = false;
  94320. }
  94321. };
  94322. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  94323. var impostorObject = impostor.object;
  94324. this._prepareSphere();
  94325. this._sphere.position = origin;
  94326. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  94327. this._sphere._updateBoundingInfo();
  94328. this._sphere.computeWorldMatrix(true);
  94329. return this._sphere.intersectsMesh(impostorObject, true);
  94330. };
  94331. return PhysicsRadialExplosionEvent;
  94332. }());
  94333. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  94334. /***** Gravitational Field *****/
  94335. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  94336. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  94337. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  94338. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  94339. this._physicsHelper = physicsHelper;
  94340. this._scene = scene;
  94341. this._origin = origin;
  94342. this._radius = radius;
  94343. this._strength = strength;
  94344. this._falloff = falloff;
  94345. this._tickCallback = this._tick.bind(this);
  94346. }
  94347. /**
  94348. * Returns the data related to the gravitational field event (sphere).
  94349. * @returns {PhysicsGravitationalFieldEventData}
  94350. */
  94351. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  94352. this._dataFetched = true;
  94353. return {
  94354. sphere: this._sphere,
  94355. };
  94356. };
  94357. /**
  94358. * Enables the gravitational field.
  94359. */
  94360. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  94361. this._tickCallback.call(this);
  94362. this._scene.registerBeforeRender(this._tickCallback);
  94363. };
  94364. /**
  94365. * Disables the gravitational field.
  94366. */
  94367. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  94368. this._scene.unregisterBeforeRender(this._tickCallback);
  94369. };
  94370. /**
  94371. * Disposes the sphere.
  94372. * @param {bolean} force
  94373. */
  94374. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  94375. var _this = this;
  94376. if (force === void 0) { force = true; }
  94377. if (force) {
  94378. this._sphere.dispose();
  94379. }
  94380. else {
  94381. setTimeout(function () {
  94382. if (!_this._dataFetched) {
  94383. _this._sphere.dispose();
  94384. }
  94385. }, 0);
  94386. }
  94387. };
  94388. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  94389. // Since the params won't change, we fetch the event only once
  94390. if (this._sphere) {
  94391. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  94392. }
  94393. else {
  94394. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  94395. if (radialExplosionEvent) {
  94396. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  94397. }
  94398. }
  94399. };
  94400. return PhysicsGravitationalFieldEvent;
  94401. }());
  94402. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  94403. /***** Updraft *****/
  94404. var PhysicsUpdraftEvent = /** @class */ (function () {
  94405. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  94406. this._scene = _scene;
  94407. this._origin = _origin;
  94408. this._radius = _radius;
  94409. this._strength = _strength;
  94410. this._height = _height;
  94411. this._updraftMode = _updraftMode;
  94412. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  94413. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  94414. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  94415. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  94416. this._physicsEngine = this._scene.getPhysicsEngine();
  94417. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  94418. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  94419. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  94420. this._originDirection = this._origin.subtract(this._originTop).normalize();
  94421. }
  94422. this._tickCallback = this._tick.bind(this);
  94423. }
  94424. /**
  94425. * Returns the data related to the updraft event (cylinder).
  94426. * @returns {PhysicsUpdraftEventData}
  94427. */
  94428. PhysicsUpdraftEvent.prototype.getData = function () {
  94429. this._dataFetched = true;
  94430. return {
  94431. cylinder: this._cylinder,
  94432. };
  94433. };
  94434. /**
  94435. * Enables the updraft.
  94436. */
  94437. PhysicsUpdraftEvent.prototype.enable = function () {
  94438. this._tickCallback.call(this);
  94439. this._scene.registerBeforeRender(this._tickCallback);
  94440. };
  94441. /**
  94442. * Disables the cortex.
  94443. */
  94444. PhysicsUpdraftEvent.prototype.disable = function () {
  94445. this._scene.unregisterBeforeRender(this._tickCallback);
  94446. };
  94447. /**
  94448. * Disposes the sphere.
  94449. * @param {bolean} force
  94450. */
  94451. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  94452. var _this = this;
  94453. if (force === void 0) { force = true; }
  94454. if (force) {
  94455. this._cylinder.dispose();
  94456. }
  94457. else {
  94458. setTimeout(function () {
  94459. if (!_this._dataFetched) {
  94460. _this._cylinder.dispose();
  94461. }
  94462. }, 0);
  94463. }
  94464. };
  94465. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  94466. if (impostor.mass === 0) {
  94467. return null;
  94468. }
  94469. if (!this._intersectsWithCylinder(impostor)) {
  94470. return null;
  94471. }
  94472. var impostorObjectCenter = impostor.getObjectCenter();
  94473. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  94474. var direction = this._originDirection;
  94475. }
  94476. else {
  94477. var direction = impostorObjectCenter.subtract(this._originTop);
  94478. }
  94479. var multiplier = this._strength * -1;
  94480. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  94481. return { force: force, contactPoint: impostorObjectCenter };
  94482. };
  94483. PhysicsUpdraftEvent.prototype._tick = function () {
  94484. var _this = this;
  94485. this._physicsEngine.getImpostors().forEach(function (impostor) {
  94486. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  94487. if (!impostorForceAndContactPoint) {
  94488. return;
  94489. }
  94490. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  94491. });
  94492. };
  94493. /*** Helpers ***/
  94494. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  94495. if (!this._cylinder) {
  94496. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  94497. height: this._height,
  94498. diameter: this._radius * 2,
  94499. }, this._scene);
  94500. this._cylinder.isVisible = false;
  94501. }
  94502. };
  94503. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  94504. var impostorObject = impostor.object;
  94505. this._prepareCylinder();
  94506. this._cylinder.position = this._cylinderPosition;
  94507. return this._cylinder.intersectsMesh(impostorObject, true);
  94508. };
  94509. return PhysicsUpdraftEvent;
  94510. }());
  94511. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  94512. /***** Vortex *****/
  94513. var PhysicsVortexEvent = /** @class */ (function () {
  94514. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  94515. this._scene = _scene;
  94516. this._origin = _origin;
  94517. this._radius = _radius;
  94518. this._strength = _strength;
  94519. this._height = _height;
  94520. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  94521. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  94522. this._updraftMultiplier = 0.02;
  94523. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  94524. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  94525. this._physicsEngine = this._scene.getPhysicsEngine();
  94526. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  94527. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  94528. this._tickCallback = this._tick.bind(this);
  94529. }
  94530. /**
  94531. * Returns the data related to the vortex event (cylinder).
  94532. * @returns {PhysicsVortexEventData}
  94533. */
  94534. PhysicsVortexEvent.prototype.getData = function () {
  94535. this._dataFetched = true;
  94536. return {
  94537. cylinder: this._cylinder,
  94538. };
  94539. };
  94540. /**
  94541. * Enables the vortex.
  94542. */
  94543. PhysicsVortexEvent.prototype.enable = function () {
  94544. this._tickCallback.call(this);
  94545. this._scene.registerBeforeRender(this._tickCallback);
  94546. };
  94547. /**
  94548. * Disables the cortex.
  94549. */
  94550. PhysicsVortexEvent.prototype.disable = function () {
  94551. this._scene.unregisterBeforeRender(this._tickCallback);
  94552. };
  94553. /**
  94554. * Disposes the sphere.
  94555. * @param {bolean} force
  94556. */
  94557. PhysicsVortexEvent.prototype.dispose = function (force) {
  94558. var _this = this;
  94559. if (force === void 0) { force = true; }
  94560. if (force) {
  94561. this._cylinder.dispose();
  94562. }
  94563. else {
  94564. setTimeout(function () {
  94565. if (!_this._dataFetched) {
  94566. _this._cylinder.dispose();
  94567. }
  94568. }, 0);
  94569. }
  94570. };
  94571. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  94572. if (impostor.mass === 0) {
  94573. return null;
  94574. }
  94575. if (!this._intersectsWithCylinder(impostor)) {
  94576. return null;
  94577. }
  94578. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  94579. return null;
  94580. }
  94581. var impostorObjectCenter = impostor.getObjectCenter();
  94582. 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)
  94583. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  94584. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  94585. var hit = ray.intersectsMesh(impostor.object);
  94586. var contactPoint = hit.pickedPoint;
  94587. if (!contactPoint) {
  94588. return null;
  94589. }
  94590. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  94591. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  94592. var directionToOrigin = contactPoint.normalize();
  94593. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  94594. directionToOrigin = directionToOrigin.negate();
  94595. }
  94596. // TODO: find a more physically based solution
  94597. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  94598. var forceX = directionToOrigin.x * this._strength / 8;
  94599. var forceY = directionToOrigin.y * this._updraftMultiplier;
  94600. var forceZ = directionToOrigin.z * this._strength / 8;
  94601. }
  94602. else {
  94603. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  94604. var forceY = this._originTop.y * this._updraftMultiplier;
  94605. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  94606. }
  94607. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  94608. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  94609. return { force: force, contactPoint: impostorObjectCenter };
  94610. };
  94611. PhysicsVortexEvent.prototype._tick = function () {
  94612. var _this = this;
  94613. this._physicsEngine.getImpostors().forEach(function (impostor) {
  94614. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  94615. if (!impostorForceAndContactPoint) {
  94616. return;
  94617. }
  94618. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  94619. });
  94620. };
  94621. /*** Helpers ***/
  94622. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  94623. if (!this._cylinder) {
  94624. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  94625. height: this._height,
  94626. diameter: this._radius * 2,
  94627. }, this._scene);
  94628. this._cylinder.isVisible = false;
  94629. }
  94630. };
  94631. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  94632. var impostorObject = impostor.object;
  94633. this._prepareCylinder();
  94634. this._cylinder.position = this._cylinderPosition;
  94635. return this._cylinder.intersectsMesh(impostorObject, true);
  94636. };
  94637. return PhysicsVortexEvent;
  94638. }());
  94639. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  94640. /***** Enums *****/
  94641. /**
  94642. * The strenght of the force in correspondence to the distance of the affected object
  94643. */
  94644. var PhysicsRadialImpulseFalloff;
  94645. (function (PhysicsRadialImpulseFalloff) {
  94646. /** Defines that impulse is constant in strength across it's whole radius */
  94647. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  94648. /** DEfines that impulse gets weaker if it's further from the origin */
  94649. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  94650. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  94651. /**
  94652. * The strenght of the force in correspondence to the distance of the affected object
  94653. */
  94654. var PhysicsUpdraftMode;
  94655. (function (PhysicsUpdraftMode) {
  94656. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  94657. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  94658. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  94659. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  94660. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  94661. })(BABYLON || (BABYLON = {}));
  94662. //# sourceMappingURL=babylon.physicsHelper.js.map
  94663. var BABYLON;
  94664. (function (BABYLON) {
  94665. /** @hidden */
  94666. var CannonJSPlugin = /** @class */ (function () {
  94667. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  94668. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  94669. if (iterations === void 0) { iterations = 10; }
  94670. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  94671. this.name = "CannonJSPlugin";
  94672. this._physicsMaterials = new Array();
  94673. this._fixedTimeStep = 1 / 60;
  94674. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  94675. this.BJSCANNON = CANNON;
  94676. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  94677. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  94678. this._tmpPosition = BABYLON.Vector3.Zero();
  94679. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  94680. this._tmpUnityRotation = new BABYLON.Quaternion();
  94681. if (!this.isSupported()) {
  94682. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  94683. return;
  94684. }
  94685. this._extendNamespace();
  94686. this.world = new this.BJSCANNON.World();
  94687. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  94688. this.world.solver.iterations = iterations;
  94689. }
  94690. CannonJSPlugin.prototype.setGravity = function (gravity) {
  94691. this.world.gravity.copy(gravity);
  94692. };
  94693. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  94694. this._fixedTimeStep = timeStep;
  94695. };
  94696. CannonJSPlugin.prototype.getTimeStep = function () {
  94697. return this._fixedTimeStep;
  94698. };
  94699. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  94700. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  94701. };
  94702. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  94703. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  94704. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  94705. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  94706. };
  94707. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  94708. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  94709. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  94710. impostor.physicsBody.applyForce(impulse, worldPoint);
  94711. };
  94712. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  94713. //parent-child relationship. Does this impostor has a parent impostor?
  94714. if (impostor.parent) {
  94715. if (impostor.physicsBody) {
  94716. this.removePhysicsBody(impostor);
  94717. //TODO is that needed?
  94718. impostor.forceUpdate();
  94719. }
  94720. return;
  94721. }
  94722. //should a new body be created for this impostor?
  94723. if (impostor.isBodyInitRequired()) {
  94724. var shape = this._createShape(impostor);
  94725. //unregister events, if body is being changed
  94726. var oldBody = impostor.physicsBody;
  94727. if (oldBody) {
  94728. this.removePhysicsBody(impostor);
  94729. }
  94730. //create the body and material
  94731. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  94732. var bodyCreationObject = {
  94733. mass: impostor.getParam("mass"),
  94734. material: material
  94735. };
  94736. // A simple extend, in case native options were used.
  94737. var nativeOptions = impostor.getParam("nativeOptions");
  94738. for (var key in nativeOptions) {
  94739. if (nativeOptions.hasOwnProperty(key)) {
  94740. bodyCreationObject[key] = nativeOptions[key];
  94741. }
  94742. }
  94743. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  94744. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  94745. this.world.addEventListener("preStep", impostor.beforeStep);
  94746. this.world.addEventListener("postStep", impostor.afterStep);
  94747. impostor.physicsBody.addShape(shape);
  94748. this.world.add(impostor.physicsBody);
  94749. //try to keep the body moving in the right direction by taking old properties.
  94750. //Should be tested!
  94751. if (oldBody) {
  94752. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  94753. impostor.physicsBody[param].copy(oldBody[param]);
  94754. });
  94755. }
  94756. this._processChildMeshes(impostor);
  94757. }
  94758. //now update the body's transformation
  94759. this._updatePhysicsBodyTransformation(impostor);
  94760. };
  94761. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  94762. var _this = this;
  94763. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  94764. var currentRotation = mainImpostor.object.rotationQuaternion;
  94765. if (meshChildren.length) {
  94766. var processMesh = function (localPosition, mesh) {
  94767. if (!currentRotation || !mesh.rotationQuaternion) {
  94768. return;
  94769. }
  94770. var childImpostor = mesh.getPhysicsImpostor();
  94771. if (childImpostor) {
  94772. var parent = childImpostor.parent;
  94773. if (parent !== mainImpostor) {
  94774. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  94775. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  94776. if (childImpostor.physicsBody) {
  94777. _this.removePhysicsBody(childImpostor);
  94778. childImpostor.physicsBody = null;
  94779. }
  94780. childImpostor.parent = mainImpostor;
  94781. childImpostor.resetUpdateFlags();
  94782. 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));
  94783. //Add the mass of the children.
  94784. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  94785. }
  94786. }
  94787. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  94788. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  94789. };
  94790. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  94791. }
  94792. };
  94793. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  94794. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  94795. this.world.removeEventListener("preStep", impostor.beforeStep);
  94796. this.world.removeEventListener("postStep", impostor.afterStep);
  94797. this.world.remove(impostor.physicsBody);
  94798. };
  94799. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  94800. var mainBody = impostorJoint.mainImpostor.physicsBody;
  94801. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  94802. if (!mainBody || !connectedBody) {
  94803. return;
  94804. }
  94805. var constraint;
  94806. var jointData = impostorJoint.joint.jointData;
  94807. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  94808. var constraintData = {
  94809. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  94810. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  94811. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  94812. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  94813. maxForce: jointData.nativeParams.maxForce,
  94814. collideConnected: !!jointData.collision
  94815. };
  94816. switch (impostorJoint.joint.type) {
  94817. case BABYLON.PhysicsJoint.HingeJoint:
  94818. case BABYLON.PhysicsJoint.Hinge2Joint:
  94819. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  94820. break;
  94821. case BABYLON.PhysicsJoint.DistanceJoint:
  94822. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  94823. break;
  94824. case BABYLON.PhysicsJoint.SpringJoint:
  94825. var springData = jointData;
  94826. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  94827. restLength: springData.length,
  94828. stiffness: springData.stiffness,
  94829. damping: springData.damping,
  94830. localAnchorA: constraintData.pivotA,
  94831. localAnchorB: constraintData.pivotB
  94832. });
  94833. break;
  94834. case BABYLON.PhysicsJoint.LockJoint:
  94835. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  94836. break;
  94837. case BABYLON.PhysicsJoint.PointToPointJoint:
  94838. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  94839. default:
  94840. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  94841. break;
  94842. }
  94843. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  94844. constraint.collideConnected = !!jointData.collision;
  94845. impostorJoint.joint.physicsJoint = constraint;
  94846. //don't add spring as constraint, as it is not one.
  94847. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  94848. this.world.addConstraint(constraint);
  94849. }
  94850. else {
  94851. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  94852. constraint.applyForce();
  94853. };
  94854. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  94855. }
  94856. };
  94857. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  94858. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  94859. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  94860. }
  94861. else {
  94862. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  94863. }
  94864. };
  94865. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  94866. var index;
  94867. var mat;
  94868. for (index = 0; index < this._physicsMaterials.length; index++) {
  94869. mat = this._physicsMaterials[index];
  94870. if (mat.friction === friction && mat.restitution === restitution) {
  94871. return mat;
  94872. }
  94873. }
  94874. var currentMat = new this.BJSCANNON.Material(name);
  94875. currentMat.friction = friction;
  94876. currentMat.restitution = restitution;
  94877. this._physicsMaterials.push(currentMat);
  94878. return currentMat;
  94879. };
  94880. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  94881. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  94882. };
  94883. CannonJSPlugin.prototype._createShape = function (impostor) {
  94884. var object = impostor.object;
  94885. var returnValue;
  94886. var extendSize = impostor.getObjectExtendSize();
  94887. switch (impostor.type) {
  94888. case BABYLON.PhysicsImpostor.SphereImpostor:
  94889. var radiusX = extendSize.x;
  94890. var radiusY = extendSize.y;
  94891. var radiusZ = extendSize.z;
  94892. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  94893. break;
  94894. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  94895. case BABYLON.PhysicsImpostor.CylinderImpostor:
  94896. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  94897. break;
  94898. case BABYLON.PhysicsImpostor.BoxImpostor:
  94899. var box = extendSize.scale(0.5);
  94900. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  94901. break;
  94902. case BABYLON.PhysicsImpostor.PlaneImpostor:
  94903. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  94904. returnValue = new this.BJSCANNON.Plane();
  94905. break;
  94906. case BABYLON.PhysicsImpostor.MeshImpostor:
  94907. // should transform the vertex data to world coordinates!!
  94908. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  94909. var rawFaces = object.getIndices ? object.getIndices() : [];
  94910. if (!rawVerts)
  94911. return;
  94912. // get only scale! so the object could transform correctly.
  94913. var oldPosition = object.position.clone();
  94914. var oldRotation = object.rotation && object.rotation.clone();
  94915. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  94916. object.position.copyFromFloats(0, 0, 0);
  94917. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  94918. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  94919. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  94920. var transform = object.computeWorldMatrix(true);
  94921. // convert rawVerts to object space
  94922. var temp = new Array();
  94923. var index;
  94924. for (index = 0; index < rawVerts.length; index += 3) {
  94925. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  94926. }
  94927. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  94928. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  94929. //now set back the transformation!
  94930. object.position.copyFrom(oldPosition);
  94931. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  94932. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  94933. break;
  94934. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  94935. var oldPosition2 = object.position.clone();
  94936. var oldRotation2 = object.rotation && object.rotation.clone();
  94937. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  94938. object.position.copyFromFloats(0, 0, 0);
  94939. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  94940. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  94941. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  94942. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  94943. returnValue = this._createHeightmap(object);
  94944. object.position.copyFrom(oldPosition2);
  94945. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  94946. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  94947. object.computeWorldMatrix(true);
  94948. break;
  94949. case BABYLON.PhysicsImpostor.ParticleImpostor:
  94950. returnValue = new this.BJSCANNON.Particle();
  94951. break;
  94952. }
  94953. return returnValue;
  94954. };
  94955. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  94956. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  94957. var transform = object.computeWorldMatrix(true);
  94958. // convert rawVerts to object space
  94959. var temp = new Array();
  94960. var index;
  94961. for (index = 0; index < pos.length; index += 3) {
  94962. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  94963. }
  94964. pos = temp;
  94965. var matrix = new Array();
  94966. //For now pointDepth will not be used and will be automatically calculated.
  94967. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  94968. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  94969. var boundingInfo = object.getBoundingInfo();
  94970. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  94971. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  94972. var elementSize = dim * 2 / arraySize;
  94973. for (var i = 0; i < pos.length; i = i + 3) {
  94974. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  94975. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  94976. var y = -pos[i + 2] + minY;
  94977. if (!matrix[x]) {
  94978. matrix[x] = [];
  94979. }
  94980. if (!matrix[x][z]) {
  94981. matrix[x][z] = y;
  94982. }
  94983. matrix[x][z] = Math.max(y, matrix[x][z]);
  94984. }
  94985. for (var x = 0; x <= arraySize; ++x) {
  94986. if (!matrix[x]) {
  94987. var loc = 1;
  94988. while (!matrix[(x + loc) % arraySize]) {
  94989. loc++;
  94990. }
  94991. matrix[x] = matrix[(x + loc) % arraySize].slice();
  94992. //console.log("missing x", x);
  94993. }
  94994. for (var z = 0; z <= arraySize; ++z) {
  94995. if (!matrix[x][z]) {
  94996. var loc = 1;
  94997. var newValue;
  94998. while (newValue === undefined) {
  94999. newValue = matrix[x][(z + loc++) % arraySize];
  95000. }
  95001. matrix[x][z] = newValue;
  95002. }
  95003. }
  95004. }
  95005. var shape = new this.BJSCANNON.Heightfield(matrix, {
  95006. elementSize: elementSize
  95007. });
  95008. //For future reference, needed for body transformation
  95009. shape.minY = minY;
  95010. return shape;
  95011. };
  95012. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  95013. var object = impostor.object;
  95014. //make sure it is updated...
  95015. object.computeWorldMatrix && object.computeWorldMatrix(true);
  95016. // The delta between the mesh position and the mesh bounding box center
  95017. var bInfo = object.getBoundingInfo();
  95018. if (!bInfo)
  95019. return;
  95020. var center = impostor.getObjectCenter();
  95021. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  95022. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  95023. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  95024. this._tmpPosition.copyFrom(center);
  95025. var quaternion = object.rotationQuaternion;
  95026. if (!quaternion) {
  95027. return;
  95028. }
  95029. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  95030. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  95031. //-90 DEG in X, precalculated
  95032. quaternion = quaternion.multiply(this._minus90X);
  95033. //Invert! (Precalculated, 90 deg in X)
  95034. //No need to clone. this will never change.
  95035. impostor.setDeltaRotation(this._plus90X);
  95036. }
  95037. //If it is a heightfield, if should be centered.
  95038. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  95039. var mesh = object;
  95040. var boundingInfo = mesh.getBoundingInfo();
  95041. //calculate the correct body position:
  95042. var rotationQuaternion = mesh.rotationQuaternion;
  95043. mesh.rotationQuaternion = this._tmpUnityRotation;
  95044. mesh.computeWorldMatrix(true);
  95045. //get original center with no rotation
  95046. var c = center.clone();
  95047. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  95048. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  95049. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  95050. mesh.setPreTransformMatrix(p);
  95051. mesh.computeWorldMatrix(true);
  95052. //calculate the translation
  95053. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  95054. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  95055. //add it inverted to the delta
  95056. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  95057. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  95058. //rotation is back
  95059. mesh.rotationQuaternion = rotationQuaternion;
  95060. mesh.setPreTransformMatrix(oldPivot);
  95061. mesh.computeWorldMatrix(true);
  95062. }
  95063. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  95064. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  95065. //this._tmpPosition.copyFrom(object.position);
  95066. }
  95067. impostor.setDeltaPosition(this._tmpDeltaPosition);
  95068. //Now update the impostor object
  95069. impostor.physicsBody.position.copy(this._tmpPosition);
  95070. impostor.physicsBody.quaternion.copy(quaternion);
  95071. };
  95072. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  95073. impostor.object.position.copyFrom(impostor.physicsBody.position);
  95074. if (impostor.object.rotationQuaternion) {
  95075. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  95076. }
  95077. };
  95078. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  95079. impostor.physicsBody.position.copy(newPosition);
  95080. impostor.physicsBody.quaternion.copy(newRotation);
  95081. };
  95082. CannonJSPlugin.prototype.isSupported = function () {
  95083. return this.BJSCANNON !== undefined;
  95084. };
  95085. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  95086. impostor.physicsBody.velocity.copy(velocity);
  95087. };
  95088. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  95089. impostor.physicsBody.angularVelocity.copy(velocity);
  95090. };
  95091. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  95092. var v = impostor.physicsBody.velocity;
  95093. if (!v) {
  95094. return null;
  95095. }
  95096. return new BABYLON.Vector3(v.x, v.y, v.z);
  95097. };
  95098. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  95099. var v = impostor.physicsBody.angularVelocity;
  95100. if (!v) {
  95101. return null;
  95102. }
  95103. return new BABYLON.Vector3(v.x, v.y, v.z);
  95104. };
  95105. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  95106. impostor.physicsBody.mass = mass;
  95107. impostor.physicsBody.updateMassProperties();
  95108. };
  95109. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  95110. return impostor.physicsBody.mass;
  95111. };
  95112. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  95113. return impostor.physicsBody.material.friction;
  95114. };
  95115. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  95116. impostor.physicsBody.material.friction = friction;
  95117. };
  95118. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  95119. return impostor.physicsBody.material.restitution;
  95120. };
  95121. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  95122. impostor.physicsBody.material.restitution = restitution;
  95123. };
  95124. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  95125. impostor.physicsBody.sleep();
  95126. };
  95127. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  95128. impostor.physicsBody.wakeUp();
  95129. };
  95130. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  95131. joint.physicsJoint.distance = maxDistance;
  95132. };
  95133. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  95134. // if (!motorIndex) {
  95135. // joint.physicsJoint.enableMotor();
  95136. // }
  95137. // }
  95138. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  95139. // if (!motorIndex) {
  95140. // joint.physicsJoint.disableMotor();
  95141. // }
  95142. // }
  95143. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  95144. if (!motorIndex) {
  95145. joint.physicsJoint.enableMotor();
  95146. joint.physicsJoint.setMotorSpeed(speed);
  95147. if (maxForce) {
  95148. this.setLimit(joint, maxForce);
  95149. }
  95150. }
  95151. };
  95152. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  95153. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  95154. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  95155. };
  95156. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  95157. var body = impostor.physicsBody;
  95158. mesh.position.x = body.position.x;
  95159. mesh.position.y = body.position.y;
  95160. mesh.position.z = body.position.z;
  95161. if (mesh.rotationQuaternion) {
  95162. mesh.rotationQuaternion.x = body.quaternion.x;
  95163. mesh.rotationQuaternion.y = body.quaternion.y;
  95164. mesh.rotationQuaternion.z = body.quaternion.z;
  95165. mesh.rotationQuaternion.w = body.quaternion.w;
  95166. }
  95167. };
  95168. CannonJSPlugin.prototype.getRadius = function (impostor) {
  95169. var shape = impostor.physicsBody.shapes[0];
  95170. return shape.boundingSphereRadius;
  95171. };
  95172. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  95173. var shape = impostor.physicsBody.shapes[0];
  95174. result.x = shape.halfExtents.x * 2;
  95175. result.y = shape.halfExtents.y * 2;
  95176. result.z = shape.halfExtents.z * 2;
  95177. };
  95178. CannonJSPlugin.prototype.dispose = function () {
  95179. };
  95180. CannonJSPlugin.prototype._extendNamespace = function () {
  95181. //this will force cannon to execute at least one step when using interpolation
  95182. var step_tmp1 = new this.BJSCANNON.Vec3();
  95183. var Engine = this.BJSCANNON;
  95184. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  95185. maxSubSteps = maxSubSteps || 10;
  95186. timeSinceLastCalled = timeSinceLastCalled || 0;
  95187. if (timeSinceLastCalled === 0) {
  95188. this.internalStep(dt);
  95189. this.time += dt;
  95190. }
  95191. else {
  95192. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  95193. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  95194. var t0 = performance.now();
  95195. for (var i = 0; i !== internalSteps; i++) {
  95196. this.internalStep(dt);
  95197. if (performance.now() - t0 > dt * 1000) {
  95198. break;
  95199. }
  95200. }
  95201. this.time += timeSinceLastCalled;
  95202. var h = this.time % dt;
  95203. var h_div_dt = h / dt;
  95204. var interpvelo = step_tmp1;
  95205. var bodies = this.bodies;
  95206. for (var j = 0; j !== bodies.length; j++) {
  95207. var b = bodies[j];
  95208. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  95209. b.position.vsub(b.previousPosition, interpvelo);
  95210. interpvelo.scale(h_div_dt, interpvelo);
  95211. b.position.vadd(interpvelo, b.interpolatedPosition);
  95212. }
  95213. else {
  95214. b.interpolatedPosition.copy(b.position);
  95215. b.interpolatedQuaternion.copy(b.quaternion);
  95216. }
  95217. }
  95218. }
  95219. };
  95220. };
  95221. return CannonJSPlugin;
  95222. }());
  95223. BABYLON.CannonJSPlugin = CannonJSPlugin;
  95224. })(BABYLON || (BABYLON = {}));
  95225. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  95226. var BABYLON;
  95227. (function (BABYLON) {
  95228. /** @hidden */
  95229. var OimoJSPlugin = /** @class */ (function () {
  95230. function OimoJSPlugin(iterations) {
  95231. this.name = "OimoJSPlugin";
  95232. this._tmpImpostorsArray = [];
  95233. this._tmpPositionVector = BABYLON.Vector3.Zero();
  95234. this.BJSOIMO = OIMO;
  95235. this.world = new this.BJSOIMO.World({
  95236. iterations: iterations
  95237. });
  95238. this.world.clear();
  95239. }
  95240. OimoJSPlugin.prototype.setGravity = function (gravity) {
  95241. this.world.gravity.copy(gravity);
  95242. };
  95243. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  95244. this.world.timeStep = timeStep;
  95245. };
  95246. OimoJSPlugin.prototype.getTimeStep = function () {
  95247. return this.world.timeStep;
  95248. };
  95249. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  95250. var _this = this;
  95251. impostors.forEach(function (impostor) {
  95252. impostor.beforeStep();
  95253. });
  95254. this.world.step();
  95255. impostors.forEach(function (impostor) {
  95256. impostor.afterStep();
  95257. //update the ordered impostors array
  95258. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  95259. });
  95260. //check for collisions
  95261. var contact = this.world.contacts;
  95262. while (contact !== null) {
  95263. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  95264. contact = contact.next;
  95265. continue;
  95266. }
  95267. //is this body colliding with any other? get the impostor
  95268. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  95269. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  95270. if (!mainImpostor || !collidingImpostor) {
  95271. contact = contact.next;
  95272. continue;
  95273. }
  95274. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  95275. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  95276. contact = contact.next;
  95277. }
  95278. };
  95279. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  95280. var mass = impostor.physicsBody.mass;
  95281. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  95282. };
  95283. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  95284. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  95285. this.applyImpulse(impostor, force, contactPoint);
  95286. };
  95287. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  95288. var _this = this;
  95289. //parent-child relationship. Does this impostor has a parent impostor?
  95290. if (impostor.parent) {
  95291. if (impostor.physicsBody) {
  95292. this.removePhysicsBody(impostor);
  95293. //TODO is that needed?
  95294. impostor.forceUpdate();
  95295. }
  95296. return;
  95297. }
  95298. if (impostor.isBodyInitRequired()) {
  95299. var bodyConfig = {
  95300. name: impostor.uniqueId,
  95301. //Oimo must have mass, also for static objects.
  95302. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  95303. size: [],
  95304. type: [],
  95305. pos: [],
  95306. posShape: [],
  95307. rot: [],
  95308. rotShape: [],
  95309. move: impostor.getParam("mass") !== 0,
  95310. density: impostor.getParam("mass"),
  95311. friction: impostor.getParam("friction"),
  95312. restitution: impostor.getParam("restitution"),
  95313. //Supporting older versions of Oimo
  95314. world: this.world
  95315. };
  95316. var impostors = [impostor];
  95317. var addToArray = function (parent) {
  95318. if (!parent.getChildMeshes)
  95319. return;
  95320. parent.getChildMeshes().forEach(function (m) {
  95321. if (m.physicsImpostor) {
  95322. impostors.push(m.physicsImpostor);
  95323. //m.physicsImpostor._init();
  95324. }
  95325. });
  95326. };
  95327. addToArray(impostor.object);
  95328. var checkWithEpsilon_1 = function (value) {
  95329. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  95330. };
  95331. var globalQuaternion_1 = new BABYLON.Quaternion();
  95332. impostors.forEach(function (i) {
  95333. if (!i.object.rotationQuaternion) {
  95334. return;
  95335. }
  95336. //get the correct bounding box
  95337. var oldQuaternion = i.object.rotationQuaternion;
  95338. globalQuaternion_1 = oldQuaternion.clone();
  95339. var rot = oldQuaternion.toEulerAngles();
  95340. var extendSize = i.getObjectExtendSize();
  95341. var radToDeg = 57.295779513082320876;
  95342. if (i === impostor) {
  95343. var center = impostor.getObjectCenter();
  95344. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  95345. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  95346. //Can also use Array.prototype.push.apply
  95347. bodyConfig.pos.push(center.x);
  95348. bodyConfig.pos.push(center.y);
  95349. bodyConfig.pos.push(center.z);
  95350. bodyConfig.posShape.push(0, 0, 0);
  95351. //tmp solution
  95352. bodyConfig.rot.push(0);
  95353. bodyConfig.rot.push(0);
  95354. bodyConfig.rot.push(0);
  95355. bodyConfig.rotShape.push(0, 0, 0);
  95356. }
  95357. else {
  95358. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  95359. bodyConfig.posShape.push(localPosition.x);
  95360. bodyConfig.posShape.push(localPosition.y);
  95361. bodyConfig.posShape.push(localPosition.z);
  95362. bodyConfig.pos.push(0, 0, 0);
  95363. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  95364. bodyConfig.rot.push(0);
  95365. bodyConfig.rot.push(0);
  95366. bodyConfig.rot.push(0);
  95367. bodyConfig.rotShape.push(rot.x * radToDeg);
  95368. bodyConfig.rotShape.push(rot.y * radToDeg);
  95369. bodyConfig.rotShape.push(rot.z * radToDeg);
  95370. }
  95371. // register mesh
  95372. switch (i.type) {
  95373. case BABYLON.PhysicsImpostor.ParticleImpostor:
  95374. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  95375. case BABYLON.PhysicsImpostor.SphereImpostor:
  95376. var radiusX = extendSize.x;
  95377. var radiusY = extendSize.y;
  95378. var radiusZ = extendSize.z;
  95379. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  95380. bodyConfig.type.push('sphere');
  95381. //due to the way oimo works with compounds, add 3 times
  95382. bodyConfig.size.push(size);
  95383. bodyConfig.size.push(size);
  95384. bodyConfig.size.push(size);
  95385. break;
  95386. case BABYLON.PhysicsImpostor.CylinderImpostor:
  95387. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  95388. var sizeY = checkWithEpsilon_1(extendSize.y);
  95389. bodyConfig.type.push('cylinder');
  95390. bodyConfig.size.push(sizeX);
  95391. bodyConfig.size.push(sizeY);
  95392. //due to the way oimo works with compounds, add one more value.
  95393. bodyConfig.size.push(sizeY);
  95394. break;
  95395. case BABYLON.PhysicsImpostor.PlaneImpostor:
  95396. case BABYLON.PhysicsImpostor.BoxImpostor:
  95397. default:
  95398. var sizeX = checkWithEpsilon_1(extendSize.x);
  95399. var sizeY = checkWithEpsilon_1(extendSize.y);
  95400. var sizeZ = checkWithEpsilon_1(extendSize.z);
  95401. bodyConfig.type.push('box');
  95402. //if (i === impostor) {
  95403. bodyConfig.size.push(sizeX);
  95404. bodyConfig.size.push(sizeY);
  95405. bodyConfig.size.push(sizeZ);
  95406. //} else {
  95407. // bodyConfig.size.push(0,0,0);
  95408. //}
  95409. break;
  95410. }
  95411. //actually not needed, but hey...
  95412. i.object.rotationQuaternion = oldQuaternion;
  95413. });
  95414. impostor.physicsBody = this.world.add(bodyConfig);
  95415. // set the quaternion, ignoring the previously defined (euler) rotation
  95416. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  95417. // update with delta 0, so the body will reveive the new rotation.
  95418. impostor.physicsBody.updatePosition(0);
  95419. }
  95420. else {
  95421. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  95422. }
  95423. impostor.setDeltaPosition(this._tmpPositionVector);
  95424. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  95425. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  95426. };
  95427. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  95428. //impostor.physicsBody.dispose();
  95429. //Same as : (older oimo versions)
  95430. this.world.removeRigidBody(impostor.physicsBody);
  95431. };
  95432. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  95433. var mainBody = impostorJoint.mainImpostor.physicsBody;
  95434. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  95435. if (!mainBody || !connectedBody) {
  95436. return;
  95437. }
  95438. var jointData = impostorJoint.joint.jointData;
  95439. var options = jointData.nativeParams || {};
  95440. var type;
  95441. var nativeJointData = {
  95442. body1: mainBody,
  95443. body2: connectedBody,
  95444. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  95445. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  95446. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  95447. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  95448. min: options.min,
  95449. max: options.max,
  95450. collision: options.collision || jointData.collision,
  95451. spring: options.spring,
  95452. //supporting older version of Oimo
  95453. world: this.world
  95454. };
  95455. switch (impostorJoint.joint.type) {
  95456. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  95457. type = "jointBall";
  95458. break;
  95459. case BABYLON.PhysicsJoint.SpringJoint:
  95460. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  95461. var springData = jointData;
  95462. nativeJointData.min = springData.length || nativeJointData.min;
  95463. //Max should also be set, just make sure it is at least min
  95464. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  95465. case BABYLON.PhysicsJoint.DistanceJoint:
  95466. type = "jointDistance";
  95467. nativeJointData.max = jointData.maxDistance;
  95468. break;
  95469. case BABYLON.PhysicsJoint.PrismaticJoint:
  95470. type = "jointPrisme";
  95471. break;
  95472. case BABYLON.PhysicsJoint.SliderJoint:
  95473. type = "jointSlide";
  95474. break;
  95475. case BABYLON.PhysicsJoint.WheelJoint:
  95476. type = "jointWheel";
  95477. break;
  95478. case BABYLON.PhysicsJoint.HingeJoint:
  95479. default:
  95480. type = "jointHinge";
  95481. break;
  95482. }
  95483. nativeJointData.type = type;
  95484. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  95485. };
  95486. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  95487. //Bug in Oimo prevents us from disposing a joint in the playground
  95488. //joint.joint.physicsJoint.dispose();
  95489. //So we will bruteforce it!
  95490. try {
  95491. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  95492. }
  95493. catch (e) {
  95494. BABYLON.Tools.Warn(e);
  95495. }
  95496. };
  95497. OimoJSPlugin.prototype.isSupported = function () {
  95498. return this.BJSOIMO !== undefined;
  95499. };
  95500. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  95501. if (!impostor.physicsBody.sleeping) {
  95502. //TODO check that
  95503. /*if (impostor.physicsBody.shapes.next) {
  95504. var parentShape = this._getLastShape(impostor.physicsBody);
  95505. impostor.object.position.copyFrom(parentShape.position);
  95506. console.log(parentShape.position);
  95507. } else {*/
  95508. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  95509. //}
  95510. if (impostor.object.rotationQuaternion) {
  95511. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  95512. }
  95513. }
  95514. };
  95515. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  95516. var body = impostor.physicsBody;
  95517. body.position.copy(newPosition);
  95518. body.orientation.copy(newRotation);
  95519. body.syncShapes();
  95520. body.awake();
  95521. };
  95522. /*private _getLastShape(body: any): any {
  95523. var lastShape = body.shapes;
  95524. while (lastShape.next) {
  95525. lastShape = lastShape.next;
  95526. }
  95527. return lastShape;
  95528. }*/
  95529. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  95530. impostor.physicsBody.linearVelocity.copy(velocity);
  95531. };
  95532. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  95533. impostor.physicsBody.angularVelocity.copy(velocity);
  95534. };
  95535. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  95536. var v = impostor.physicsBody.linearVelocity;
  95537. if (!v) {
  95538. return null;
  95539. }
  95540. return new BABYLON.Vector3(v.x, v.y, v.z);
  95541. };
  95542. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  95543. var v = impostor.physicsBody.angularVelocity;
  95544. if (!v) {
  95545. return null;
  95546. }
  95547. return new BABYLON.Vector3(v.x, v.y, v.z);
  95548. };
  95549. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  95550. var staticBody = mass === 0;
  95551. //this will actually set the body's density and not its mass.
  95552. //But this is how oimo treats the mass variable.
  95553. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  95554. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  95555. };
  95556. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  95557. return impostor.physicsBody.shapes.density;
  95558. };
  95559. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  95560. return impostor.physicsBody.shapes.friction;
  95561. };
  95562. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  95563. impostor.physicsBody.shapes.friction = friction;
  95564. };
  95565. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  95566. return impostor.physicsBody.shapes.restitution;
  95567. };
  95568. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  95569. impostor.physicsBody.shapes.restitution = restitution;
  95570. };
  95571. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  95572. impostor.physicsBody.sleep();
  95573. };
  95574. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  95575. impostor.physicsBody.awake();
  95576. };
  95577. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  95578. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  95579. if (minDistance !== void 0) {
  95580. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  95581. }
  95582. };
  95583. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  95584. //TODO separate rotational and transational motors.
  95585. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  95586. if (motor) {
  95587. motor.setMotor(speed, maxForce);
  95588. }
  95589. };
  95590. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  95591. //TODO separate rotational and transational motors.
  95592. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  95593. if (motor) {
  95594. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  95595. }
  95596. };
  95597. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  95598. var body = impostor.physicsBody;
  95599. mesh.position.x = body.position.x;
  95600. mesh.position.y = body.position.y;
  95601. mesh.position.z = body.position.z;
  95602. if (mesh.rotationQuaternion) {
  95603. mesh.rotationQuaternion.x = body.orientation.x;
  95604. mesh.rotationQuaternion.y = body.orientation.y;
  95605. mesh.rotationQuaternion.z = body.orientation.z;
  95606. mesh.rotationQuaternion.w = body.orientation.s;
  95607. }
  95608. };
  95609. OimoJSPlugin.prototype.getRadius = function (impostor) {
  95610. return impostor.physicsBody.shapes.radius;
  95611. };
  95612. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  95613. var shape = impostor.physicsBody.shapes;
  95614. result.x = shape.halfWidth * 2;
  95615. result.y = shape.halfHeight * 2;
  95616. result.z = shape.halfDepth * 2;
  95617. };
  95618. OimoJSPlugin.prototype.dispose = function () {
  95619. this.world.clear();
  95620. };
  95621. return OimoJSPlugin;
  95622. }());
  95623. BABYLON.OimoJSPlugin = OimoJSPlugin;
  95624. })(BABYLON || (BABYLON = {}));
  95625. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  95626. var BABYLON;
  95627. (function (BABYLON) {
  95628. /**
  95629. * Gets the current physics engine
  95630. * @returns a IPhysicsEngine or null if none attached
  95631. */
  95632. BABYLON.Scene.prototype.getPhysicsEngine = function () {
  95633. return this._physicsEngine;
  95634. };
  95635. /**
  95636. * Enables physics to the current scene
  95637. * @param gravity defines the scene's gravity for the physics engine
  95638. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  95639. * @return a boolean indicating if the physics engine was initialized
  95640. */
  95641. BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
  95642. if (gravity === void 0) { gravity = null; }
  95643. if (this._physicsEngine) {
  95644. return true;
  95645. }
  95646. // Register the component to the scene
  95647. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
  95648. if (!component) {
  95649. component = new PhysicsEngineSceneComponent(this);
  95650. this._addComponent(component);
  95651. }
  95652. try {
  95653. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  95654. return true;
  95655. }
  95656. catch (e) {
  95657. BABYLON.Tools.Error(e.message);
  95658. return false;
  95659. }
  95660. };
  95661. /**
  95662. * Disables and disposes the physics engine associated with the scene
  95663. */
  95664. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  95665. if (!this._physicsEngine) {
  95666. return;
  95667. }
  95668. this._physicsEngine.dispose();
  95669. this._physicsEngine = null;
  95670. };
  95671. /**
  95672. * Gets a boolean indicating if there is an active physics engine
  95673. * @returns a boolean indicating if there is an active physics engine
  95674. */
  95675. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  95676. return this._physicsEngine !== undefined;
  95677. };
  95678. /**
  95679. * Deletes a physics compound impostor
  95680. * @param compound defines the compound to delete
  95681. */
  95682. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  95683. var mesh = compound.parts[0].mesh;
  95684. if (mesh.physicsImpostor) {
  95685. mesh.physicsImpostor.dispose( /*true*/);
  95686. mesh.physicsImpostor = null;
  95687. }
  95688. };
  95689. /** @hidden */
  95690. BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
  95691. if (this._physicsEngine) {
  95692. this.onBeforePhysicsObservable.notifyObservers(this);
  95693. this._physicsEngine._step(step / 1000);
  95694. this.onAfterPhysicsObservable.notifyObservers(this);
  95695. }
  95696. };
  95697. Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
  95698. get: function () {
  95699. return this._physicsImpostor;
  95700. },
  95701. set: function (value) {
  95702. var _this = this;
  95703. if (this._physicsImpostor === value) {
  95704. return;
  95705. }
  95706. if (this._disposePhysicsObserver) {
  95707. this.onDisposeObservable.remove(this._disposePhysicsObserver);
  95708. }
  95709. this._physicsImpostor = value;
  95710. if (value) {
  95711. this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
  95712. // Physics
  95713. if (_this.physicsImpostor) {
  95714. _this.physicsImpostor.dispose( /*!doNotRecurse*/);
  95715. _this.physicsImpostor = null;
  95716. }
  95717. });
  95718. }
  95719. },
  95720. enumerable: true,
  95721. configurable: true
  95722. });
  95723. /**
  95724. * Gets the current physics impostor
  95725. * @see http://doc.babylonjs.com/features/physics_engine
  95726. * @returns a physics impostor or null
  95727. */
  95728. BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
  95729. return this.physicsImpostor;
  95730. };
  95731. /**
  95732. * Apply a physic impulse to the mesh
  95733. * @param force defines the force to apply
  95734. * @param contactPoint defines where to apply the force
  95735. * @returns the current mesh
  95736. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  95737. */
  95738. BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  95739. if (!this.physicsImpostor) {
  95740. return this;
  95741. }
  95742. this.physicsImpostor.applyImpulse(force, contactPoint);
  95743. return this;
  95744. };
  95745. /**
  95746. * Creates a physic joint between two meshes
  95747. * @param otherMesh defines the other mesh to use
  95748. * @param pivot1 defines the pivot to use on this mesh
  95749. * @param pivot2 defines the pivot to use on the other mesh
  95750. * @param options defines additional options (can be plugin dependent)
  95751. * @returns the current mesh
  95752. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  95753. */
  95754. BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  95755. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  95756. return this;
  95757. }
  95758. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  95759. mainPivot: pivot1,
  95760. connectedPivot: pivot2,
  95761. nativeParams: options
  95762. });
  95763. return this;
  95764. };
  95765. /**
  95766. * Defines the physics engine scene component responsible to manage a physics engine
  95767. */
  95768. var PhysicsEngineSceneComponent = /** @class */ (function () {
  95769. /**
  95770. * Creates a new instance of the component for the given scene
  95771. * @param scene Defines the scene to register the component in
  95772. */
  95773. function PhysicsEngineSceneComponent(scene) {
  95774. var _this = this;
  95775. /**
  95776. * The component name helpful to identify the component in the list of scene components.
  95777. */
  95778. this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
  95779. this.scene = scene;
  95780. this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
  95781. this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
  95782. // Replace the function used to get the deterministic frame time
  95783. this.scene.getDeterministicFrameTime = function () {
  95784. if (_this.scene._physicsEngine) {
  95785. return _this.scene._physicsEngine.getTimeStep() * 1000;
  95786. }
  95787. return 1000.0 / 60.0;
  95788. };
  95789. }
  95790. /**
  95791. * Registers the component in a given scene
  95792. */
  95793. PhysicsEngineSceneComponent.prototype.register = function () {
  95794. };
  95795. /**
  95796. * Rebuilds the elements related to this component in case of
  95797. * context lost for instance.
  95798. */
  95799. PhysicsEngineSceneComponent.prototype.rebuild = function () {
  95800. // Nothing to do for this component
  95801. };
  95802. /**
  95803. * Disposes the component and the associated ressources
  95804. */
  95805. PhysicsEngineSceneComponent.prototype.dispose = function () {
  95806. this.scene.onBeforePhysicsObservable.clear();
  95807. this.scene.onAfterPhysicsObservable.clear();
  95808. if (this.scene._physicsEngine) {
  95809. this.scene.disablePhysicsEngine();
  95810. }
  95811. };
  95812. return PhysicsEngineSceneComponent;
  95813. }());
  95814. BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
  95815. })(BABYLON || (BABYLON = {}));
  95816. //# sourceMappingURL=babylon.physicsEngineComponent.js.map
  95817. var BABYLON;
  95818. (function (BABYLON) {
  95819. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  95820. // All values and structures referenced from:
  95821. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  95822. var DDS_MAGIC = 0x20534444;
  95823. var
  95824. //DDSD_CAPS = 0x1,
  95825. //DDSD_HEIGHT = 0x2,
  95826. //DDSD_WIDTH = 0x4,
  95827. //DDSD_PITCH = 0x8,
  95828. //DDSD_PIXELFORMAT = 0x1000,
  95829. DDSD_MIPMAPCOUNT = 0x20000;
  95830. //DDSD_LINEARSIZE = 0x80000,
  95831. //DDSD_DEPTH = 0x800000;
  95832. // var DDSCAPS_COMPLEX = 0x8,
  95833. // DDSCAPS_MIPMAP = 0x400000,
  95834. // DDSCAPS_TEXTURE = 0x1000;
  95835. var DDSCAPS2_CUBEMAP = 0x200;
  95836. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  95837. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  95838. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  95839. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  95840. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  95841. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  95842. // DDSCAPS2_VOLUME = 0x200000;
  95843. var
  95844. //DDPF_ALPHAPIXELS = 0x1,
  95845. //DDPF_ALPHA = 0x2,
  95846. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  95847. //DDPF_YUV = 0x200,
  95848. DDPF_LUMINANCE = 0x20000;
  95849. function FourCCToInt32(value) {
  95850. return value.charCodeAt(0) +
  95851. (value.charCodeAt(1) << 8) +
  95852. (value.charCodeAt(2) << 16) +
  95853. (value.charCodeAt(3) << 24);
  95854. }
  95855. function Int32ToFourCC(value) {
  95856. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  95857. }
  95858. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  95859. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  95860. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  95861. var FOURCC_DX10 = FourCCToInt32("DX10");
  95862. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  95863. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  95864. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  95865. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  95866. var headerLengthInt = 31; // The header length in 32 bit ints
  95867. // Offsets into the header array
  95868. var off_magic = 0;
  95869. var off_size = 1;
  95870. var off_flags = 2;
  95871. var off_height = 3;
  95872. var off_width = 4;
  95873. var off_mipmapCount = 7;
  95874. var off_pfFlags = 20;
  95875. var off_pfFourCC = 21;
  95876. var off_RGBbpp = 22;
  95877. var off_RMask = 23;
  95878. var off_GMask = 24;
  95879. var off_BMask = 25;
  95880. var off_AMask = 26;
  95881. // var off_caps1 = 27;
  95882. var off_caps2 = 28;
  95883. // var off_caps3 = 29;
  95884. // var off_caps4 = 30;
  95885. var off_dxgiFormat = 32;
  95886. ;
  95887. /**
  95888. * Class used to provide DDS decompression tools
  95889. */
  95890. var DDSTools = /** @class */ (function () {
  95891. function DDSTools() {
  95892. }
  95893. /**
  95894. * Gets DDS information from an array buffer
  95895. * @param arrayBuffer defines the array buffer to read data from
  95896. * @returns the DDS information
  95897. */
  95898. DDSTools.GetDDSInfo = function (arrayBuffer) {
  95899. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  95900. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  95901. var mipmapCount = 1;
  95902. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  95903. mipmapCount = Math.max(1, header[off_mipmapCount]);
  95904. }
  95905. var fourCC = header[off_pfFourCC];
  95906. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  95907. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95908. switch (fourCC) {
  95909. case FOURCC_D3DFMT_R16G16B16A16F:
  95910. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  95911. break;
  95912. case FOURCC_D3DFMT_R32G32B32A32F:
  95913. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  95914. break;
  95915. case FOURCC_DX10:
  95916. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  95917. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  95918. break;
  95919. }
  95920. }
  95921. return {
  95922. width: header[off_width],
  95923. height: header[off_height],
  95924. mipmapCount: mipmapCount,
  95925. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  95926. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  95927. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  95928. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  95929. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  95930. dxgiFormat: dxgiFormat,
  95931. textureType: textureType
  95932. };
  95933. };
  95934. DDSTools._ToHalfFloat = function (value) {
  95935. if (!DDSTools._FloatView) {
  95936. DDSTools._FloatView = new Float32Array(1);
  95937. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  95938. }
  95939. DDSTools._FloatView[0] = value;
  95940. var x = DDSTools._Int32View[0];
  95941. var bits = (x >> 16) & 0x8000; /* Get the sign */
  95942. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  95943. var e = (x >> 23) & 0xff; /* Using int is faster here */
  95944. /* If zero, or denormal, or exponent underflows too much for a denormal
  95945. * half, return signed zero. */
  95946. if (e < 103) {
  95947. return bits;
  95948. }
  95949. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  95950. if (e > 142) {
  95951. bits |= 0x7c00;
  95952. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  95953. * not Inf, so make sure we set one mantissa bit too. */
  95954. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  95955. return bits;
  95956. }
  95957. /* If exponent underflows but not too much, return a denormal */
  95958. if (e < 113) {
  95959. m |= 0x0800;
  95960. /* Extra rounding may overflow and set mantissa to 0 and exponent
  95961. * to 1, which is OK. */
  95962. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  95963. return bits;
  95964. }
  95965. bits |= ((e - 112) << 10) | (m >> 1);
  95966. bits += m & 1;
  95967. return bits;
  95968. };
  95969. DDSTools._FromHalfFloat = function (value) {
  95970. var s = (value & 0x8000) >> 15;
  95971. var e = (value & 0x7C00) >> 10;
  95972. var f = value & 0x03FF;
  95973. if (e === 0) {
  95974. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  95975. }
  95976. else if (e == 0x1F) {
  95977. return f ? NaN : ((s ? -1 : 1) * Infinity);
  95978. }
  95979. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  95980. };
  95981. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  95982. var destArray = new Float32Array(dataLength);
  95983. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  95984. var index = 0;
  95985. for (var y = 0; y < height; y++) {
  95986. for (var x = 0; x < width; x++) {
  95987. var srcPos = (x + y * width) * 4;
  95988. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  95989. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  95990. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  95991. if (DDSTools.StoreLODInAlphaChannel) {
  95992. destArray[index + 3] = lod;
  95993. }
  95994. else {
  95995. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  95996. }
  95997. index += 4;
  95998. }
  95999. }
  96000. return destArray;
  96001. };
  96002. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  96003. if (DDSTools.StoreLODInAlphaChannel) {
  96004. var destArray = new Uint16Array(dataLength);
  96005. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  96006. var index = 0;
  96007. for (var y = 0; y < height; y++) {
  96008. for (var x = 0; x < width; x++) {
  96009. var srcPos = (x + y * width) * 4;
  96010. destArray[index] = srcData[srcPos];
  96011. destArray[index + 1] = srcData[srcPos + 1];
  96012. destArray[index + 2] = srcData[srcPos + 2];
  96013. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  96014. index += 4;
  96015. }
  96016. }
  96017. return destArray;
  96018. }
  96019. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  96020. };
  96021. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  96022. if (DDSTools.StoreLODInAlphaChannel) {
  96023. var destArray = new Float32Array(dataLength);
  96024. var srcData = new Float32Array(arrayBuffer, dataOffset);
  96025. var index = 0;
  96026. for (var y = 0; y < height; y++) {
  96027. for (var x = 0; x < width; x++) {
  96028. var srcPos = (x + y * width) * 4;
  96029. destArray[index] = srcData[srcPos];
  96030. destArray[index + 1] = srcData[srcPos + 1];
  96031. destArray[index + 2] = srcData[srcPos + 2];
  96032. destArray[index + 3] = lod;
  96033. index += 4;
  96034. }
  96035. }
  96036. return destArray;
  96037. }
  96038. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  96039. };
  96040. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  96041. var destArray = new Uint8Array(dataLength);
  96042. var srcData = new Float32Array(arrayBuffer, dataOffset);
  96043. var index = 0;
  96044. for (var y = 0; y < height; y++) {
  96045. for (var x = 0; x < width; x++) {
  96046. var srcPos = (x + y * width) * 4;
  96047. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  96048. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  96049. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  96050. if (DDSTools.StoreLODInAlphaChannel) {
  96051. destArray[index + 3] = lod;
  96052. }
  96053. else {
  96054. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  96055. }
  96056. index += 4;
  96057. }
  96058. }
  96059. return destArray;
  96060. };
  96061. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  96062. var destArray = new Uint8Array(dataLength);
  96063. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  96064. var index = 0;
  96065. for (var y = 0; y < height; y++) {
  96066. for (var x = 0; x < width; x++) {
  96067. var srcPos = (x + y * width) * 4;
  96068. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  96069. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  96070. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  96071. if (DDSTools.StoreLODInAlphaChannel) {
  96072. destArray[index + 3] = lod;
  96073. }
  96074. else {
  96075. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  96076. }
  96077. index += 4;
  96078. }
  96079. }
  96080. return destArray;
  96081. };
  96082. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  96083. var byteArray = new Uint8Array(dataLength);
  96084. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  96085. var index = 0;
  96086. for (var y = 0; y < height; y++) {
  96087. for (var x = 0; x < width; x++) {
  96088. var srcPos = (x + y * width) * 4;
  96089. byteArray[index] = srcData[srcPos + rOffset];
  96090. byteArray[index + 1] = srcData[srcPos + gOffset];
  96091. byteArray[index + 2] = srcData[srcPos + bOffset];
  96092. byteArray[index + 3] = srcData[srcPos + aOffset];
  96093. index += 4;
  96094. }
  96095. }
  96096. return byteArray;
  96097. };
  96098. DDSTools._ExtractLongWordOrder = function (value) {
  96099. if (value === 0 || value === 255 || value === -16777216) {
  96100. return 0;
  96101. }
  96102. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  96103. };
  96104. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  96105. var byteArray = new Uint8Array(dataLength);
  96106. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  96107. var index = 0;
  96108. for (var y = 0; y < height; y++) {
  96109. for (var x = 0; x < width; x++) {
  96110. var srcPos = (x + y * width) * 3;
  96111. byteArray[index] = srcData[srcPos + rOffset];
  96112. byteArray[index + 1] = srcData[srcPos + gOffset];
  96113. byteArray[index + 2] = srcData[srcPos + bOffset];
  96114. index += 3;
  96115. }
  96116. }
  96117. return byteArray;
  96118. };
  96119. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  96120. var byteArray = new Uint8Array(dataLength);
  96121. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  96122. var index = 0;
  96123. for (var y = 0; y < height; y++) {
  96124. for (var x = 0; x < width; x++) {
  96125. var srcPos = (x + y * width);
  96126. byteArray[index] = srcData[srcPos];
  96127. index++;
  96128. }
  96129. }
  96130. return byteArray;
  96131. };
  96132. /**
  96133. * Uploads DDS Levels to a Babylon Texture
  96134. * @hidden
  96135. */
  96136. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  96137. if (lodIndex === void 0) { lodIndex = -1; }
  96138. var sphericalPolynomialFaces = null;
  96139. if (info.sphericalPolynomial) {
  96140. sphericalPolynomialFaces = new Array();
  96141. }
  96142. var ext = engine.getCaps().s3tc;
  96143. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  96144. var fourCC, width, height, dataLength = 0, dataOffset;
  96145. var byteArray, mipmapCount, mip;
  96146. var internalCompressedFormat = 0;
  96147. var blockBytes = 1;
  96148. if (header[off_magic] !== DDS_MAGIC) {
  96149. BABYLON.Tools.Error("Invalid magic number in DDS header");
  96150. return;
  96151. }
  96152. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  96153. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  96154. return;
  96155. }
  96156. if (info.isCompressed && !ext) {
  96157. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  96158. return;
  96159. }
  96160. var bpp = header[off_RGBbpp];
  96161. dataOffset = header[off_size] + 4;
  96162. var computeFormats = false;
  96163. if (info.isFourCC) {
  96164. fourCC = header[off_pfFourCC];
  96165. switch (fourCC) {
  96166. case FOURCC_DXT1:
  96167. blockBytes = 8;
  96168. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  96169. break;
  96170. case FOURCC_DXT3:
  96171. blockBytes = 16;
  96172. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  96173. break;
  96174. case FOURCC_DXT5:
  96175. blockBytes = 16;
  96176. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  96177. break;
  96178. case FOURCC_D3DFMT_R16G16B16A16F:
  96179. computeFormats = true;
  96180. break;
  96181. case FOURCC_D3DFMT_R32G32B32A32F:
  96182. computeFormats = true;
  96183. break;
  96184. case FOURCC_DX10:
  96185. // There is an additionnal header so dataOffset need to be changed
  96186. dataOffset += 5 * 4; // 5 uints
  96187. var supported = false;
  96188. switch (info.dxgiFormat) {
  96189. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  96190. computeFormats = true;
  96191. supported = true;
  96192. break;
  96193. case DXGI_FORMAT_B8G8R8X8_UNORM:
  96194. info.isRGB = true;
  96195. info.isFourCC = false;
  96196. bpp = 32;
  96197. supported = true;
  96198. break;
  96199. }
  96200. if (supported) {
  96201. break;
  96202. }
  96203. default:
  96204. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  96205. return;
  96206. }
  96207. }
  96208. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  96209. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  96210. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  96211. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  96212. if (computeFormats) {
  96213. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  96214. }
  96215. mipmapCount = 1;
  96216. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  96217. mipmapCount = Math.max(1, header[off_mipmapCount]);
  96218. }
  96219. for (var face = 0; face < faces; face++) {
  96220. width = header[off_width];
  96221. height = header[off_height];
  96222. for (mip = 0; mip < mipmapCount; ++mip) {
  96223. if (lodIndex === -1 || lodIndex === mip) {
  96224. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  96225. var i = (lodIndex === -1) ? mip : 0;
  96226. if (!info.isCompressed && info.isFourCC) {
  96227. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  96228. dataLength = width * height * 4;
  96229. var floatArray = null;
  96230. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  96231. if (bpp === 128) {
  96232. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  96233. if (sphericalPolynomialFaces && i == 0) {
  96234. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  96235. }
  96236. }
  96237. else if (bpp === 64) {
  96238. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  96239. if (sphericalPolynomialFaces && i == 0) {
  96240. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  96241. }
  96242. }
  96243. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96244. }
  96245. else {
  96246. if (bpp === 128) {
  96247. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  96248. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  96249. if (sphericalPolynomialFaces && i == 0) {
  96250. sphericalPolynomialFaces.push(floatArray);
  96251. }
  96252. }
  96253. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  96254. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  96255. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  96256. if (sphericalPolynomialFaces && i == 0) {
  96257. sphericalPolynomialFaces.push(floatArray);
  96258. }
  96259. }
  96260. else { // 64
  96261. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  96262. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  96263. if (sphericalPolynomialFaces && i == 0) {
  96264. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  96265. }
  96266. }
  96267. }
  96268. if (floatArray) {
  96269. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  96270. }
  96271. }
  96272. else if (info.isRGB) {
  96273. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96274. if (bpp === 24) {
  96275. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  96276. dataLength = width * height * 3;
  96277. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  96278. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  96279. }
  96280. else { // 32
  96281. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  96282. dataLength = width * height * 4;
  96283. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  96284. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  96285. }
  96286. }
  96287. else if (info.isLuminance) {
  96288. var unpackAlignment = engine._getUnpackAlignement();
  96289. var unpaddedRowSize = width;
  96290. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  96291. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  96292. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  96293. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  96294. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96295. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  96296. }
  96297. else {
  96298. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  96299. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  96300. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96301. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  96302. }
  96303. }
  96304. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  96305. width *= 0.5;
  96306. height *= 0.5;
  96307. width = Math.max(1.0, width);
  96308. height = Math.max(1.0, height);
  96309. }
  96310. if (currentFace !== undefined) {
  96311. // Loading a single face
  96312. break;
  96313. }
  96314. }
  96315. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  96316. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  96317. size: header[off_width],
  96318. right: sphericalPolynomialFaces[0],
  96319. left: sphericalPolynomialFaces[1],
  96320. up: sphericalPolynomialFaces[2],
  96321. down: sphericalPolynomialFaces[3],
  96322. front: sphericalPolynomialFaces[4],
  96323. back: sphericalPolynomialFaces[5],
  96324. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  96325. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  96326. gammaSpace: false,
  96327. });
  96328. }
  96329. else {
  96330. info.sphericalPolynomial = undefined;
  96331. }
  96332. };
  96333. /**
  96334. * Gets or sets a boolean indicating that LOD info is stored in alpha channel (false by default)
  96335. */
  96336. DDSTools.StoreLODInAlphaChannel = false;
  96337. return DDSTools;
  96338. }());
  96339. BABYLON.DDSTools = DDSTools;
  96340. })(BABYLON || (BABYLON = {}));
  96341. //# sourceMappingURL=babylon.dds.js.map
  96342. var BABYLON;
  96343. (function (BABYLON) {
  96344. /**
  96345. * Implementation of the DDS Texture Loader.
  96346. */
  96347. var DDSTextureLoader = /** @class */ (function () {
  96348. function DDSTextureLoader() {
  96349. /**
  96350. * Defines wether the loader supports cascade loading the different faces.
  96351. */
  96352. this.supportCascades = true;
  96353. }
  96354. /**
  96355. * This returns if the loader support the current file information.
  96356. * @param extension defines the file extension of the file being loaded
  96357. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96358. * @param fallback defines the fallback internal texture if any
  96359. * @param isBase64 defines whether the texture is encoded as a base64
  96360. * @param isBuffer defines whether the texture data are stored as a buffer
  96361. * @returns true if the loader can load the specified file
  96362. */
  96363. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  96364. return extension.indexOf(".dds") === 0;
  96365. };
  96366. /**
  96367. * Transform the url before loading if required.
  96368. * @param rootUrl the url of the texture
  96369. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96370. * @returns the transformed texture
  96371. */
  96372. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  96373. return rootUrl;
  96374. };
  96375. /**
  96376. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  96377. * @param rootUrl the url of the texture
  96378. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96379. * @returns the fallback texture
  96380. */
  96381. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  96382. return null;
  96383. };
  96384. /**
  96385. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  96386. * @param data contains the texture data
  96387. * @param texture defines the BabylonJS internal texture
  96388. * @param createPolynomials will be true if polynomials have been requested
  96389. * @param onLoad defines the callback to trigger once the texture is ready
  96390. * @param onError defines the callback to trigger in case of error
  96391. */
  96392. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  96393. var engine = texture.getEngine();
  96394. var info;
  96395. var loadMipmap = false;
  96396. if (Array.isArray(imgs)) {
  96397. for (var index = 0; index < imgs.length; index++) {
  96398. var data_1 = imgs[index];
  96399. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  96400. texture.width = info.width;
  96401. texture.height = info.height;
  96402. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  96403. engine._unpackFlipY(info.isCompressed);
  96404. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  96405. if (!info.isFourCC && info.mipmapCount === 1) {
  96406. engine.generateMipMapsForCubemap(texture);
  96407. }
  96408. }
  96409. }
  96410. else {
  96411. var data = imgs;
  96412. info = BABYLON.DDSTools.GetDDSInfo(data);
  96413. texture.width = info.width;
  96414. texture.height = info.height;
  96415. if (createPolynomials) {
  96416. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  96417. }
  96418. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  96419. engine._unpackFlipY(info.isCompressed);
  96420. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  96421. if (!info.isFourCC && info.mipmapCount === 1) {
  96422. engine.generateMipMapsForCubemap(texture);
  96423. }
  96424. }
  96425. engine._setCubeMapTextureParams(loadMipmap);
  96426. texture.isReady = true;
  96427. if (onLoad) {
  96428. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  96429. }
  96430. };
  96431. /**
  96432. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  96433. * @param data contains the texture data
  96434. * @param texture defines the BabylonJS internal texture
  96435. * @param callback defines the method to call once ready to upload
  96436. */
  96437. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  96438. var info = BABYLON.DDSTools.GetDDSInfo(data);
  96439. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  96440. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  96441. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  96442. });
  96443. };
  96444. return DDSTextureLoader;
  96445. }());
  96446. // Register the loader.
  96447. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  96448. })(BABYLON || (BABYLON = {}));
  96449. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  96450. var BABYLON;
  96451. (function (BABYLON) {
  96452. /**
  96453. * Based on jsTGALoader - Javascript loader for TGA file
  96454. * By Vincent Thibault
  96455. * @see http://blog.robrowser.com/javascript-tga-loader.html
  96456. */
  96457. var TGATools = /** @class */ (function () {
  96458. function TGATools() {
  96459. }
  96460. /**
  96461. * Gets the header of a TGA file
  96462. * @param data defines the TGA data
  96463. * @returns the header
  96464. */
  96465. TGATools.GetTGAHeader = function (data) {
  96466. var offset = 0;
  96467. var header = {
  96468. id_length: data[offset++],
  96469. colormap_type: data[offset++],
  96470. image_type: data[offset++],
  96471. colormap_index: data[offset++] | data[offset++] << 8,
  96472. colormap_length: data[offset++] | data[offset++] << 8,
  96473. colormap_size: data[offset++],
  96474. origin: [
  96475. data[offset++] | data[offset++] << 8,
  96476. data[offset++] | data[offset++] << 8
  96477. ],
  96478. width: data[offset++] | data[offset++] << 8,
  96479. height: data[offset++] | data[offset++] << 8,
  96480. pixel_size: data[offset++],
  96481. flags: data[offset++]
  96482. };
  96483. return header;
  96484. };
  96485. /**
  96486. * Uploads TGA content to a Babylon Texture
  96487. * @hidden
  96488. */
  96489. TGATools.UploadContent = function (texture, data) {
  96490. // Not enough data to contain header ?
  96491. if (data.length < 19) {
  96492. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  96493. return;
  96494. }
  96495. // Read Header
  96496. var offset = 18;
  96497. var header = TGATools.GetTGAHeader(data);
  96498. // Assume it's a valid Targa file.
  96499. if (header.id_length + offset > data.length) {
  96500. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  96501. return;
  96502. }
  96503. // Skip not needed data
  96504. offset += header.id_length;
  96505. var use_rle = false;
  96506. var use_pal = false;
  96507. var use_grey = false;
  96508. // Get some informations.
  96509. switch (header.image_type) {
  96510. case TGATools._TYPE_RLE_INDEXED:
  96511. use_rle = true;
  96512. case TGATools._TYPE_INDEXED:
  96513. use_pal = true;
  96514. break;
  96515. case TGATools._TYPE_RLE_RGB:
  96516. use_rle = true;
  96517. case TGATools._TYPE_RGB:
  96518. // use_rgb = true;
  96519. break;
  96520. case TGATools._TYPE_RLE_GREY:
  96521. use_rle = true;
  96522. case TGATools._TYPE_GREY:
  96523. use_grey = true;
  96524. break;
  96525. }
  96526. var pixel_data;
  96527. // var numAlphaBits = header.flags & 0xf;
  96528. var pixel_size = header.pixel_size >> 3;
  96529. var pixel_total = header.width * header.height * pixel_size;
  96530. // Read palettes
  96531. var palettes;
  96532. if (use_pal) {
  96533. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  96534. }
  96535. // Read LRE
  96536. if (use_rle) {
  96537. pixel_data = new Uint8Array(pixel_total);
  96538. var c, count, i;
  96539. var localOffset = 0;
  96540. var pixels = new Uint8Array(pixel_size);
  96541. while (offset < pixel_total && localOffset < pixel_total) {
  96542. c = data[offset++];
  96543. count = (c & 0x7f) + 1;
  96544. // RLE pixels
  96545. if (c & 0x80) {
  96546. // Bind pixel tmp array
  96547. for (i = 0; i < pixel_size; ++i) {
  96548. pixels[i] = data[offset++];
  96549. }
  96550. // Copy pixel array
  96551. for (i = 0; i < count; ++i) {
  96552. pixel_data.set(pixels, localOffset + i * pixel_size);
  96553. }
  96554. localOffset += pixel_size * count;
  96555. }
  96556. // Raw pixels
  96557. else {
  96558. count *= pixel_size;
  96559. for (i = 0; i < count; ++i) {
  96560. pixel_data[localOffset + i] = data[offset++];
  96561. }
  96562. localOffset += count;
  96563. }
  96564. }
  96565. }
  96566. // RAW Pixels
  96567. else {
  96568. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  96569. }
  96570. // Load to texture
  96571. var x_start, y_start, x_step, y_step, y_end, x_end;
  96572. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  96573. default:
  96574. case TGATools._ORIGIN_UL:
  96575. x_start = 0;
  96576. x_step = 1;
  96577. x_end = header.width;
  96578. y_start = 0;
  96579. y_step = 1;
  96580. y_end = header.height;
  96581. break;
  96582. case TGATools._ORIGIN_BL:
  96583. x_start = 0;
  96584. x_step = 1;
  96585. x_end = header.width;
  96586. y_start = header.height - 1;
  96587. y_step = -1;
  96588. y_end = -1;
  96589. break;
  96590. case TGATools._ORIGIN_UR:
  96591. x_start = header.width - 1;
  96592. x_step = -1;
  96593. x_end = -1;
  96594. y_start = 0;
  96595. y_step = 1;
  96596. y_end = header.height;
  96597. break;
  96598. case TGATools._ORIGIN_BR:
  96599. x_start = header.width - 1;
  96600. x_step = -1;
  96601. x_end = -1;
  96602. y_start = header.height - 1;
  96603. y_step = -1;
  96604. y_end = -1;
  96605. break;
  96606. }
  96607. // Load the specify method
  96608. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  96609. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  96610. var engine = texture.getEngine();
  96611. engine._uploadDataToTextureDirectly(texture, imageData);
  96612. };
  96613. /** @hidden */
  96614. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  96615. var image = pixel_data, colormap = palettes;
  96616. var width = header.width, height = header.height;
  96617. var color, i = 0, x, y;
  96618. var imageData = new Uint8Array(width * height * 4);
  96619. for (y = y_start; y !== y_end; y += y_step) {
  96620. for (x = x_start; x !== x_end; x += x_step, i++) {
  96621. color = image[i];
  96622. imageData[(x + width * y) * 4 + 3] = 255;
  96623. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  96624. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  96625. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  96626. }
  96627. }
  96628. return imageData;
  96629. };
  96630. /** @hidden */
  96631. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  96632. var image = pixel_data;
  96633. var width = header.width, height = header.height;
  96634. var color, i = 0, x, y;
  96635. var imageData = new Uint8Array(width * height * 4);
  96636. for (y = y_start; y !== y_end; y += y_step) {
  96637. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  96638. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  96639. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  96640. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  96641. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  96642. imageData[(x + width * y) * 4 + 0] = r;
  96643. imageData[(x + width * y) * 4 + 1] = g;
  96644. imageData[(x + width * y) * 4 + 2] = b;
  96645. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  96646. }
  96647. }
  96648. return imageData;
  96649. };
  96650. /** @hidden */
  96651. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  96652. var image = pixel_data;
  96653. var width = header.width, height = header.height;
  96654. var i = 0, x, y;
  96655. var imageData = new Uint8Array(width * height * 4);
  96656. for (y = y_start; y !== y_end; y += y_step) {
  96657. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  96658. imageData[(x + width * y) * 4 + 3] = 255;
  96659. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  96660. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  96661. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  96662. }
  96663. }
  96664. return imageData;
  96665. };
  96666. /** @hidden */
  96667. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  96668. var image = pixel_data;
  96669. var width = header.width, height = header.height;
  96670. var i = 0, x, y;
  96671. var imageData = new Uint8Array(width * height * 4);
  96672. for (y = y_start; y !== y_end; y += y_step) {
  96673. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  96674. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  96675. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  96676. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  96677. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  96678. }
  96679. }
  96680. return imageData;
  96681. };
  96682. /** @hidden */
  96683. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  96684. var image = pixel_data;
  96685. var width = header.width, height = header.height;
  96686. var color, i = 0, x, y;
  96687. var imageData = new Uint8Array(width * height * 4);
  96688. for (y = y_start; y !== y_end; y += y_step) {
  96689. for (x = x_start; x !== x_end; x += x_step, i++) {
  96690. color = image[i];
  96691. imageData[(x + width * y) * 4 + 0] = color;
  96692. imageData[(x + width * y) * 4 + 1] = color;
  96693. imageData[(x + width * y) * 4 + 2] = color;
  96694. imageData[(x + width * y) * 4 + 3] = 255;
  96695. }
  96696. }
  96697. return imageData;
  96698. };
  96699. /** @hidden */
  96700. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  96701. var image = pixel_data;
  96702. var width = header.width, height = header.height;
  96703. var i = 0, x, y;
  96704. var imageData = new Uint8Array(width * height * 4);
  96705. for (y = y_start; y !== y_end; y += y_step) {
  96706. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  96707. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  96708. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  96709. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  96710. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  96711. }
  96712. }
  96713. return imageData;
  96714. };
  96715. //private static _TYPE_NO_DATA = 0;
  96716. TGATools._TYPE_INDEXED = 1;
  96717. TGATools._TYPE_RGB = 2;
  96718. TGATools._TYPE_GREY = 3;
  96719. TGATools._TYPE_RLE_INDEXED = 9;
  96720. TGATools._TYPE_RLE_RGB = 10;
  96721. TGATools._TYPE_RLE_GREY = 11;
  96722. TGATools._ORIGIN_MASK = 0x30;
  96723. TGATools._ORIGIN_SHIFT = 0x04;
  96724. TGATools._ORIGIN_BL = 0x00;
  96725. TGATools._ORIGIN_BR = 0x01;
  96726. TGATools._ORIGIN_UL = 0x02;
  96727. TGATools._ORIGIN_UR = 0x03;
  96728. return TGATools;
  96729. }());
  96730. BABYLON.TGATools = TGATools;
  96731. })(BABYLON || (BABYLON = {}));
  96732. //# sourceMappingURL=babylon.tga.js.map
  96733. var BABYLON;
  96734. (function (BABYLON) {
  96735. /**
  96736. * Implementation of the TGA Texture Loader.
  96737. */
  96738. var TGATextureLoader = /** @class */ (function () {
  96739. function TGATextureLoader() {
  96740. /**
  96741. * Defines wether the loader supports cascade loading the different faces.
  96742. */
  96743. this.supportCascades = false;
  96744. }
  96745. /**
  96746. * This returns if the loader support the current file information.
  96747. * @param extension defines the file extension of the file being loaded
  96748. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96749. * @param fallback defines the fallback internal texture if any
  96750. * @param isBase64 defines whether the texture is encoded as a base64
  96751. * @param isBuffer defines whether the texture data are stored as a buffer
  96752. * @returns true if the loader can load the specified file
  96753. */
  96754. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  96755. return extension.indexOf(".tga") === 0;
  96756. };
  96757. /**
  96758. * Transform the url before loading if required.
  96759. * @param rootUrl the url of the texture
  96760. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96761. * @returns the transformed texture
  96762. */
  96763. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  96764. return rootUrl;
  96765. };
  96766. /**
  96767. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  96768. * @param rootUrl the url of the texture
  96769. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96770. * @returns the fallback texture
  96771. */
  96772. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  96773. return null;
  96774. };
  96775. /**
  96776. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  96777. * @param data contains the texture data
  96778. * @param texture defines the BabylonJS internal texture
  96779. * @param createPolynomials will be true if polynomials have been requested
  96780. * @param onLoad defines the callback to trigger once the texture is ready
  96781. * @param onError defines the callback to trigger in case of error
  96782. */
  96783. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  96784. throw ".env not supported in Cube.";
  96785. };
  96786. /**
  96787. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  96788. * @param data contains the texture data
  96789. * @param texture defines the BabylonJS internal texture
  96790. * @param callback defines the method to call once ready to upload
  96791. */
  96792. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  96793. var uintData = new Uint8Array(data);
  96794. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  96795. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  96796. BABYLON.TGATools.UploadContent(texture, uintData);
  96797. });
  96798. };
  96799. return TGATextureLoader;
  96800. }());
  96801. // Register the loader.
  96802. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  96803. })(BABYLON || (BABYLON = {}));
  96804. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  96805. var BABYLON;
  96806. (function (BABYLON) {
  96807. /**
  96808. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  96809. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  96810. */
  96811. var KhronosTextureContainer = /** @class */ (function () {
  96812. /**
  96813. * Creates a new KhronosTextureContainer
  96814. * @param arrayBuffer contents of the KTX container file
  96815. * @param facesExpected should be either 1 or 6, based whether a cube texture or or
  96816. * @param threeDExpected provision for indicating that data should be a 3D texture, not implemented
  96817. * @param textureArrayExpected provision for indicating that data should be a texture array, not implemented
  96818. */
  96819. function KhronosTextureContainer(
  96820. /** contents of the KTX container file */
  96821. arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  96822. this.arrayBuffer = arrayBuffer;
  96823. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  96824. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  96825. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  96826. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  96827. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  96828. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  96829. BABYLON.Tools.Error("texture missing KTX identifier");
  96830. return;
  96831. }
  96832. // load the reset of the header in native 32 bit int
  96833. var header = new Int32Array(this.arrayBuffer, 12, 13);
  96834. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  96835. var oppositeEndianess = header[0] === 0x01020304;
  96836. // read all the header elements in order they exist in the file, without modification (sans endainness)
  96837. this.glType = oppositeEndianess ? this.switchEndianness(header[1]) : header[1]; // must be 0 for compressed textures
  96838. this.glTypeSize = oppositeEndianess ? this.switchEndianness(header[2]) : header[2]; // must be 1 for compressed textures
  96839. this.glFormat = oppositeEndianess ? this.switchEndianness(header[3]) : header[3]; // must be 0 for compressed textures
  96840. this.glInternalFormat = oppositeEndianess ? this.switchEndianness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  96841. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndianness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  96842. this.pixelWidth = oppositeEndianess ? this.switchEndianness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  96843. this.pixelHeight = oppositeEndianess ? this.switchEndianness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  96844. this.pixelDepth = oppositeEndianess ? this.switchEndianness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  96845. this.numberOfArrayElements = oppositeEndianess ? this.switchEndianness(header[9]) : header[9]; // used for texture arrays
  96846. this.numberOfFaces = oppositeEndianess ? this.switchEndianness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  96847. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndianness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  96848. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndianness(header[12]) : header[12]; // the amount of space after the header for meta-data
  96849. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  96850. if (this.glType !== 0) {
  96851. BABYLON.Tools.Error("only compressed formats currently supported");
  96852. return;
  96853. }
  96854. else {
  96855. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  96856. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  96857. }
  96858. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  96859. BABYLON.Tools.Error("only 2D textures currently supported");
  96860. return;
  96861. }
  96862. if (this.numberOfArrayElements !== 0) {
  96863. BABYLON.Tools.Error("texture arrays not currently supported");
  96864. return;
  96865. }
  96866. if (this.numberOfFaces !== facesExpected) {
  96867. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  96868. return;
  96869. }
  96870. // we now have a completely validated file, so could use existence of loadType as success
  96871. // would need to make this more elaborate & adjust checks above to support more than one load type
  96872. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  96873. }
  96874. //
  96875. /**
  96876. * Revert the endianness of a value.
  96877. * Not as fast hardware based, but will probably never need to use
  96878. * @param val defines the value to convert
  96879. * @returns the new value
  96880. */
  96881. KhronosTextureContainer.prototype.switchEndianness = function (val) {
  96882. return ((val & 0xFF) << 24)
  96883. | ((val & 0xFF00) << 8)
  96884. | ((val >> 8) & 0xFF00)
  96885. | ((val >> 24) & 0xFF);
  96886. };
  96887. /**
  96888. * Uploads KTX content to a Babylon Texture.
  96889. * It is assumed that the texture has already been created & is currently bound
  96890. * @hidden
  96891. */
  96892. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  96893. switch (this.loadType) {
  96894. case KhronosTextureContainer.COMPRESSED_2D:
  96895. this._upload2DCompressedLevels(texture, loadMipmaps);
  96896. break;
  96897. case KhronosTextureContainer.TEX_2D:
  96898. case KhronosTextureContainer.COMPRESSED_3D:
  96899. case KhronosTextureContainer.TEX_3D:
  96900. }
  96901. };
  96902. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  96903. // initialize width & height for level 1
  96904. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  96905. var width = this.pixelWidth;
  96906. var height = this.pixelHeight;
  96907. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  96908. for (var level = 0; level < mipmapCount; level++) {
  96909. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  96910. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  96911. for (var face = 0; face < this.numberOfFaces; face++) {
  96912. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  96913. var engine = texture.getEngine();
  96914. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  96915. dataOffset += imageSize; // add size of the image for the next face/mipmap
  96916. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  96917. }
  96918. width = Math.max(1.0, width * 0.5);
  96919. height = Math.max(1.0, height * 0.5);
  96920. }
  96921. };
  96922. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  96923. // load types
  96924. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  96925. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  96926. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  96927. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  96928. return KhronosTextureContainer;
  96929. }());
  96930. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  96931. })(BABYLON || (BABYLON = {}));
  96932. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  96933. var BABYLON;
  96934. (function (BABYLON) {
  96935. /**
  96936. * Implementation of the KTX Texture Loader.
  96937. */
  96938. var KTXTextureLoader = /** @class */ (function () {
  96939. function KTXTextureLoader() {
  96940. /**
  96941. * Defines wether the loader supports cascade loading the different faces.
  96942. */
  96943. this.supportCascades = false;
  96944. }
  96945. /**
  96946. * This returns if the loader support the current file information.
  96947. * @param extension defines the file extension of the file being loaded
  96948. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96949. * @param fallback defines the fallback internal texture if any
  96950. * @param isBase64 defines whether the texture is encoded as a base64
  96951. * @param isBuffer defines whether the texture data are stored as a buffer
  96952. * @returns true if the loader can load the specified file
  96953. */
  96954. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  96955. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  96956. return true;
  96957. }
  96958. return false;
  96959. };
  96960. /**
  96961. * Transform the url before loading if required.
  96962. * @param rootUrl the url of the texture
  96963. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96964. * @returns the transformed texture
  96965. */
  96966. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  96967. var lastDot = rootUrl.lastIndexOf('.');
  96968. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  96969. };
  96970. /**
  96971. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  96972. * @param rootUrl the url of the texture
  96973. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96974. * @returns the fallback texture
  96975. */
  96976. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  96977. // remove the format appended to the rootUrl in the original createCubeTexture call.
  96978. var exp = new RegExp("" + textureFormatInUse + "$");
  96979. return rootUrl.replace(exp, "");
  96980. };
  96981. /**
  96982. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  96983. * @param data contains the texture data
  96984. * @param texture defines the BabylonJS internal texture
  96985. * @param createPolynomials will be true if polynomials have been requested
  96986. * @param onLoad defines the callback to trigger once the texture is ready
  96987. * @param onError defines the callback to trigger in case of error
  96988. */
  96989. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  96990. if (Array.isArray(data)) {
  96991. return;
  96992. }
  96993. var engine = texture.getEngine();
  96994. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  96995. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  96996. engine._unpackFlipY(true);
  96997. ktx.uploadLevels(texture, texture.generateMipMaps);
  96998. texture.width = ktx.pixelWidth;
  96999. texture.height = ktx.pixelHeight;
  97000. engine._setCubeMapTextureParams(loadMipmap);
  97001. texture.isReady = true;
  97002. };
  97003. /**
  97004. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  97005. * @param data contains the texture data
  97006. * @param texture defines the BabylonJS internal texture
  97007. * @param callback defines the method to call once ready to upload
  97008. */
  97009. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  97010. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  97011. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  97012. ktx.uploadLevels(texture, texture.generateMipMaps);
  97013. });
  97014. };
  97015. return KTXTextureLoader;
  97016. }());
  97017. // Register the loader.
  97018. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  97019. })(BABYLON || (BABYLON = {}));
  97020. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  97021. var BABYLON;
  97022. (function (BABYLON) {
  97023. /**
  97024. * Sets of helpers addressing the serialization and deserialization of environment texture
  97025. * stored in a BabylonJS env file.
  97026. * Those files are usually stored as .env files.
  97027. */
  97028. var EnvironmentTextureTools = /** @class */ (function () {
  97029. function EnvironmentTextureTools() {
  97030. }
  97031. /**
  97032. * Gets the environment info from an env file.
  97033. * @param data The array buffer containing the .env bytes.
  97034. * @returns the environment file info (the json header) if successfully parsed.
  97035. */
  97036. EnvironmentTextureTools.GetEnvInfo = function (data) {
  97037. var dataView = new DataView(data);
  97038. var pos = 0;
  97039. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  97040. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  97041. BABYLON.Tools.Error('Not a babylon environment map');
  97042. return null;
  97043. }
  97044. }
  97045. // Read json manifest - collect characters up to null terminator
  97046. var manifestString = '';
  97047. var charCode = 0x00;
  97048. while ((charCode = dataView.getUint8(pos++))) {
  97049. manifestString += String.fromCharCode(charCode);
  97050. }
  97051. var manifest = JSON.parse(manifestString);
  97052. if (manifest.specular) {
  97053. // Extend the header with the position of the payload.
  97054. manifest.specular.specularDataPosition = pos;
  97055. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  97056. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  97057. }
  97058. return manifest;
  97059. };
  97060. /**
  97061. * Creates an environment texture from a loaded cube texture.
  97062. * @param texture defines the cube texture to convert in env file
  97063. * @return a promise containing the environment data if succesfull.
  97064. */
  97065. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  97066. var _this = this;
  97067. var internalTexture = texture.getInternalTexture();
  97068. if (!internalTexture) {
  97069. return Promise.reject("The cube texture is invalid.");
  97070. }
  97071. if (!texture._prefiltered) {
  97072. return Promise.reject("The cube texture is invalid (not prefiltered).");
  97073. }
  97074. var engine = internalTexture.getEngine();
  97075. if (engine && engine.premultipliedAlpha) {
  97076. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  97077. }
  97078. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  97079. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  97080. }
  97081. var canvas = engine.getRenderingCanvas();
  97082. if (!canvas) {
  97083. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  97084. }
  97085. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  97086. if (!engine.getCaps().textureFloatRender) {
  97087. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97088. if (!engine.getCaps().textureHalfFloatRender) {
  97089. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  97090. }
  97091. }
  97092. var cubeWidth = internalTexture.width;
  97093. var hostingScene = new BABYLON.Scene(engine);
  97094. var specularTextures = {};
  97095. var promises = [];
  97096. // Read and collect all mipmaps data from the cube.
  97097. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  97098. mipmapsCount = Math.round(mipmapsCount);
  97099. var _loop_1 = function (i) {
  97100. var faceWidth = Math.pow(2, mipmapsCount - i);
  97101. var _loop_2 = function (face) {
  97102. var data = texture.readPixels(face, i);
  97103. // Creates a temp texture with the face data.
  97104. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  97105. // And rgbdEncode them.
  97106. var promise = new Promise(function (resolve, reject) {
  97107. 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);
  97108. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  97109. rgbdPostProcess.onApply = function (effect) {
  97110. effect._bindTexture("textureSampler", tempTexture);
  97111. };
  97112. // As the process needs to happen on the main canvas, keep track of the current size
  97113. var currentW = engine.getRenderWidth();
  97114. var currentH = engine.getRenderHeight();
  97115. // Set the desired size for the texture
  97116. engine.setSize(faceWidth, faceWidth);
  97117. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  97118. // Reading datas from WebGL
  97119. BABYLON.Tools.ToBlob(canvas, function (blob) {
  97120. var fileReader = new FileReader();
  97121. fileReader.onload = function (event) {
  97122. var arrayBuffer = event.target.result;
  97123. specularTextures[i * 6 + face] = arrayBuffer;
  97124. resolve();
  97125. };
  97126. fileReader.readAsArrayBuffer(blob);
  97127. });
  97128. // Reapply the previous canvas size
  97129. engine.setSize(currentW, currentH);
  97130. });
  97131. });
  97132. promises.push(promise);
  97133. };
  97134. // All faces of the cube.
  97135. for (var face = 0; face < 6; face++) {
  97136. _loop_2(face);
  97137. }
  97138. };
  97139. for (var i = 0; i <= mipmapsCount; i++) {
  97140. _loop_1(i);
  97141. }
  97142. // Once all the textures haves been collected as RGBD stored in PNGs
  97143. return Promise.all(promises).then(function () {
  97144. // We can delete the hosting scene keeping track of all the creation objects
  97145. hostingScene.dispose();
  97146. // Creates the json header for the env texture
  97147. var info = {
  97148. version: 1,
  97149. width: cubeWidth,
  97150. irradiance: _this._CreateEnvTextureIrradiance(texture),
  97151. specular: {
  97152. mipmaps: [],
  97153. lodGenerationScale: texture.lodGenerationScale
  97154. }
  97155. };
  97156. // Sets the specular image data information
  97157. var position = 0;
  97158. for (var i = 0; i <= mipmapsCount; i++) {
  97159. for (var face = 0; face < 6; face++) {
  97160. var byteLength = specularTextures[i * 6 + face].byteLength;
  97161. info.specular.mipmaps.push({
  97162. length: byteLength,
  97163. position: position
  97164. });
  97165. position += byteLength;
  97166. }
  97167. }
  97168. // Encode the JSON as an array buffer
  97169. var infoString = JSON.stringify(info);
  97170. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  97171. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  97172. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  97173. infoView[i] = infoString.charCodeAt(i);
  97174. }
  97175. // Ends up with a null terminator for easier parsing
  97176. infoView[infoString.length] = 0x00;
  97177. // Computes the final required size and creates the storage
  97178. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  97179. var finalBuffer = new ArrayBuffer(totalSize);
  97180. var finalBufferView = new Uint8Array(finalBuffer);
  97181. var dataView = new DataView(finalBuffer);
  97182. // Copy the magic bytes identifying the file in
  97183. var pos = 0;
  97184. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  97185. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  97186. }
  97187. // Add the json info
  97188. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  97189. pos += infoBuffer.byteLength;
  97190. // Finally inserts the texture data
  97191. for (var i = 0; i <= mipmapsCount; i++) {
  97192. for (var face = 0; face < 6; face++) {
  97193. var dataBuffer = specularTextures[i * 6 + face];
  97194. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  97195. pos += dataBuffer.byteLength;
  97196. }
  97197. }
  97198. // Voila
  97199. return finalBuffer;
  97200. });
  97201. };
  97202. /**
  97203. * Creates a JSON representation of the spherical data.
  97204. * @param texture defines the texture containing the polynomials
  97205. * @return the JSON representation of the spherical info
  97206. */
  97207. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  97208. var polynmials = texture.sphericalPolynomial;
  97209. if (polynmials == null) {
  97210. return null;
  97211. }
  97212. return {
  97213. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  97214. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  97215. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  97216. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  97217. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  97218. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  97219. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  97220. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  97221. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  97222. };
  97223. };
  97224. /**
  97225. * Uploads the texture info contained in the env file to the GPU.
  97226. * @param texture defines the internal texture to upload to
  97227. * @param arrayBuffer defines the buffer cotaining the data to load
  97228. * @param info defines the texture info retrieved through the GetEnvInfo method
  97229. * @returns a promise
  97230. */
  97231. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  97232. if (info.version !== 1) {
  97233. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  97234. }
  97235. var specularInfo = info.specular;
  97236. if (!specularInfo) {
  97237. // Nothing else parsed so far
  97238. return Promise.resolve();
  97239. }
  97240. // Double checks the enclosed info
  97241. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  97242. mipmapsCount = Math.round(mipmapsCount) + 1;
  97243. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  97244. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  97245. }
  97246. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  97247. var imageData = new Array(mipmapsCount);
  97248. for (var i = 0; i < mipmapsCount; i++) {
  97249. imageData[i] = new Array(6);
  97250. for (var face = 0; face < 6; face++) {
  97251. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  97252. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  97253. }
  97254. }
  97255. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  97256. };
  97257. /**
  97258. * Uploads the levels of image data to the GPU.
  97259. * @param texture defines the internal texture to upload to
  97260. * @param imageData defines the array buffer views of image data [mipmap][face]
  97261. * @returns a promise
  97262. */
  97263. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  97264. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  97265. throw new Error("Texture size must be a power of two");
  97266. }
  97267. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  97268. // Gets everything ready.
  97269. var engine = texture.getEngine();
  97270. var expandTexture = false;
  97271. var generateNonLODTextures = false;
  97272. var rgbdPostProcess = null;
  97273. var cubeRtt = null;
  97274. var lodTextures = null;
  97275. var caps = engine.getCaps();
  97276. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  97277. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97278. texture.generateMipMaps = true;
  97279. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  97280. // Add extra process if texture lod is not supported
  97281. if (!caps.textureLOD) {
  97282. expandTexture = false;
  97283. generateNonLODTextures = true;
  97284. lodTextures = {};
  97285. }
  97286. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  97287. else if (engine.webGLVersion < 2) {
  97288. expandTexture = false;
  97289. }
  97290. // If half float available we can uncompress the texture
  97291. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  97292. expandTexture = true;
  97293. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97294. }
  97295. // If full float available we can uncompress the texture
  97296. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  97297. expandTexture = true;
  97298. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  97299. }
  97300. // Expand the texture if possible
  97301. if (expandTexture) {
  97302. // Simply run through the decode PP
  97303. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  97304. texture._isRGBD = false;
  97305. texture.invertY = false;
  97306. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  97307. generateDepthBuffer: false,
  97308. generateMipMaps: true,
  97309. generateStencilBuffer: false,
  97310. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  97311. type: texture.type,
  97312. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  97313. });
  97314. }
  97315. else {
  97316. texture._isRGBD = true;
  97317. texture.invertY = true;
  97318. // In case of missing support, applies the same patch than DDS files.
  97319. if (generateNonLODTextures) {
  97320. var mipSlices = 3;
  97321. var scale = texture._lodGenerationScale;
  97322. var offset = texture._lodGenerationOffset;
  97323. for (var i = 0; i < mipSlices; i++) {
  97324. //compute LOD from even spacing in smoothness (matching shader calculation)
  97325. var smoothness = i / (mipSlices - 1);
  97326. var roughness = 1 - smoothness;
  97327. var minLODIndex = offset; // roughness = 0
  97328. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  97329. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  97330. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  97331. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  97332. glTextureFromLod.isCube = true;
  97333. glTextureFromLod.invertY = true;
  97334. glTextureFromLod.generateMipMaps = false;
  97335. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  97336. // Wrap in a base texture for easy binding.
  97337. var lodTexture = new BABYLON.BaseTexture(null);
  97338. lodTexture.isCube = true;
  97339. lodTexture._texture = glTextureFromLod;
  97340. lodTextures[mipmapIndex] = lodTexture;
  97341. switch (i) {
  97342. case 0:
  97343. texture._lodTextureLow = lodTexture;
  97344. break;
  97345. case 1:
  97346. texture._lodTextureMid = lodTexture;
  97347. break;
  97348. case 2:
  97349. texture._lodTextureHigh = lodTexture;
  97350. break;
  97351. }
  97352. }
  97353. }
  97354. }
  97355. var promises = [];
  97356. var _loop_3 = function (i) {
  97357. var _loop_4 = function (face) {
  97358. // Constructs an image element from image data
  97359. var bytes = imageData[i][face];
  97360. var blob = new Blob([bytes], { type: 'image/png' });
  97361. var url = URL.createObjectURL(blob);
  97362. var image = new Image();
  97363. image.src = url;
  97364. // Enqueue promise to upload to the texture.
  97365. var promise = new Promise(function (resolve, reject) {
  97366. image.onload = function () {
  97367. if (expandTexture) {
  97368. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  97369. reject(message);
  97370. }, image);
  97371. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  97372. // Uncompress the data to a RTT
  97373. rgbdPostProcess.onApply = function (effect) {
  97374. effect._bindTexture("textureSampler", tempTexture_1);
  97375. effect.setFloat2("scale", 1, 1);
  97376. };
  97377. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  97378. // Cleanup
  97379. engine.restoreDefaultFramebuffer();
  97380. tempTexture_1.dispose();
  97381. window.URL.revokeObjectURL(url);
  97382. resolve();
  97383. });
  97384. }
  97385. else {
  97386. engine._uploadImageToTexture(texture, image, face, i);
  97387. // Upload the face to the non lod texture support
  97388. if (generateNonLODTextures) {
  97389. var lodTexture = lodTextures[i];
  97390. if (lodTexture) {
  97391. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  97392. }
  97393. }
  97394. resolve();
  97395. }
  97396. };
  97397. image.onerror = function (error) {
  97398. reject(error);
  97399. };
  97400. });
  97401. promises.push(promise);
  97402. };
  97403. // All faces
  97404. for (var face = 0; face < 6; face++) {
  97405. _loop_4(face);
  97406. }
  97407. };
  97408. // All mipmaps up to provided number of images
  97409. for (var i = 0; i < imageData.length; i++) {
  97410. _loop_3(i);
  97411. }
  97412. // Fill remaining mipmaps with black textures.
  97413. if (imageData.length < mipmapsCount) {
  97414. var data = void 0;
  97415. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  97416. var dataLength = size * size * 4;
  97417. switch (texture.type) {
  97418. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  97419. data = new Uint8Array(dataLength);
  97420. break;
  97421. }
  97422. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  97423. data = new Uint16Array(dataLength);
  97424. break;
  97425. }
  97426. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  97427. data = new Float32Array(dataLength);
  97428. break;
  97429. }
  97430. }
  97431. for (var i = imageData.length; i < mipmapsCount; i++) {
  97432. for (var face = 0; face < 6; face++) {
  97433. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  97434. }
  97435. }
  97436. }
  97437. // Once all done, finishes the cleanup and return
  97438. return Promise.all(promises).then(function () {
  97439. // Release temp RTT.
  97440. if (cubeRtt) {
  97441. engine._releaseFramebufferObjects(cubeRtt);
  97442. cubeRtt._swapAndDie(texture);
  97443. }
  97444. // Release temp Post Process.
  97445. if (rgbdPostProcess) {
  97446. rgbdPostProcess.dispose();
  97447. }
  97448. // Flag internal texture as ready in case they are in use.
  97449. if (generateNonLODTextures) {
  97450. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  97451. texture._lodTextureHigh._texture.isReady = true;
  97452. }
  97453. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  97454. texture._lodTextureMid._texture.isReady = true;
  97455. }
  97456. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  97457. texture._lodTextureLow._texture.isReady = true;
  97458. }
  97459. }
  97460. });
  97461. };
  97462. /**
  97463. * Uploads spherical polynomials information to the texture.
  97464. * @param texture defines the texture we are trying to upload the information to
  97465. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  97466. */
  97467. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  97468. if (info.version !== 1) {
  97469. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  97470. }
  97471. var irradianceInfo = info.irradiance;
  97472. if (!irradianceInfo) {
  97473. return;
  97474. }
  97475. var sp = new BABYLON.SphericalPolynomial();
  97476. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  97477. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  97478. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  97479. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  97480. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  97481. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  97482. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  97483. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  97484. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  97485. texture._sphericalPolynomial = sp;
  97486. };
  97487. /**
  97488. * Magic number identifying the env file.
  97489. */
  97490. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  97491. return EnvironmentTextureTools;
  97492. }());
  97493. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  97494. })(BABYLON || (BABYLON = {}));
  97495. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  97496. var BABYLON;
  97497. (function (BABYLON) {
  97498. /**
  97499. * Implementation of the ENV Texture Loader.
  97500. */
  97501. var ENVTextureLoader = /** @class */ (function () {
  97502. function ENVTextureLoader() {
  97503. /**
  97504. * Defines wether the loader supports cascade loading the different faces.
  97505. */
  97506. this.supportCascades = false;
  97507. }
  97508. /**
  97509. * This returns if the loader support the current file information.
  97510. * @param extension defines the file extension of the file being loaded
  97511. * @param textureFormatInUse defines the current compressed format in use iun the engine
  97512. * @param fallback defines the fallback internal texture if any
  97513. * @param isBase64 defines whether the texture is encoded as a base64
  97514. * @param isBuffer defines whether the texture data are stored as a buffer
  97515. * @returns true if the loader can load the specified file
  97516. */
  97517. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  97518. return extension.indexOf(".env") === 0;
  97519. };
  97520. /**
  97521. * Transform the url before loading if required.
  97522. * @param rootUrl the url of the texture
  97523. * @param textureFormatInUse defines the current compressed format in use iun the engine
  97524. * @returns the transformed texture
  97525. */
  97526. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  97527. return rootUrl;
  97528. };
  97529. /**
  97530. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  97531. * @param rootUrl the url of the texture
  97532. * @param textureFormatInUse defines the current compressed format in use iun the engine
  97533. * @returns the fallback texture
  97534. */
  97535. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  97536. return null;
  97537. };
  97538. /**
  97539. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  97540. * @param data contains the texture data
  97541. * @param texture defines the BabylonJS internal texture
  97542. * @param createPolynomials will be true if polynomials have been requested
  97543. * @param onLoad defines the callback to trigger once the texture is ready
  97544. * @param onError defines the callback to trigger in case of error
  97545. */
  97546. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  97547. if (Array.isArray(data)) {
  97548. return;
  97549. }
  97550. data = data;
  97551. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  97552. if (info) {
  97553. texture.width = info.width;
  97554. texture.height = info.width;
  97555. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  97556. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  97557. texture.isReady = true;
  97558. if (onLoad) {
  97559. onLoad();
  97560. }
  97561. });
  97562. }
  97563. else if (onError) {
  97564. onError("Can not parse the environment file", null);
  97565. }
  97566. };
  97567. /**
  97568. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  97569. * @param data contains the texture data
  97570. * @param texture defines the BabylonJS internal texture
  97571. * @param callback defines the method to call once ready to upload
  97572. */
  97573. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  97574. throw ".env not supported in 2d.";
  97575. };
  97576. return ENVTextureLoader;
  97577. }());
  97578. // Register the loader.
  97579. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  97580. })(BABYLON || (BABYLON = {}));
  97581. //# sourceMappingURL=babylon.envTextureLoader.js.map
  97582. var BABYLON;
  97583. (function (BABYLON) {
  97584. /**
  97585. * Renders a layer on top of an existing scene
  97586. */
  97587. var UtilityLayerRenderer = /** @class */ (function () {
  97588. /**
  97589. * Instantiates a UtilityLayerRenderer
  97590. * @param originalScene the original scene that will be rendered on top of
  97591. */
  97592. function UtilityLayerRenderer(
  97593. /** the original scene that will be rendered on top of */
  97594. originalScene) {
  97595. var _this = this;
  97596. this.originalScene = originalScene;
  97597. this._pointerCaptures = {};
  97598. this._lastPointerEvents = {};
  97599. /**
  97600. * If the utility layer should automatically be rendered on top of existing scene
  97601. */
  97602. this.shouldRender = true;
  97603. /**
  97604. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  97605. */
  97606. this.onlyCheckPointerDownEvents = true;
  97607. /**
  97608. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  97609. */
  97610. this.processAllEvents = false;
  97611. /**
  97612. * Observable raised when the pointer move from the utility layer scene to the main scene
  97613. */
  97614. this.onPointerOutObservable = new BABYLON.Observable();
  97615. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  97616. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  97617. this.utilityLayerScene.useRightHandedSystem = originalScene.useRightHandedSystem;
  97618. this.utilityLayerScene._allowPostProcessClearColor = false;
  97619. originalScene.getEngine().scenes.pop();
  97620. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  97621. this.utilityLayerScene.detachControl();
  97622. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  97623. if (!_this.processAllEvents) {
  97624. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  97625. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  97626. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  97627. return;
  97628. }
  97629. }
  97630. var pointerEvent = (prePointerInfo.event);
  97631. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  97632. _this._pointerCaptures[pointerEvent.pointerId] = false;
  97633. return;
  97634. }
  97635. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  97636. if (!prePointerInfo.ray && utilityScenePick) {
  97637. prePointerInfo.ray = utilityScenePick.ray;
  97638. }
  97639. // always fire the prepointer oversvable
  97640. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  97641. // allow every non pointer down event to flow to the utility layer
  97642. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  97643. if (!prePointerInfo.skipOnPointerObservable) {
  97644. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  97645. }
  97646. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  97647. _this._pointerCaptures[pointerEvent.pointerId] = false;
  97648. }
  97649. return;
  97650. }
  97651. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  97652. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  97653. if (utilityScenePick && utilityScenePick.hit) {
  97654. if (!prePointerInfo.skipOnPointerObservable) {
  97655. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  97656. }
  97657. prePointerInfo.skipOnPointerObservable = true;
  97658. }
  97659. }
  97660. else {
  97661. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  97662. var pointerEvent_1 = (prePointerInfo.event);
  97663. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  97664. if (originalScenePick && utilityScenePick) {
  97665. // No pick in utility scene
  97666. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  97667. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  97668. // We touched an utility mesh present in the main scene
  97669. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  97670. prePointerInfo.skipOnPointerObservable = true;
  97671. }
  97672. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  97673. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  97674. }
  97675. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  97676. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  97677. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  97678. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  97679. }
  97680. }
  97681. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  97682. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  97683. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  97684. // If a previous utility layer set this, do not unset this
  97685. if (!prePointerInfo.skipOnPointerObservable) {
  97686. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  97687. }
  97688. }
  97689. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  97690. // We have a pick in both scenes but main is closer than utility
  97691. // We touched an utility mesh present in the main scene
  97692. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  97693. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  97694. prePointerInfo.skipOnPointerObservable = true;
  97695. }
  97696. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  97697. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  97698. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  97699. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  97700. }
  97701. }
  97702. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  97703. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  97704. }
  97705. }
  97706. }
  97707. });
  97708. // Render directly on top of existing scene without clearing
  97709. this.utilityLayerScene.autoClear = false;
  97710. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  97711. if (_this.shouldRender) {
  97712. _this.render();
  97713. }
  97714. });
  97715. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  97716. _this.dispose();
  97717. });
  97718. this._updateCamera();
  97719. }
  97720. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  97721. /**
  97722. * 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)
  97723. */
  97724. get: function () {
  97725. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  97726. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  97727. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  97728. UtilityLayerRenderer._DefaultUtilityLayer = null;
  97729. });
  97730. }
  97731. return UtilityLayerRenderer._DefaultUtilityLayer;
  97732. },
  97733. enumerable: true,
  97734. configurable: true
  97735. });
  97736. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  97737. /**
  97738. * 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)
  97739. */
  97740. get: function () {
  97741. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  97742. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  97743. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  97744. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  97745. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  97746. });
  97747. }
  97748. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  97749. },
  97750. enumerable: true,
  97751. configurable: true
  97752. });
  97753. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  97754. if (!prePointerInfo.skipOnPointerObservable) {
  97755. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  97756. this._lastPointerEvents[pointerEvent.pointerId] = true;
  97757. }
  97758. };
  97759. /**
  97760. * Renders the utility layers scene on top of the original scene
  97761. */
  97762. UtilityLayerRenderer.prototype.render = function () {
  97763. this._updateCamera();
  97764. if (this.utilityLayerScene.activeCamera) {
  97765. // Set the camera's scene to utility layers scene
  97766. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  97767. var camera = this.utilityLayerScene.activeCamera;
  97768. camera._scene = this.utilityLayerScene;
  97769. if (camera.leftCamera) {
  97770. camera.leftCamera._scene = this.utilityLayerScene;
  97771. }
  97772. if (camera.rightCamera) {
  97773. camera.rightCamera._scene = this.utilityLayerScene;
  97774. }
  97775. this.utilityLayerScene.render(false);
  97776. // Reset camera's scene back to original
  97777. camera._scene = oldScene;
  97778. if (camera.leftCamera) {
  97779. camera.leftCamera._scene = oldScene;
  97780. }
  97781. if (camera.rightCamera) {
  97782. camera.rightCamera._scene = oldScene;
  97783. }
  97784. }
  97785. };
  97786. /**
  97787. * Disposes of the renderer
  97788. */
  97789. UtilityLayerRenderer.prototype.dispose = function () {
  97790. this.onPointerOutObservable.clear();
  97791. if (this._afterRenderObserver) {
  97792. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  97793. }
  97794. if (this._sceneDisposeObserver) {
  97795. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  97796. }
  97797. if (this._originalPointerObserver) {
  97798. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  97799. }
  97800. this.utilityLayerScene.dispose();
  97801. };
  97802. UtilityLayerRenderer.prototype._updateCamera = function () {
  97803. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  97804. };
  97805. UtilityLayerRenderer._DefaultUtilityLayer = null;
  97806. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  97807. return UtilityLayerRenderer;
  97808. }());
  97809. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  97810. })(BABYLON || (BABYLON = {}));
  97811. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  97812. //# sourceMappingURL=babylon.behavior.js.map
  97813. var BABYLON;
  97814. (function (BABYLON) {
  97815. /**
  97816. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  97817. */
  97818. var PointerDragBehavior = /** @class */ (function () {
  97819. /**
  97820. * Creates a pointer drag behavior that can be attached to a mesh
  97821. * @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)
  97822. */
  97823. function PointerDragBehavior(options) {
  97824. /**
  97825. * 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)
  97826. */
  97827. this.maxDragAngle = 0;
  97828. /**
  97829. * @hidden
  97830. */
  97831. this._useAlternatePickedPointAboveMaxDragAngle = false;
  97832. /**
  97833. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  97834. */
  97835. this.currentDraggingPointerID = -1;
  97836. /**
  97837. * If the behavior is currently in a dragging state
  97838. */
  97839. this.dragging = false;
  97840. /**
  97841. * 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)
  97842. */
  97843. this.dragDeltaRatio = 0.2;
  97844. /**
  97845. * If the drag plane orientation should be updated during the dragging (Default: true)
  97846. */
  97847. this.updateDragPlane = true;
  97848. // Debug mode will display drag planes to help visualize behavior
  97849. this._debugMode = false;
  97850. this._moving = false;
  97851. /**
  97852. * Fires each time the attached mesh is dragged with the pointer
  97853. * * delta between last drag position and current drag position in world space
  97854. * * dragDistance along the drag axis
  97855. * * dragPlaneNormal normal of the current drag plane used during the drag
  97856. * * dragPlanePoint in world space where the drag intersects the drag plane
  97857. */
  97858. this.onDragObservable = new BABYLON.Observable();
  97859. /**
  97860. * Fires each time a drag begins (eg. mouse down on mesh)
  97861. */
  97862. this.onDragStartObservable = new BABYLON.Observable();
  97863. /**
  97864. * Fires each time a drag ends (eg. mouse release after drag)
  97865. */
  97866. this.onDragEndObservable = new BABYLON.Observable();
  97867. /**
  97868. * If the attached mesh should be moved when dragged
  97869. */
  97870. this.moveAttached = true;
  97871. /**
  97872. * If the drag behavior will react to drag events (Default: true)
  97873. */
  97874. this.enabled = true;
  97875. /**
  97876. * If camera controls should be detached during the drag
  97877. */
  97878. this.detachCameraControls = true;
  97879. /**
  97880. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  97881. */
  97882. this.useObjectOrienationForDragging = true;
  97883. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  97884. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  97885. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  97886. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  97887. this._attachedElement = null;
  97888. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  97889. this._lastPointerRay = {};
  97890. this._dragDelta = new BABYLON.Vector3();
  97891. // Variables to avoid instantiation in the below method
  97892. this._pointA = new BABYLON.Vector3(0, 0, 0);
  97893. this._pointB = new BABYLON.Vector3(0, 0, 0);
  97894. this._pointC = new BABYLON.Vector3(0, 0, 0);
  97895. this._lineA = new BABYLON.Vector3(0, 0, 0);
  97896. this._lineB = new BABYLON.Vector3(0, 0, 0);
  97897. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  97898. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  97899. this._options = options ? options : {};
  97900. var optionCount = 0;
  97901. if (this._options.dragAxis) {
  97902. optionCount++;
  97903. }
  97904. if (this._options.dragPlaneNormal) {
  97905. optionCount++;
  97906. }
  97907. if (optionCount > 1) {
  97908. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  97909. }
  97910. }
  97911. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  97912. /**
  97913. * The name of the behavior
  97914. */
  97915. get: function () {
  97916. return "PointerDrag";
  97917. },
  97918. enumerable: true,
  97919. configurable: true
  97920. });
  97921. /**
  97922. * Initializes the behavior
  97923. */
  97924. PointerDragBehavior.prototype.init = function () { };
  97925. /**
  97926. * Attaches the drag behavior the passed in mesh
  97927. * @param ownerNode The mesh that will be dragged around once attached
  97928. */
  97929. PointerDragBehavior.prototype.attach = function (ownerNode) {
  97930. var _this = this;
  97931. this._scene = ownerNode.getScene();
  97932. this._attachedNode = ownerNode;
  97933. // Initialize drag plane to not interfere with existing scene
  97934. if (!PointerDragBehavior._planeScene) {
  97935. if (this._debugMode) {
  97936. PointerDragBehavior._planeScene = this._scene;
  97937. }
  97938. else {
  97939. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  97940. PointerDragBehavior._planeScene.detachControl();
  97941. this._scene.getEngine().scenes.pop();
  97942. this._scene.onDisposeObservable.addOnce(function () {
  97943. PointerDragBehavior._planeScene.dispose();
  97944. PointerDragBehavior._planeScene = null;
  97945. });
  97946. }
  97947. }
  97948. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  97949. // State of the drag
  97950. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  97951. var pickPredicate = function (m) {
  97952. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  97953. };
  97954. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  97955. if (!_this.enabled) {
  97956. return;
  97957. }
  97958. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  97959. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  97960. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  97961. }
  97962. }
  97963. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  97964. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  97965. _this.releaseDrag();
  97966. }
  97967. }
  97968. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  97969. var pointerId = pointerInfo.event.pointerId;
  97970. // If drag was started with anyMouseID specified, set pointerID to the next mouse that moved
  97971. if (_this.currentDraggingPointerID === PointerDragBehavior._AnyMouseID && pointerId !== PointerDragBehavior._AnyMouseID && pointerInfo.event.pointerType == "mouse") {
  97972. if (_this._lastPointerRay[_this.currentDraggingPointerID]) {
  97973. _this._lastPointerRay[pointerId] = _this._lastPointerRay[_this.currentDraggingPointerID];
  97974. delete _this._lastPointerRay[_this.currentDraggingPointerID];
  97975. }
  97976. _this.currentDraggingPointerID = pointerId;
  97977. }
  97978. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  97979. if (!_this._lastPointerRay[pointerId]) {
  97980. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  97981. }
  97982. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  97983. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  97984. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  97985. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  97986. _this._moveDrag(pointerInfo.pickInfo.ray);
  97987. }
  97988. }
  97989. }
  97990. });
  97991. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  97992. if (_this._moving && _this.moveAttached) {
  97993. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  97994. // Slowly move mesh to avoid jitter
  97995. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  97996. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  97997. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  97998. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  97999. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  98000. }
  98001. });
  98002. };
  98003. /**
  98004. * Force relase the drag action by code.
  98005. */
  98006. PointerDragBehavior.prototype.releaseDrag = function () {
  98007. this.dragging = false;
  98008. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  98009. this.currentDraggingPointerID = -1;
  98010. this._moving = false;
  98011. // Reattach camera controls
  98012. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  98013. this._scene.activeCamera.attachControl(this._attachedElement, true);
  98014. }
  98015. };
  98016. /**
  98017. * Simulates the start of a pointer drag event on the behavior
  98018. * @param pointerId pointerID of the pointer that should be simulated (Default: Any mouse pointer ID)
  98019. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  98020. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  98021. */
  98022. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  98023. if (pointerId === void 0) { pointerId = PointerDragBehavior._AnyMouseID; }
  98024. this._startDrag(pointerId, fromRay, startPickedPoint);
  98025. var lastRay = this._lastPointerRay[pointerId];
  98026. if (pointerId === PointerDragBehavior._AnyMouseID) {
  98027. lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]];
  98028. }
  98029. if (lastRay) {
  98030. // if there was a last pointer ray drag the object there
  98031. this._moveDrag(lastRay);
  98032. }
  98033. };
  98034. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  98035. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  98036. return;
  98037. }
  98038. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  98039. // Create start ray from the camera to the object
  98040. if (fromRay) {
  98041. this._startDragRay.direction.copyFrom(fromRay.direction);
  98042. this._startDragRay.origin.copyFrom(fromRay.origin);
  98043. }
  98044. else {
  98045. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  98046. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  98047. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  98048. }
  98049. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  98050. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  98051. if (pickedPoint) {
  98052. this.dragging = true;
  98053. this.currentDraggingPointerID = pointerId;
  98054. this.lastDragPosition.copyFrom(pickedPoint);
  98055. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  98056. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  98057. // Detatch camera controls
  98058. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  98059. if (this._scene.activeCamera.inputs.attachedElement) {
  98060. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  98061. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  98062. }
  98063. else {
  98064. this._attachedElement = null;
  98065. }
  98066. }
  98067. }
  98068. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  98069. };
  98070. PointerDragBehavior.prototype._moveDrag = function (ray) {
  98071. this._moving = true;
  98072. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  98073. if (pickedPoint) {
  98074. if (this.updateDragPlane) {
  98075. this._updateDragPlanePosition(ray, pickedPoint);
  98076. }
  98077. var dragLength = 0;
  98078. // depending on the drag mode option drag accordingly
  98079. if (this._options.dragAxis) {
  98080. // Convert local drag axis to world
  98081. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  98082. // Project delta drag from the drag plane onto the drag axis
  98083. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  98084. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  98085. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  98086. }
  98087. else {
  98088. dragLength = this._dragDelta.length();
  98089. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  98090. }
  98091. this._targetPosition.addInPlace(this._dragDelta);
  98092. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  98093. this.lastDragPosition.copyFrom(pickedPoint);
  98094. }
  98095. };
  98096. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  98097. var _this = this;
  98098. if (!ray) {
  98099. return null;
  98100. }
  98101. // Calculate angle between plane normal and ray
  98102. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  98103. // Correct if ray is casted from oposite side
  98104. if (angle > Math.PI / 2) {
  98105. angle = Math.PI - angle;
  98106. }
  98107. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  98108. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  98109. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  98110. // Invert ray direction along the towards object axis
  98111. this._tmpVector.copyFrom(ray.direction);
  98112. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  98113. this._alternatePickedPoint.normalize();
  98114. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  98115. this._tmpVector.addInPlace(this._alternatePickedPoint);
  98116. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  98117. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  98118. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  98119. this._alternatePickedPoint.addInPlace(this._tmpVector);
  98120. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  98121. return this._alternatePickedPoint;
  98122. }
  98123. else {
  98124. return null;
  98125. }
  98126. }
  98127. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  98128. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  98129. return pickResult.pickedPoint;
  98130. }
  98131. else {
  98132. return null;
  98133. }
  98134. };
  98135. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  98136. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  98137. this._pointA.copyFrom(dragPlanePosition);
  98138. if (this._options.dragAxis) {
  98139. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  98140. // Calculate plane normal in direction of camera but perpendicular to drag axis
  98141. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  98142. ray.origin.subtractToRef(this._pointA, this._pointC);
  98143. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  98144. // Get perpendicular line from direction to camera and drag axis
  98145. this._pointB.subtractToRef(this._pointA, this._lineA);
  98146. this._pointC.subtractToRef(this._pointA, this._lineB);
  98147. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  98148. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  98149. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  98150. this._lookAt.normalize();
  98151. this._dragPlane.position.copyFrom(this._pointA);
  98152. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  98153. this._dragPlane.lookAt(this._lookAt);
  98154. }
  98155. else if (this._options.dragPlaneNormal) {
  98156. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  98157. this._dragPlane.position.copyFrom(this._pointA);
  98158. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  98159. this._dragPlane.lookAt(this._lookAt);
  98160. }
  98161. else {
  98162. this._dragPlane.position.copyFrom(this._pointA);
  98163. this._dragPlane.lookAt(ray.origin);
  98164. }
  98165. this._dragPlane.computeWorldMatrix(true);
  98166. };
  98167. /**
  98168. * Detaches the behavior from the mesh
  98169. */
  98170. PointerDragBehavior.prototype.detach = function () {
  98171. if (this._pointerObserver) {
  98172. this._scene.onPointerObservable.remove(this._pointerObserver);
  98173. }
  98174. if (this._beforeRenderObserver) {
  98175. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  98176. }
  98177. };
  98178. PointerDragBehavior._AnyMouseID = -2;
  98179. return PointerDragBehavior;
  98180. }());
  98181. BABYLON.PointerDragBehavior = PointerDragBehavior;
  98182. })(BABYLON || (BABYLON = {}));
  98183. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  98184. var BABYLON;
  98185. (function (BABYLON) {
  98186. /**
  98187. * A behavior that when attached to a mesh will allow the mesh to be scaled
  98188. */
  98189. var MultiPointerScaleBehavior = /** @class */ (function () {
  98190. /**
  98191. * Instantiate a new behavior that when attached to a mesh will allow the mesh to be scaled
  98192. */
  98193. function MultiPointerScaleBehavior() {
  98194. this._startDistance = 0;
  98195. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  98196. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  98197. this._sceneRenderObserver = null;
  98198. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  98199. this._dragBehaviorA.moveAttached = false;
  98200. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  98201. this._dragBehaviorB.moveAttached = false;
  98202. }
  98203. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  98204. /**
  98205. * The name of the behavior
  98206. */
  98207. get: function () {
  98208. return "MultiPointerScale";
  98209. },
  98210. enumerable: true,
  98211. configurable: true
  98212. });
  98213. /**
  98214. * Initializes the behavior
  98215. */
  98216. MultiPointerScaleBehavior.prototype.init = function () { };
  98217. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  98218. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  98219. };
  98220. /**
  98221. * Attaches the scale behavior the passed in mesh
  98222. * @param ownerNode The mesh that will be scaled around once attached
  98223. */
  98224. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  98225. var _this = this;
  98226. this._ownerNode = ownerNode;
  98227. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  98228. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  98229. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  98230. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  98231. _this._dragBehaviorA.releaseDrag();
  98232. }
  98233. else {
  98234. _this._initialScale.copyFrom(ownerNode.scaling);
  98235. _this._startDistance = _this._getCurrentDistance();
  98236. }
  98237. }
  98238. });
  98239. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  98240. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  98241. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  98242. _this._dragBehaviorB.releaseDrag();
  98243. }
  98244. else {
  98245. _this._initialScale.copyFrom(ownerNode.scaling);
  98246. _this._startDistance = _this._getCurrentDistance();
  98247. }
  98248. }
  98249. });
  98250. // Once both drag behaviors are active scale based on the distance between the two pointers
  98251. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  98252. behavior.onDragObservable.add(function () {
  98253. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  98254. var ratio = _this._getCurrentDistance() / _this._startDistance;
  98255. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  98256. }
  98257. });
  98258. });
  98259. ownerNode.addBehavior(this._dragBehaviorA);
  98260. ownerNode.addBehavior(this._dragBehaviorB);
  98261. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  98262. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  98263. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  98264. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  98265. if (change.length() > 0.01) {
  98266. ownerNode.scaling.addInPlace(change);
  98267. }
  98268. }
  98269. });
  98270. };
  98271. /**
  98272. * Detaches the behavior from the mesh
  98273. */
  98274. MultiPointerScaleBehavior.prototype.detach = function () {
  98275. var _this = this;
  98276. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  98277. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  98278. behavior.onDragStartObservable.clear();
  98279. behavior.onDragObservable.clear();
  98280. _this._ownerNode.removeBehavior(behavior);
  98281. });
  98282. };
  98283. return MultiPointerScaleBehavior;
  98284. }());
  98285. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  98286. })(BABYLON || (BABYLON = {}));
  98287. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  98288. var BABYLON;
  98289. (function (BABYLON) {
  98290. /**
  98291. * 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
  98292. */
  98293. var SixDofDragBehavior = /** @class */ (function () {
  98294. /**
  98295. * Instantiates 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
  98296. */
  98297. function SixDofDragBehavior() {
  98298. this._sceneRenderObserver = null;
  98299. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  98300. this._moving = false;
  98301. this._startingOrientation = new BABYLON.Quaternion();
  98302. /**
  98303. * 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)
  98304. */
  98305. this.zDragFactor = 3;
  98306. /**
  98307. * If the behavior is currently in a dragging state
  98308. */
  98309. this.dragging = false;
  98310. /**
  98311. * 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)
  98312. */
  98313. this.dragDeltaRatio = 0.2;
  98314. /**
  98315. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  98316. */
  98317. this.currentDraggingPointerID = -1;
  98318. /**
  98319. * If camera controls should be detached during the drag
  98320. */
  98321. this.detachCameraControls = true;
  98322. /**
  98323. * Fires each time a drag starts
  98324. */
  98325. this.onDragStartObservable = new BABYLON.Observable();
  98326. /**
  98327. * Fires each time a drag ends (eg. mouse release after drag)
  98328. */
  98329. this.onDragEndObservable = new BABYLON.Observable();
  98330. }
  98331. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  98332. /**
  98333. * The name of the behavior
  98334. */
  98335. get: function () {
  98336. return "SixDofDrag";
  98337. },
  98338. enumerable: true,
  98339. configurable: true
  98340. });
  98341. /**
  98342. * Initializes the behavior
  98343. */
  98344. SixDofDragBehavior.prototype.init = function () { };
  98345. /**
  98346. * Attaches the scale behavior the passed in mesh
  98347. * @param ownerNode The mesh that will be scaled around once attached
  98348. */
  98349. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  98350. var _this = this;
  98351. this._ownerNode = ownerNode;
  98352. this._scene = this._ownerNode.getScene();
  98353. if (!SixDofDragBehavior._virtualScene) {
  98354. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  98355. this._scene.getEngine().scenes.pop();
  98356. }
  98357. var pickedMesh = null;
  98358. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  98359. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  98360. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  98361. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  98362. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  98363. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  98364. var pickPredicate = function (m) {
  98365. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  98366. };
  98367. var attachedElement = null;
  98368. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  98369. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  98370. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  98371. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  98372. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  98373. }
  98374. pickedMesh = _this._ownerNode;
  98375. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  98376. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  98377. // Set position and orientation of the controller
  98378. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  98379. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  98380. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  98381. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  98382. pickedMesh.computeWorldMatrix();
  98383. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  98384. if (!pickedMesh.rotationQuaternion) {
  98385. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  98386. }
  98387. var oldParent = pickedMesh.parent;
  98388. pickedMesh.setParent(null);
  98389. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  98390. pickedMesh.setParent(oldParent);
  98391. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  98392. // Update state
  98393. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  98394. _this.dragging = true;
  98395. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  98396. // Detatch camera controls
  98397. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  98398. if (_this._scene.activeCamera.inputs.attachedElement) {
  98399. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  98400. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  98401. }
  98402. else {
  98403. attachedElement = null;
  98404. }
  98405. }
  98406. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  98407. _this.onDragStartObservable.notifyObservers({});
  98408. }
  98409. }
  98410. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  98411. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  98412. _this.dragging = false;
  98413. _this._moving = false;
  98414. _this.currentDraggingPointerID = -1;
  98415. pickedMesh = null;
  98416. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  98417. // Reattach camera controls
  98418. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  98419. _this._scene.activeCamera.attachControl(attachedElement, true);
  98420. }
  98421. _this.onDragEndObservable.notifyObservers({});
  98422. }
  98423. }
  98424. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  98425. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  98426. var zDragFactor = _this.zDragFactor;
  98427. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  98428. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  98429. zDragFactor = 0;
  98430. }
  98431. // Calculate controller drag distance in controller space
  98432. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  98433. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  98434. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  98435. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  98436. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  98437. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  98438. if (_this._virtualDragMesh.position.z < 0) {
  98439. _this._virtualDragMesh.position.z = 0;
  98440. }
  98441. // Update the controller position
  98442. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  98443. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  98444. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  98445. // Move the virtualObjectsPosition into the picked mesh's space if needed
  98446. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  98447. if (pickedMesh.parent) {
  98448. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  98449. }
  98450. if (!_this._moving) {
  98451. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  98452. }
  98453. _this._moving = true;
  98454. }
  98455. }
  98456. });
  98457. var tmpQuaternion = new BABYLON.Quaternion();
  98458. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  98459. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  98460. if (_this.dragging && _this._moving && pickedMesh) {
  98461. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  98462. // Slowly move mesh to avoid jitter
  98463. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  98464. // Get change in rotation
  98465. tmpQuaternion.copyFrom(_this._startingOrientation);
  98466. tmpQuaternion.x = -tmpQuaternion.x;
  98467. tmpQuaternion.y = -tmpQuaternion.y;
  98468. tmpQuaternion.z = -tmpQuaternion.z;
  98469. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  98470. // Convert change in rotation to only y axis rotation
  98471. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  98472. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  98473. // Slowly move mesh to avoid jitter
  98474. var oldParent = pickedMesh.parent;
  98475. pickedMesh.setParent(null);
  98476. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  98477. pickedMesh.setParent(oldParent);
  98478. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  98479. }
  98480. });
  98481. };
  98482. /**
  98483. * Detaches the behavior from the mesh
  98484. */
  98485. SixDofDragBehavior.prototype.detach = function () {
  98486. if (this._scene) {
  98487. this._scene.onPointerObservable.remove(this._pointerObserver);
  98488. }
  98489. if (this._ownerNode) {
  98490. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  98491. }
  98492. if (this._virtualOriginMesh) {
  98493. this._virtualOriginMesh.dispose();
  98494. }
  98495. if (this._virtualDragMesh) {
  98496. this._virtualDragMesh.dispose();
  98497. }
  98498. this.onDragEndObservable.clear();
  98499. this.onDragStartObservable.clear();
  98500. };
  98501. return SixDofDragBehavior;
  98502. }());
  98503. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  98504. })(BABYLON || (BABYLON = {}));
  98505. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  98506. var BABYLON;
  98507. (function (BABYLON) {
  98508. /**
  98509. * @hidden
  98510. */
  98511. var FaceDirectionInfo = /** @class */ (function () {
  98512. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  98513. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  98514. if (diff === void 0) { diff = 0; }
  98515. if (ignore === void 0) { ignore = false; }
  98516. this.direction = direction;
  98517. this.rotatedDirection = rotatedDirection;
  98518. this.diff = diff;
  98519. this.ignore = ignore;
  98520. }
  98521. return FaceDirectionInfo;
  98522. }());
  98523. /**
  98524. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  98525. */
  98526. var AttachToBoxBehavior = /** @class */ (function () {
  98527. /**
  98528. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  98529. * @param ui The transform node that should be attched to the mesh
  98530. */
  98531. function AttachToBoxBehavior(ui) {
  98532. this.ui = ui;
  98533. /**
  98534. * The name of the behavior
  98535. */
  98536. this.name = "AttachToBoxBehavior";
  98537. /**
  98538. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  98539. */
  98540. this.distanceAwayFromFace = 0.15;
  98541. /**
  98542. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  98543. */
  98544. this.distanceAwayFromBottomOfFace = 0.15;
  98545. 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))];
  98546. this._tmpMatrix = new BABYLON.Matrix();
  98547. this._tmpVector = new BABYLON.Vector3();
  98548. this._zeroVector = BABYLON.Vector3.Zero();
  98549. this._lookAtTmpMatrix = new BABYLON.Matrix();
  98550. /* Does nothing */
  98551. }
  98552. /**
  98553. * Initializes the behavior
  98554. */
  98555. AttachToBoxBehavior.prototype.init = function () {
  98556. /* Does nothing */
  98557. };
  98558. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  98559. var _this = this;
  98560. // Go over each face and calculate the angle between the face's normal and targetDirection
  98561. this._faceVectors.forEach(function (v) {
  98562. if (!_this._target.rotationQuaternion) {
  98563. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  98564. }
  98565. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  98566. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  98567. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  98568. });
  98569. // Return the face information of the one with the normal closeset to target direction
  98570. return this._faceVectors.reduce(function (min, p) {
  98571. if (min.ignore) {
  98572. return p;
  98573. }
  98574. else if (p.ignore) {
  98575. return min;
  98576. }
  98577. else {
  98578. return min.diff < p.diff ? min : p;
  98579. }
  98580. }, this._faceVectors[0]);
  98581. };
  98582. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  98583. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  98584. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  98585. this._lookAtTmpMatrix.invert();
  98586. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  98587. };
  98588. /**
  98589. * Attaches the AttachToBoxBehavior to the passed in mesh
  98590. * @param target The mesh that the specified node will be attached to
  98591. */
  98592. AttachToBoxBehavior.prototype.attach = function (target) {
  98593. var _this = this;
  98594. this._target = target;
  98595. this._scene = this._target.getScene();
  98596. // Every frame, update the app bars position
  98597. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  98598. if (!_this._scene.activeCamera) {
  98599. return;
  98600. }
  98601. // Find the face closest to the cameras position
  98602. var cameraPos = _this._scene.activeCamera.position;
  98603. if (_this._scene.activeCamera.devicePosition) {
  98604. cameraPos = _this._scene.activeCamera.devicePosition;
  98605. }
  98606. var facing = _this._closestFace(cameraPos.subtract(target.position));
  98607. if (_this._scene.activeCamera.leftCamera) {
  98608. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  98609. }
  98610. else {
  98611. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  98612. }
  98613. // Get camera up direction
  98614. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  98615. // Ignore faces to not select a parrelel face for the up vector of the UI
  98616. _this._faceVectors.forEach(function (v) {
  98617. if (facing.direction.x && v.direction.x) {
  98618. v.ignore = true;
  98619. }
  98620. if (facing.direction.y && v.direction.y) {
  98621. v.ignore = true;
  98622. }
  98623. if (facing.direction.z && v.direction.z) {
  98624. v.ignore = true;
  98625. }
  98626. });
  98627. var facingUp = _this._closestFace(_this._tmpVector);
  98628. // Unignore faces
  98629. _this._faceVectors.forEach(function (v) {
  98630. v.ignore = false;
  98631. });
  98632. // Position the app bar on that face
  98633. _this.ui.position.copyFrom(target.position);
  98634. if (facing.direction.x) {
  98635. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  98636. _this.ui.position.addInPlace(_this._tmpVector);
  98637. }
  98638. if (facing.direction.y) {
  98639. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  98640. _this.ui.position.addInPlace(_this._tmpVector);
  98641. }
  98642. if (facing.direction.z) {
  98643. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  98644. _this.ui.position.addInPlace(_this._tmpVector);
  98645. }
  98646. // Rotate to be oriented properly to the camera
  98647. if (!_this.ui.rotationQuaternion) {
  98648. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  98649. }
  98650. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  98651. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  98652. // Place ui the correct distance from the bottom of the mesh
  98653. if (facingUp.direction.x) {
  98654. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  98655. }
  98656. if (facingUp.direction.y) {
  98657. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  98658. }
  98659. if (facingUp.direction.z) {
  98660. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  98661. }
  98662. _this.ui.position.addInPlace(_this._tmpVector);
  98663. });
  98664. };
  98665. /**
  98666. * Detaches the behavior from the mesh
  98667. */
  98668. AttachToBoxBehavior.prototype.detach = function () {
  98669. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  98670. };
  98671. return AttachToBoxBehavior;
  98672. }());
  98673. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  98674. })(BABYLON || (BABYLON = {}));
  98675. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  98676. var BABYLON;
  98677. (function (BABYLON) {
  98678. /**
  98679. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  98680. */
  98681. var FadeInOutBehavior = /** @class */ (function () {
  98682. /**
  98683. * Instatiates the FadeInOutBehavior
  98684. */
  98685. function FadeInOutBehavior() {
  98686. var _this = this;
  98687. /**
  98688. * Time in milliseconds to delay before fading in (Default: 0)
  98689. */
  98690. this.delay = 0;
  98691. /**
  98692. * Time in milliseconds for the mesh to fade in (Default: 300)
  98693. */
  98694. this.fadeInTime = 300;
  98695. this._millisecondsPerFrame = 1000 / 60;
  98696. this._hovered = false;
  98697. this._hoverValue = 0;
  98698. this._ownerNode = null;
  98699. this._update = function () {
  98700. if (_this._ownerNode) {
  98701. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  98702. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  98703. if (_this._ownerNode.visibility > 1) {
  98704. _this._setAllVisibility(_this._ownerNode, 1);
  98705. _this._hoverValue = _this.fadeInTime + _this.delay;
  98706. return;
  98707. }
  98708. else if (_this._ownerNode.visibility < 0) {
  98709. _this._setAllVisibility(_this._ownerNode, 0);
  98710. if (_this._hoverValue < 0) {
  98711. _this._hoverValue = 0;
  98712. return;
  98713. }
  98714. }
  98715. setTimeout(_this._update, _this._millisecondsPerFrame);
  98716. }
  98717. };
  98718. }
  98719. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  98720. /**
  98721. * The name of the behavior
  98722. */
  98723. get: function () {
  98724. return "FadeInOut";
  98725. },
  98726. enumerable: true,
  98727. configurable: true
  98728. });
  98729. /**
  98730. * Initializes the behavior
  98731. */
  98732. FadeInOutBehavior.prototype.init = function () {
  98733. };
  98734. /**
  98735. * Attaches the fade behavior on the passed in mesh
  98736. * @param ownerNode The mesh that will be faded in/out once attached
  98737. */
  98738. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  98739. this._ownerNode = ownerNode;
  98740. this._setAllVisibility(this._ownerNode, 0);
  98741. };
  98742. /**
  98743. * Detaches the behavior from the mesh
  98744. */
  98745. FadeInOutBehavior.prototype.detach = function () {
  98746. this._ownerNode = null;
  98747. };
  98748. /**
  98749. * Triggers the mesh to begin fading in or out
  98750. * @param value if the object should fade in or out (true to fade in)
  98751. */
  98752. FadeInOutBehavior.prototype.fadeIn = function (value) {
  98753. this._hovered = value;
  98754. this._update();
  98755. };
  98756. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  98757. var _this = this;
  98758. mesh.visibility = value;
  98759. mesh.getChildMeshes().forEach(function (c) {
  98760. _this._setAllVisibility(c, value);
  98761. });
  98762. };
  98763. return FadeInOutBehavior;
  98764. }());
  98765. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  98766. })(BABYLON || (BABYLON = {}));
  98767. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  98768. var BABYLON;
  98769. (function (BABYLON) {
  98770. /**
  98771. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  98772. */
  98773. var Gizmo = /** @class */ (function () {
  98774. /**
  98775. * Creates a gizmo
  98776. * @param gizmoLayer The utility layer the gizmo will be added to
  98777. */
  98778. function Gizmo(
  98779. /** The utility layer the gizmo will be added to */
  98780. gizmoLayer) {
  98781. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  98782. var _this = this;
  98783. this.gizmoLayer = gizmoLayer;
  98784. /**
  98785. * Ratio for the scale of the gizmo (Default: 1)
  98786. */
  98787. this.scaleRatio = 1;
  98788. this._tmpMatrix = new BABYLON.Matrix();
  98789. /**
  98790. * If a custom mesh has been set (Default: false)
  98791. */
  98792. this._customMeshSet = false;
  98793. /**
  98794. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  98795. */
  98796. this.updateGizmoRotationToMatchAttachedMesh = true;
  98797. /**
  98798. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  98799. */
  98800. this.updateGizmoPositionToMatchAttachedMesh = true;
  98801. /**
  98802. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  98803. */
  98804. this._updateScale = true;
  98805. this._interactionsEnabled = true;
  98806. this._tempVector = new BABYLON.Vector3();
  98807. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  98808. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  98809. _this._update();
  98810. });
  98811. this.attachedMesh = null;
  98812. }
  98813. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  98814. /**
  98815. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  98816. * * When set, interactions will be enabled
  98817. */
  98818. get: function () {
  98819. return this._attachedMesh;
  98820. },
  98821. set: function (value) {
  98822. this._attachedMesh = value;
  98823. this._rootMesh.setEnabled(value ? true : false);
  98824. this._attachedMeshChanged(value);
  98825. },
  98826. enumerable: true,
  98827. configurable: true
  98828. });
  98829. /**
  98830. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  98831. * @param mesh The mesh to replace the default mesh of the gizmo
  98832. */
  98833. Gizmo.prototype.setCustomMesh = function (mesh) {
  98834. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  98835. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  98836. }
  98837. this._rootMesh.getChildMeshes().forEach(function (c) {
  98838. c.dispose();
  98839. });
  98840. mesh.parent = this._rootMesh;
  98841. this._customMeshSet = true;
  98842. };
  98843. Gizmo.prototype._attachedMeshChanged = function (value) {
  98844. };
  98845. /**
  98846. * @hidden
  98847. * Updates the gizmo to match the attached mesh's position/rotation
  98848. */
  98849. Gizmo.prototype._update = function () {
  98850. if (this.attachedMesh) {
  98851. if (this.updateGizmoRotationToMatchAttachedMesh) {
  98852. if (!this._rootMesh.rotationQuaternion) {
  98853. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  98854. }
  98855. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  98856. this._tempVector.copyFrom(this.attachedMesh.scaling);
  98857. if (this.attachedMesh.scaling.x < 0) {
  98858. this.attachedMesh.scaling.x *= -1;
  98859. }
  98860. if (this.attachedMesh.scaling.y < 0) {
  98861. this.attachedMesh.scaling.y *= -1;
  98862. }
  98863. if (this.attachedMesh.scaling.z < 0) {
  98864. this.attachedMesh.scaling.z *= -1;
  98865. }
  98866. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  98867. this.attachedMesh.scaling.copyFrom(this._tempVector);
  98868. this.attachedMesh.computeWorldMatrix();
  98869. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  98870. }
  98871. else if (this._rootMesh.rotationQuaternion) {
  98872. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  98873. }
  98874. if (this.updateGizmoPositionToMatchAttachedMesh) {
  98875. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  98876. }
  98877. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  98878. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  98879. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  98880. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  98881. }
  98882. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  98883. var dist = this._tempVector.length() * this.scaleRatio;
  98884. this._rootMesh.scaling.set(dist, dist, dist);
  98885. }
  98886. }
  98887. };
  98888. /**
  98889. * Disposes of the gizmo
  98890. */
  98891. Gizmo.prototype.dispose = function () {
  98892. this._rootMesh.dispose();
  98893. if (this._beforeRenderObserver) {
  98894. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  98895. }
  98896. };
  98897. return Gizmo;
  98898. }());
  98899. BABYLON.Gizmo = Gizmo;
  98900. })(BABYLON || (BABYLON = {}));
  98901. //# sourceMappingURL=babylon.gizmo.js.map
  98902. var BABYLON;
  98903. (function (BABYLON) {
  98904. /**
  98905. * Single axis drag gizmo
  98906. */
  98907. var AxisDragGizmo = /** @class */ (function (_super) {
  98908. __extends(AxisDragGizmo, _super);
  98909. /**
  98910. * Creates an AxisDragGizmo
  98911. * @param gizmoLayer The utility layer the gizmo will be added to
  98912. * @param dragAxis The axis which the gizmo will be able to drag on
  98913. * @param color The color of the gizmo
  98914. */
  98915. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  98916. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  98917. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  98918. var _this = _super.call(this, gizmoLayer) || this;
  98919. _this._pointerObserver = null;
  98920. /**
  98921. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  98922. */
  98923. _this.snapDistance = 0;
  98924. /**
  98925. * Event that fires each time the gizmo snaps to a new location.
  98926. * * snapDistance is the the change in distance
  98927. */
  98928. _this.onSnapObservable = new BABYLON.Observable();
  98929. // Create Material
  98930. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  98931. coloredMaterial.disableLighting = true;
  98932. coloredMaterial.emissiveColor = color;
  98933. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  98934. hoverMaterial.disableLighting = true;
  98935. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  98936. // Build mesh on root node
  98937. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  98938. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  98939. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  98940. arrowTail.color = coloredMaterial.emissiveColor;
  98941. arrow.addChild(arrowMesh);
  98942. arrow.addChild(arrowTail);
  98943. // Position arrow pointing in its drag axis
  98944. arrowMesh.scaling.scaleInPlace(0.05);
  98945. arrowMesh.material = coloredMaterial;
  98946. arrowMesh.rotation.x = Math.PI / 2;
  98947. arrowMesh.position.z += 0.3;
  98948. arrowTail.scaling.scaleInPlace(0.26);
  98949. arrowTail.rotation.x = Math.PI / 2;
  98950. arrowTail.material = coloredMaterial;
  98951. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  98952. arrow.scaling.scaleInPlace(1 / 3);
  98953. _this._rootMesh.addChild(arrow);
  98954. var currentSnapDragDistance = 0;
  98955. var tmpVector = new BABYLON.Vector3();
  98956. var tmpSnapEvent = { snapDistance: 0 };
  98957. // Add drag behavior to handle events when the gizmo is dragged
  98958. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  98959. _this.dragBehavior.moveAttached = false;
  98960. _this._rootMesh.addBehavior(_this.dragBehavior);
  98961. var localDelta = new BABYLON.Vector3();
  98962. var tmpMatrix = new BABYLON.Matrix();
  98963. _this.dragBehavior.onDragObservable.add(function (event) {
  98964. if (_this.attachedMesh) {
  98965. // Convert delta to local translation if it has a parent
  98966. if (_this.attachedMesh.parent) {
  98967. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  98968. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  98969. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  98970. }
  98971. else {
  98972. localDelta.copyFrom(event.delta);
  98973. }
  98974. // Snapping logic
  98975. if (_this.snapDistance == 0) {
  98976. _this.attachedMesh.position.addInPlace(localDelta);
  98977. }
  98978. else {
  98979. currentSnapDragDistance += event.dragDistance;
  98980. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  98981. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  98982. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  98983. localDelta.normalizeToRef(tmpVector);
  98984. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  98985. _this.attachedMesh.position.addInPlace(tmpVector);
  98986. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  98987. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  98988. }
  98989. }
  98990. }
  98991. });
  98992. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  98993. if (_this._customMeshSet) {
  98994. return;
  98995. }
  98996. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  98997. var material = isHovered ? hoverMaterial : coloredMaterial;
  98998. _this._rootMesh.getChildMeshes().forEach(function (m) {
  98999. m.material = material;
  99000. if (m.color) {
  99001. m.color = material.emissiveColor;
  99002. }
  99003. });
  99004. });
  99005. return _this;
  99006. }
  99007. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  99008. if (this.dragBehavior) {
  99009. this.dragBehavior.enabled = value ? true : false;
  99010. }
  99011. };
  99012. /**
  99013. * Disposes of the gizmo
  99014. */
  99015. AxisDragGizmo.prototype.dispose = function () {
  99016. this.onSnapObservable.clear();
  99017. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  99018. this.dragBehavior.detach();
  99019. _super.prototype.dispose.call(this);
  99020. };
  99021. return AxisDragGizmo;
  99022. }(BABYLON.Gizmo));
  99023. BABYLON.AxisDragGizmo = AxisDragGizmo;
  99024. })(BABYLON || (BABYLON = {}));
  99025. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  99026. var BABYLON;
  99027. (function (BABYLON) {
  99028. /**
  99029. * Single axis scale gizmo
  99030. */
  99031. var AxisScaleGizmo = /** @class */ (function (_super) {
  99032. __extends(AxisScaleGizmo, _super);
  99033. /**
  99034. * Creates an AxisScaleGizmo
  99035. * @param gizmoLayer The utility layer the gizmo will be added to
  99036. * @param dragAxis The axis which the gizmo will be able to scale on
  99037. * @param color The color of the gizmo
  99038. */
  99039. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  99040. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  99041. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  99042. var _this = _super.call(this, gizmoLayer) || this;
  99043. _this._pointerObserver = null;
  99044. /**
  99045. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  99046. */
  99047. _this.snapDistance = 0;
  99048. /**
  99049. * Event that fires each time the gizmo snaps to a new location.
  99050. * * snapDistance is the the change in distance
  99051. */
  99052. _this.onSnapObservable = new BABYLON.Observable();
  99053. /**
  99054. * If the scaling operation should be done on all axis (default: false)
  99055. */
  99056. _this.uniformScaling = false;
  99057. // Create Material
  99058. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  99059. _this._coloredMaterial.disableLighting = true;
  99060. _this._coloredMaterial.emissiveColor = color;
  99061. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  99062. hoverMaterial.disableLighting = true;
  99063. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  99064. // Build mesh on root node
  99065. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  99066. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  99067. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  99068. arrowTail.color = _this._coloredMaterial.emissiveColor;
  99069. arrow.addChild(arrowMesh);
  99070. arrow.addChild(arrowTail);
  99071. // Position arrow pointing in its drag axis
  99072. arrowMesh.scaling.scaleInPlace(0.1);
  99073. arrowMesh.material = _this._coloredMaterial;
  99074. arrowMesh.rotation.x = Math.PI / 2;
  99075. arrowMesh.position.z += 0.3;
  99076. arrowTail.scaling.scaleInPlace(0.26);
  99077. arrowTail.rotation.x = Math.PI / 2;
  99078. arrowTail.material = _this._coloredMaterial;
  99079. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  99080. _this._rootMesh.addChild(arrow);
  99081. arrow.scaling.scaleInPlace(1 / 3);
  99082. // Add drag behavior to handle events when the gizmo is dragged
  99083. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  99084. _this.dragBehavior.moveAttached = false;
  99085. _this._rootMesh.addBehavior(_this.dragBehavior);
  99086. var currentSnapDragDistance = 0;
  99087. var tmpVector = new BABYLON.Vector3();
  99088. var tmpSnapEvent = { snapDistance: 0 };
  99089. _this.dragBehavior.onDragObservable.add(function (event) {
  99090. if (_this.attachedMesh) {
  99091. // Snapping logic
  99092. var snapped = false;
  99093. var dragSteps = 0;
  99094. if (_this.uniformScaling) {
  99095. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  99096. if (tmpVector.y < 0) {
  99097. tmpVector.scaleInPlace(-1);
  99098. }
  99099. }
  99100. else {
  99101. tmpVector.copyFrom(dragAxis);
  99102. }
  99103. if (_this.snapDistance == 0) {
  99104. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  99105. }
  99106. else {
  99107. currentSnapDragDistance += event.dragDistance;
  99108. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  99109. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  99110. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  99111. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  99112. snapped = true;
  99113. }
  99114. else {
  99115. tmpVector.scaleInPlace(0);
  99116. }
  99117. }
  99118. _this.attachedMesh.scaling.addInPlace(tmpVector);
  99119. if (snapped) {
  99120. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  99121. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  99122. }
  99123. }
  99124. });
  99125. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  99126. if (_this._customMeshSet) {
  99127. return;
  99128. }
  99129. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  99130. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  99131. _this._rootMesh.getChildMeshes().forEach(function (m) {
  99132. m.material = material;
  99133. if (m.color) {
  99134. m.color = material.emissiveColor;
  99135. }
  99136. });
  99137. });
  99138. return _this;
  99139. }
  99140. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  99141. if (this.dragBehavior) {
  99142. this.dragBehavior.enabled = value ? true : false;
  99143. }
  99144. };
  99145. /**
  99146. * Disposes of the gizmo
  99147. */
  99148. AxisScaleGizmo.prototype.dispose = function () {
  99149. this.onSnapObservable.clear();
  99150. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  99151. this.dragBehavior.detach();
  99152. _super.prototype.dispose.call(this);
  99153. };
  99154. /**
  99155. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  99156. * @param mesh The mesh to replace the default mesh of the gizmo
  99157. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  99158. */
  99159. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  99160. var _this = this;
  99161. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  99162. _super.prototype.setCustomMesh.call(this, mesh);
  99163. if (useGizmoMaterial) {
  99164. this._rootMesh.getChildMeshes().forEach(function (m) {
  99165. m.material = _this._coloredMaterial;
  99166. if (m.color) {
  99167. m.color = _this._coloredMaterial.emissiveColor;
  99168. }
  99169. });
  99170. this._customMeshSet = false;
  99171. }
  99172. };
  99173. return AxisScaleGizmo;
  99174. }(BABYLON.Gizmo));
  99175. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  99176. })(BABYLON || (BABYLON = {}));
  99177. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  99178. var BABYLON;
  99179. (function (BABYLON) {
  99180. /**
  99181. * Single plane rotation gizmo
  99182. */
  99183. var PlaneRotationGizmo = /** @class */ (function (_super) {
  99184. __extends(PlaneRotationGizmo, _super);
  99185. /**
  99186. * Creates a PlaneRotationGizmo
  99187. * @param gizmoLayer The utility layer the gizmo will be added to
  99188. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  99189. * @param color The color of the gizmo
  99190. */
  99191. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  99192. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  99193. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  99194. var _this = _super.call(this, gizmoLayer) || this;
  99195. _this._pointerObserver = null;
  99196. /**
  99197. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  99198. */
  99199. _this.snapDistance = 0;
  99200. /**
  99201. * Event that fires each time the gizmo snaps to a new location.
  99202. * * snapDistance is the the change in distance
  99203. */
  99204. _this.onSnapObservable = new BABYLON.Observable();
  99205. // Create Material
  99206. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  99207. coloredMaterial.disableLighting = true;
  99208. coloredMaterial.emissiveColor = color;
  99209. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  99210. hoverMaterial.disableLighting = true;
  99211. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  99212. // Build mesh on root node
  99213. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  99214. // Create circle out of lines
  99215. var tessellation = 20;
  99216. var radius = 0.8;
  99217. var points = new Array();
  99218. for (var i = 0; i < tessellation; i++) {
  99219. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  99220. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  99221. }
  99222. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  99223. rotationMesh.color = coloredMaterial.emissiveColor;
  99224. // Position arrow pointing in its drag axis
  99225. rotationMesh.scaling.scaleInPlace(0.26);
  99226. rotationMesh.material = coloredMaterial;
  99227. rotationMesh.rotation.x = Math.PI / 2;
  99228. parentMesh.addChild(rotationMesh);
  99229. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  99230. _this._rootMesh.addChild(parentMesh);
  99231. parentMesh.scaling.scaleInPlace(1 / 3);
  99232. // Add drag behavior to handle events when the gizmo is dragged
  99233. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  99234. _this.dragBehavior.moveAttached = false;
  99235. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  99236. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  99237. _this._rootMesh.addBehavior(_this.dragBehavior);
  99238. var lastDragPosition = new BABYLON.Vector3();
  99239. _this.dragBehavior.onDragStartObservable.add(function (e) {
  99240. if (_this.attachedMesh) {
  99241. lastDragPosition.copyFrom(e.dragPlanePoint);
  99242. }
  99243. });
  99244. var rotationMatrix = new BABYLON.Matrix();
  99245. var planeNormalTowardsCamera = new BABYLON.Vector3();
  99246. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  99247. var tmpSnapEvent = { snapDistance: 0 };
  99248. var currentSnapDragDistance = 0;
  99249. var tmpMatrix = new BABYLON.Matrix();
  99250. var tmpVector = new BABYLON.Vector3();
  99251. var amountToRotate = new BABYLON.Quaternion();
  99252. _this.dragBehavior.onDragObservable.add(function (event) {
  99253. if (_this.attachedMesh) {
  99254. if (!_this.attachedMesh.rotationQuaternion) {
  99255. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  99256. }
  99257. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  99258. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  99259. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  99260. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  99261. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  99262. var angle = Math.atan2(cross.length(), dot);
  99263. planeNormalTowardsCamera.copyFrom(planeNormal);
  99264. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  99265. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  99266. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  99267. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  99268. }
  99269. // Flip up vector depending on which side the camera is on
  99270. if (gizmoLayer.utilityLayerScene.activeCamera) {
  99271. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  99272. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  99273. planeNormalTowardsCamera.scaleInPlace(-1);
  99274. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  99275. }
  99276. }
  99277. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  99278. if (halfCircleSide)
  99279. angle = -angle;
  99280. // Snapping logic
  99281. var snapped = false;
  99282. if (_this.snapDistance != 0) {
  99283. currentSnapDragDistance += angle;
  99284. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  99285. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  99286. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  99287. angle = _this.snapDistance * dragSteps;
  99288. snapped = true;
  99289. }
  99290. else {
  99291. angle = 0;
  99292. }
  99293. }
  99294. // If the mesh has a parent, convert needed world rotation to local rotation
  99295. tmpMatrix.reset();
  99296. if (_this.attachedMesh.parent) {
  99297. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  99298. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  99299. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  99300. }
  99301. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  99302. var quaternionCoefficient = Math.sin(angle / 2);
  99303. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  99304. // 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
  99305. if (tmpMatrix.determinant() > 0) {
  99306. amountToRotate.toEulerAnglesToRef(tmpVector);
  99307. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  99308. }
  99309. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  99310. // Rotate selected mesh quaternion over fixed axis
  99311. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  99312. }
  99313. else {
  99314. // Rotate selected mesh quaternion over rotated axis
  99315. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  99316. }
  99317. lastDragPosition.copyFrom(event.dragPlanePoint);
  99318. if (snapped) {
  99319. tmpSnapEvent.snapDistance = angle;
  99320. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  99321. }
  99322. }
  99323. });
  99324. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  99325. if (_this._customMeshSet) {
  99326. return;
  99327. }
  99328. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  99329. var material = isHovered ? hoverMaterial : coloredMaterial;
  99330. _this._rootMesh.getChildMeshes().forEach(function (m) {
  99331. m.material = material;
  99332. if (m.color) {
  99333. m.color = material.emissiveColor;
  99334. }
  99335. });
  99336. });
  99337. return _this;
  99338. }
  99339. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  99340. if (this.dragBehavior) {
  99341. this.dragBehavior.enabled = value ? true : false;
  99342. }
  99343. };
  99344. /**
  99345. * Disposes of the gizmo
  99346. */
  99347. PlaneRotationGizmo.prototype.dispose = function () {
  99348. this.onSnapObservable.clear();
  99349. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  99350. this.dragBehavior.detach();
  99351. _super.prototype.dispose.call(this);
  99352. };
  99353. return PlaneRotationGizmo;
  99354. }(BABYLON.Gizmo));
  99355. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  99356. })(BABYLON || (BABYLON = {}));
  99357. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  99358. var BABYLON;
  99359. (function (BABYLON) {
  99360. /**
  99361. * Gizmo that enables dragging a mesh along 3 axis
  99362. */
  99363. var PositionGizmo = /** @class */ (function (_super) {
  99364. __extends(PositionGizmo, _super);
  99365. /**
  99366. * Creates a PositionGizmo
  99367. * @param gizmoLayer The utility layer the gizmo will be added to
  99368. */
  99369. function PositionGizmo(gizmoLayer) {
  99370. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  99371. var _this = _super.call(this, gizmoLayer) || this;
  99372. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  99373. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  99374. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  99375. _this.attachedMesh = null;
  99376. return _this;
  99377. }
  99378. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  99379. set: function (mesh) {
  99380. if (this.xGizmo) {
  99381. this.xGizmo.attachedMesh = mesh;
  99382. this.yGizmo.attachedMesh = mesh;
  99383. this.zGizmo.attachedMesh = mesh;
  99384. }
  99385. },
  99386. enumerable: true,
  99387. configurable: true
  99388. });
  99389. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  99390. get: function () {
  99391. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  99392. },
  99393. set: function (value) {
  99394. if (this.xGizmo) {
  99395. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99396. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99397. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99398. }
  99399. },
  99400. enumerable: true,
  99401. configurable: true
  99402. });
  99403. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  99404. get: function () {
  99405. return this.xGizmo.snapDistance;
  99406. },
  99407. /**
  99408. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  99409. */
  99410. set: function (value) {
  99411. if (this.xGizmo) {
  99412. this.xGizmo.snapDistance = value;
  99413. this.yGizmo.snapDistance = value;
  99414. this.zGizmo.snapDistance = value;
  99415. }
  99416. },
  99417. enumerable: true,
  99418. configurable: true
  99419. });
  99420. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  99421. get: function () {
  99422. return this.xGizmo.scaleRatio;
  99423. },
  99424. /**
  99425. * Ratio for the scale of the gizmo (Default: 1)
  99426. */
  99427. set: function (value) {
  99428. if (this.xGizmo) {
  99429. this.xGizmo.scaleRatio = value;
  99430. this.yGizmo.scaleRatio = value;
  99431. this.zGizmo.scaleRatio = value;
  99432. }
  99433. },
  99434. enumerable: true,
  99435. configurable: true
  99436. });
  99437. /**
  99438. * Disposes of the gizmo
  99439. */
  99440. PositionGizmo.prototype.dispose = function () {
  99441. this.xGizmo.dispose();
  99442. this.yGizmo.dispose();
  99443. this.zGizmo.dispose();
  99444. };
  99445. /**
  99446. * CustomMeshes are not supported by this gizmo
  99447. * @param mesh The mesh to replace the default mesh of the gizmo
  99448. */
  99449. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  99450. 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)");
  99451. };
  99452. return PositionGizmo;
  99453. }(BABYLON.Gizmo));
  99454. BABYLON.PositionGizmo = PositionGizmo;
  99455. })(BABYLON || (BABYLON = {}));
  99456. //# sourceMappingURL=babylon.positionGizmo.js.map
  99457. var BABYLON;
  99458. (function (BABYLON) {
  99459. /**
  99460. * Gizmo that enables rotating a mesh along 3 axis
  99461. */
  99462. var RotationGizmo = /** @class */ (function (_super) {
  99463. __extends(RotationGizmo, _super);
  99464. /**
  99465. * Creates a RotationGizmo
  99466. * @param gizmoLayer The utility layer the gizmo will be added to
  99467. */
  99468. function RotationGizmo(gizmoLayer) {
  99469. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  99470. var _this = _super.call(this, gizmoLayer) || this;
  99471. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  99472. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  99473. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  99474. _this.attachedMesh = null;
  99475. return _this;
  99476. }
  99477. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  99478. set: function (mesh) {
  99479. if (this.xGizmo) {
  99480. this.xGizmo.attachedMesh = mesh;
  99481. this.yGizmo.attachedMesh = mesh;
  99482. this.zGizmo.attachedMesh = mesh;
  99483. }
  99484. },
  99485. enumerable: true,
  99486. configurable: true
  99487. });
  99488. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  99489. get: function () {
  99490. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  99491. },
  99492. set: function (value) {
  99493. if (this.xGizmo) {
  99494. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99495. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99496. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99497. }
  99498. },
  99499. enumerable: true,
  99500. configurable: true
  99501. });
  99502. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  99503. get: function () {
  99504. return this.xGizmo.snapDistance;
  99505. },
  99506. /**
  99507. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  99508. */
  99509. set: function (value) {
  99510. if (this.xGizmo) {
  99511. this.xGizmo.snapDistance = value;
  99512. this.yGizmo.snapDistance = value;
  99513. this.zGizmo.snapDistance = value;
  99514. }
  99515. },
  99516. enumerable: true,
  99517. configurable: true
  99518. });
  99519. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  99520. get: function () {
  99521. return this.xGizmo.scaleRatio;
  99522. },
  99523. /**
  99524. * Ratio for the scale of the gizmo (Default: 1)
  99525. */
  99526. set: function (value) {
  99527. if (this.xGizmo) {
  99528. this.xGizmo.scaleRatio = value;
  99529. this.yGizmo.scaleRatio = value;
  99530. this.zGizmo.scaleRatio = value;
  99531. }
  99532. },
  99533. enumerable: true,
  99534. configurable: true
  99535. });
  99536. /**
  99537. * Disposes of the gizmo
  99538. */
  99539. RotationGizmo.prototype.dispose = function () {
  99540. this.xGizmo.dispose();
  99541. this.yGizmo.dispose();
  99542. this.zGizmo.dispose();
  99543. };
  99544. /**
  99545. * CustomMeshes are not supported by this gizmo
  99546. * @param mesh The mesh to replace the default mesh of the gizmo
  99547. */
  99548. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  99549. 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)");
  99550. };
  99551. return RotationGizmo;
  99552. }(BABYLON.Gizmo));
  99553. BABYLON.RotationGizmo = RotationGizmo;
  99554. })(BABYLON || (BABYLON = {}));
  99555. //# sourceMappingURL=babylon.rotationGizmo.js.map
  99556. var BABYLON;
  99557. (function (BABYLON) {
  99558. /**
  99559. * Gizmo that enables scaling a mesh along 3 axis
  99560. */
  99561. var ScaleGizmo = /** @class */ (function (_super) {
  99562. __extends(ScaleGizmo, _super);
  99563. /**
  99564. * Creates a ScaleGizmo
  99565. * @param gizmoLayer The utility layer the gizmo will be added to
  99566. */
  99567. function ScaleGizmo(gizmoLayer) {
  99568. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  99569. var _this = _super.call(this, gizmoLayer) || this;
  99570. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  99571. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  99572. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  99573. // Create uniform scale gizmo
  99574. _this.uniformScaleGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  99575. _this.uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  99576. _this.uniformScaleGizmo.uniformScaling = true;
  99577. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  99578. octahedron.scaling.scaleInPlace(0.007);
  99579. _this.uniformScaleGizmo.setCustomMesh(octahedron, true);
  99580. _this.attachedMesh = null;
  99581. return _this;
  99582. }
  99583. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  99584. set: function (mesh) {
  99585. if (this.xGizmo) {
  99586. this.xGizmo.attachedMesh = mesh;
  99587. this.yGizmo.attachedMesh = mesh;
  99588. this.zGizmo.attachedMesh = mesh;
  99589. this.uniformScaleGizmo.attachedMesh = mesh;
  99590. }
  99591. },
  99592. enumerable: true,
  99593. configurable: true
  99594. });
  99595. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  99596. get: function () {
  99597. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  99598. },
  99599. set: function (value) {
  99600. if (this.xGizmo) {
  99601. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99602. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99603. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99604. }
  99605. },
  99606. enumerable: true,
  99607. configurable: true
  99608. });
  99609. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  99610. get: function () {
  99611. return this.xGizmo.snapDistance;
  99612. },
  99613. /**
  99614. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  99615. */
  99616. set: function (value) {
  99617. if (this.xGizmo) {
  99618. this.xGizmo.snapDistance = value;
  99619. this.yGizmo.snapDistance = value;
  99620. this.zGizmo.snapDistance = value;
  99621. this.uniformScaleGizmo.snapDistance = value;
  99622. }
  99623. },
  99624. enumerable: true,
  99625. configurable: true
  99626. });
  99627. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  99628. get: function () {
  99629. return this.xGizmo.scaleRatio;
  99630. },
  99631. /**
  99632. * Ratio for the scale of the gizmo (Default: 1)
  99633. */
  99634. set: function (value) {
  99635. if (this.xGizmo) {
  99636. this.xGizmo.scaleRatio = value;
  99637. this.yGizmo.scaleRatio = value;
  99638. this.zGizmo.scaleRatio = value;
  99639. this.uniformScaleGizmo.scaleRatio = value;
  99640. }
  99641. },
  99642. enumerable: true,
  99643. configurable: true
  99644. });
  99645. /**
  99646. * Disposes of the gizmo
  99647. */
  99648. ScaleGizmo.prototype.dispose = function () {
  99649. this.xGizmo.dispose();
  99650. this.yGizmo.dispose();
  99651. this.zGizmo.dispose();
  99652. this.uniformScaleGizmo.dispose();
  99653. };
  99654. return ScaleGizmo;
  99655. }(BABYLON.Gizmo));
  99656. BABYLON.ScaleGizmo = ScaleGizmo;
  99657. })(BABYLON || (BABYLON = {}));
  99658. //# sourceMappingURL=babylon.scaleGizmo.js.map
  99659. var BABYLON;
  99660. (function (BABYLON) {
  99661. /**
  99662. * Bounding box gizmo
  99663. */
  99664. var BoundingBoxGizmo = /** @class */ (function (_super) {
  99665. __extends(BoundingBoxGizmo, _super);
  99666. /**
  99667. * Creates an BoundingBoxGizmo
  99668. * @param gizmoLayer The utility layer the gizmo will be added to
  99669. * @param color The color of the gizmo
  99670. */
  99671. function BoundingBoxGizmo(color, gizmoLayer) {
  99672. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  99673. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  99674. var _this = _super.call(this, gizmoLayer) || this;
  99675. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  99676. _this._renderObserver = null;
  99677. _this._pointerObserver = null;
  99678. _this._scaleDragSpeed = 0.2;
  99679. _this._tmpQuaternion = new BABYLON.Quaternion();
  99680. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  99681. _this._tmpRotationMatrix = new BABYLON.Matrix();
  99682. /**
  99683. * 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)
  99684. */
  99685. _this.ignoreChildren = false;
  99686. /**
  99687. * 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)
  99688. */
  99689. _this.includeChildPredicate = null;
  99690. /**
  99691. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  99692. */
  99693. _this.rotationSphereSize = 0.1;
  99694. /**
  99695. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  99696. */
  99697. _this.scaleBoxSize = 0.1;
  99698. /**
  99699. * 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)
  99700. */
  99701. _this.fixedDragMeshScreenSize = false;
  99702. /**
  99703. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  99704. */
  99705. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  99706. /**
  99707. * Fired when a rotation sphere or scale box is dragged
  99708. */
  99709. _this.onDragStartObservable = new BABYLON.Observable();
  99710. /**
  99711. * Fired when a scale box is dragged
  99712. */
  99713. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  99714. /**
  99715. * Fired when a scale box drag is ended
  99716. */
  99717. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  99718. /**
  99719. * Fired when a rotation sphere is dragged
  99720. */
  99721. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  99722. /**
  99723. * Fired when a rotation sphere drag is ended
  99724. */
  99725. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  99726. /**
  99727. * 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)
  99728. */
  99729. _this.scalePivot = null;
  99730. _this._existingMeshScale = new BABYLON.Vector3();
  99731. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  99732. _this._updateScale = false;
  99733. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  99734. // Create Materials
  99735. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  99736. coloredMaterial.disableLighting = true;
  99737. coloredMaterial.emissiveColor = color;
  99738. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  99739. hoverColoredMaterial.disableLighting = true;
  99740. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  99741. // Build bounding box out of lines
  99742. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  99743. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  99744. var lines = [];
  99745. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  99746. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  99747. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  99748. 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));
  99749. 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));
  99750. 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));
  99751. 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));
  99752. 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));
  99753. 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));
  99754. 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));
  99755. 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));
  99756. 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));
  99757. lines.forEach(function (l) {
  99758. l.color = color;
  99759. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  99760. l.isPickable = false;
  99761. _this._lineBoundingBox.addChild(l);
  99762. });
  99763. _this._rootMesh.addChild(_this._lineBoundingBox);
  99764. // Create rotation spheres
  99765. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  99766. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  99767. var _loop_1 = function (i_1) {
  99768. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  99769. sphere.rotationQuaternion = new BABYLON.Quaternion();
  99770. sphere.material = coloredMaterial;
  99771. // Drag behavior
  99772. _dragBehavior = new BABYLON.PointerDragBehavior({});
  99773. _dragBehavior.moveAttached = false;
  99774. _dragBehavior.updateDragPlane = false;
  99775. sphere.addBehavior(_dragBehavior);
  99776. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  99777. var totalTurnAmountOfDrag = 0;
  99778. _dragBehavior.onDragStartObservable.add(function (event) {
  99779. startingTurnDirection.copyFrom(sphere.forward);
  99780. totalTurnAmountOfDrag = 0;
  99781. });
  99782. _dragBehavior.onDragObservable.add(function (event) {
  99783. _this.onRotationSphereDragObservable.notifyObservers({});
  99784. if (_this.attachedMesh) {
  99785. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  99786. var worldDragDirection = startingTurnDirection;
  99787. // Project the world right on to the drag plane
  99788. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  99789. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  99790. // project drag delta on to the resulting drag axis and rotate based on that
  99791. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  99792. // Make rotation relative to size of mesh.
  99793. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  99794. // Rotate based on axis
  99795. if (!_this.attachedMesh.rotationQuaternion) {
  99796. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  99797. }
  99798. if (!_this._anchorMesh.rotationQuaternion) {
  99799. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  99800. }
  99801. // Do not allow the object to turn more than a full circle
  99802. totalTurnAmountOfDrag += projectDist;
  99803. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  99804. if (i_1 >= 8) {
  99805. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  99806. }
  99807. else if (i_1 >= 4) {
  99808. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  99809. }
  99810. else {
  99811. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  99812. }
  99813. // Rotate around center of bounding box
  99814. _this._anchorMesh.addChild(_this.attachedMesh);
  99815. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  99816. _this._anchorMesh.removeChild(_this.attachedMesh);
  99817. }
  99818. _this.updateBoundingBox();
  99819. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  99820. }
  99821. });
  99822. // Selection/deselection
  99823. _dragBehavior.onDragStartObservable.add(function () {
  99824. _this.onDragStartObservable.notifyObservers({});
  99825. _this._selectNode(sphere);
  99826. });
  99827. _dragBehavior.onDragEndObservable.add(function () {
  99828. _this.onRotationSphereDragEndObservable.notifyObservers({});
  99829. _this._selectNode(null);
  99830. });
  99831. this_1._rotateSpheresParent.addChild(sphere);
  99832. };
  99833. var this_1 = this, _dragBehavior;
  99834. for (var i_1 = 0; i_1 < 12; i_1++) {
  99835. _loop_1(i_1);
  99836. }
  99837. _this._rootMesh.addChild(_this._rotateSpheresParent);
  99838. // Create scale cubes
  99839. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  99840. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  99841. for (var i = 0; i < 2; i++) {
  99842. for (var j = 0; j < 2; j++) {
  99843. var _loop_2 = function () {
  99844. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  99845. box.material = coloredMaterial;
  99846. // Dragging logic
  99847. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  99848. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  99849. _dragBehavior.moveAttached = false;
  99850. box.addBehavior(_dragBehavior);
  99851. _dragBehavior.onDragObservable.add(function (event) {
  99852. _this.onScaleBoxDragObservable.notifyObservers({});
  99853. if (_this.attachedMesh) {
  99854. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  99855. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  99856. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  99857. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  99858. _this.updateBoundingBox();
  99859. if (_this.scalePivot) {
  99860. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  99861. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  99862. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  99863. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  99864. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  99865. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  99866. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  99867. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  99868. }
  99869. else {
  99870. // Scale from the position of the opposite corner
  99871. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  99872. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  99873. }
  99874. _this._anchorMesh.addChild(_this.attachedMesh);
  99875. _this._anchorMesh.scaling.addInPlace(deltaScale);
  99876. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  99877. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  99878. }
  99879. _this._anchorMesh.removeChild(_this.attachedMesh);
  99880. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  99881. }
  99882. });
  99883. // Selection/deselection
  99884. _dragBehavior.onDragStartObservable.add(function () {
  99885. _this.onDragStartObservable.notifyObservers({});
  99886. _this._selectNode(box);
  99887. });
  99888. _dragBehavior.onDragEndObservable.add(function () {
  99889. _this.onScaleBoxDragEndObservable.notifyObservers({});
  99890. _this._selectNode(null);
  99891. });
  99892. this_2._scaleBoxesParent.addChild(box);
  99893. };
  99894. var this_2 = this, _dragBehavior;
  99895. for (var k = 0; k < 2; k++) {
  99896. _loop_2();
  99897. }
  99898. }
  99899. }
  99900. _this._rootMesh.addChild(_this._scaleBoxesParent);
  99901. // Hover color change
  99902. var pointerIds = new Array();
  99903. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  99904. if (!pointerIds[pointerInfo.event.pointerId]) {
  99905. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  99906. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  99907. pointerIds[pointerInfo.event.pointerId] = mesh;
  99908. mesh.material = hoverColoredMaterial;
  99909. }
  99910. });
  99911. }
  99912. else {
  99913. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  99914. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  99915. delete pointerIds[pointerInfo.event.pointerId];
  99916. }
  99917. }
  99918. });
  99919. // Update bounding box positions
  99920. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  99921. // Only update the bouding box if scaling has changed
  99922. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  99923. _this.updateBoundingBox();
  99924. }
  99925. });
  99926. _this.updateBoundingBox();
  99927. return _this;
  99928. }
  99929. /** @hidden */
  99930. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  99931. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  99932. // Save old pivot and set pivot to 0,0,0
  99933. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  99934. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  99935. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  99936. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  99937. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  99938. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  99939. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  99940. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  99941. }
  99942. }
  99943. BoundingBoxGizmo._PivotCached++;
  99944. };
  99945. /** @hidden */
  99946. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  99947. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  99948. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  99949. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  99950. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  99951. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  99952. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  99953. }
  99954. this._PivotCached--;
  99955. };
  99956. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  99957. if (value) {
  99958. // Reset anchor mesh to match attached mesh's scale
  99959. // This is needed to avoid invalid box/sphere position on first drag
  99960. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  99961. this._anchorMesh.addChild(value);
  99962. this._anchorMesh.removeChild(value);
  99963. BoundingBoxGizmo._RestorePivotPoint(value);
  99964. this.updateBoundingBox();
  99965. }
  99966. };
  99967. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  99968. this._rotateSpheresParent.getChildMeshes()
  99969. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  99970. m.isVisible = (!selectedMesh || m == selectedMesh);
  99971. });
  99972. };
  99973. /**
  99974. * Updates the bounding box information for the Gizmo
  99975. */
  99976. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  99977. if (this.attachedMesh) {
  99978. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  99979. this._update();
  99980. // Rotate based on axis
  99981. if (!this.attachedMesh.rotationQuaternion) {
  99982. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  99983. }
  99984. if (!this._anchorMesh.rotationQuaternion) {
  99985. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  99986. }
  99987. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  99988. // Store original position and reset mesh to origin before computing the bounding box
  99989. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  99990. this._tmpVector.copyFrom(this.attachedMesh.position);
  99991. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  99992. this.attachedMesh.position.set(0, 0, 0);
  99993. // Update bounding dimensions/positions
  99994. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  99995. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  99996. // Update gizmo to match bounding box scaling and rotation
  99997. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  99998. 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);
  99999. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  100000. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  100001. this._lineBoundingBox.computeWorldMatrix();
  100002. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  100003. // restore position/rotation values
  100004. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  100005. this.attachedMesh.position.copyFrom(this._tmpVector);
  100006. }
  100007. // Update rotation sphere locations
  100008. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  100009. for (var i = 0; i < 3; i++) {
  100010. for (var j = 0; j < 2; j++) {
  100011. for (var k = 0; k < 2; k++) {
  100012. var index = ((i * 4) + (j * 2)) + k;
  100013. if (i == 0) {
  100014. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  100015. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  100016. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  100017. }
  100018. if (i == 1) {
  100019. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  100020. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  100021. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  100022. }
  100023. if (i == 2) {
  100024. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  100025. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  100026. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  100027. }
  100028. if (this.fixedDragMeshScreenSize) {
  100029. this._rootMesh.computeWorldMatrix();
  100030. this._rotateSpheresParent.computeWorldMatrix();
  100031. rotateSpheres[index].computeWorldMatrix();
  100032. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  100033. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  100034. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  100035. }
  100036. else {
  100037. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  100038. }
  100039. }
  100040. }
  100041. }
  100042. // Update scale box locations
  100043. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  100044. for (var i = 0; i < 2; i++) {
  100045. for (var j = 0; j < 2; j++) {
  100046. for (var k = 0; k < 2; k++) {
  100047. var index = ((i * 4) + (j * 2)) + k;
  100048. if (scaleBoxes[index]) {
  100049. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  100050. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  100051. if (this.fixedDragMeshScreenSize) {
  100052. this._rootMesh.computeWorldMatrix();
  100053. this._scaleBoxesParent.computeWorldMatrix();
  100054. scaleBoxes[index].computeWorldMatrix();
  100055. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  100056. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  100057. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  100058. }
  100059. else {
  100060. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  100061. }
  100062. }
  100063. }
  100064. }
  100065. }
  100066. if (this.attachedMesh) {
  100067. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  100068. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  100069. }
  100070. };
  100071. /**
  100072. * Enables rotation on the specified axis and disables rotation on the others
  100073. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  100074. */
  100075. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  100076. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  100077. if (i < 4) {
  100078. m.setEnabled(axis.indexOf("x") != -1);
  100079. }
  100080. else if (i < 8) {
  100081. m.setEnabled(axis.indexOf("y") != -1);
  100082. }
  100083. else {
  100084. m.setEnabled(axis.indexOf("z") != -1);
  100085. }
  100086. });
  100087. };
  100088. /**
  100089. * Disposes of the gizmo
  100090. */
  100091. BoundingBoxGizmo.prototype.dispose = function () {
  100092. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  100093. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  100094. this._lineBoundingBox.dispose();
  100095. this._rotateSpheresParent.dispose();
  100096. this._scaleBoxesParent.dispose();
  100097. _super.prototype.dispose.call(this);
  100098. };
  100099. /**
  100100. * 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)
  100101. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  100102. * @returns the bounding box mesh with the passed in mesh as a child
  100103. */
  100104. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  100105. var makeNotPickable = function (root) {
  100106. root.isPickable = false;
  100107. root.getChildMeshes().forEach(function (c) {
  100108. makeNotPickable(c);
  100109. });
  100110. };
  100111. makeNotPickable(mesh);
  100112. // Reset position to get boudning box from origin with no rotation
  100113. if (!mesh.rotationQuaternion) {
  100114. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  100115. }
  100116. var oldPos = mesh.position.clone();
  100117. var oldRot = mesh.rotationQuaternion.clone();
  100118. mesh.rotationQuaternion.set(0, 0, 0, 1);
  100119. mesh.position.set(0, 0, 0);
  100120. // Update bounding dimensions/positions
  100121. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  100122. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  100123. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  100124. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  100125. // Restore original positions
  100126. mesh.addChild(box);
  100127. mesh.rotationQuaternion.copyFrom(oldRot);
  100128. mesh.position.copyFrom(oldPos);
  100129. // Reverse parenting
  100130. mesh.removeChild(box);
  100131. box.addChild(mesh);
  100132. box.visibility = 0;
  100133. return box;
  100134. };
  100135. /**
  100136. * CustomMeshes are not supported by this gizmo
  100137. * @param mesh The mesh to replace the default mesh of the gizmo
  100138. */
  100139. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  100140. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  100141. };
  100142. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  100143. // store/remove pivot point should only be applied during their outermost calls
  100144. BoundingBoxGizmo._PivotCached = 0;
  100145. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  100146. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  100147. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  100148. return BoundingBoxGizmo;
  100149. }(BABYLON.Gizmo));
  100150. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  100151. })(BABYLON || (BABYLON = {}));
  100152. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  100153. var BABYLON;
  100154. (function (BABYLON) {
  100155. /**
  100156. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  100157. */
  100158. var GizmoManager = /** @class */ (function () {
  100159. /**
  100160. * Instatiates a gizmo manager
  100161. * @param scene the scene to overlay the gizmos on top of
  100162. */
  100163. function GizmoManager(scene) {
  100164. var _this = this;
  100165. this.scene = scene;
  100166. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  100167. this._pointerObserver = null;
  100168. this._attachedMesh = null;
  100169. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  100170. /**
  100171. * When bounding box gizmo is enabled, this can be used to track drag/end events
  100172. */
  100173. this.boundingBoxDragBehavior = new BABYLON.SixDofDragBehavior();
  100174. /**
  100175. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  100176. */
  100177. this.attachableMeshes = null;
  100178. /**
  100179. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  100180. */
  100181. this.usePointerToAttachGizmos = true;
  100182. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  100183. // Instatiate/dispose gizmos based on pointer actions
  100184. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  100185. if (!_this.usePointerToAttachGizmos) {
  100186. return;
  100187. }
  100188. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  100189. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  100190. var node = pointerInfo.pickInfo.pickedMesh;
  100191. if (_this.attachableMeshes == null) {
  100192. // Attach to the most parent node
  100193. while (node && node.parent != null) {
  100194. node = node.parent;
  100195. }
  100196. }
  100197. else {
  100198. // Attach to the parent node that is an attachableMesh
  100199. var found = false;
  100200. _this.attachableMeshes.forEach(function (mesh) {
  100201. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  100202. node = mesh;
  100203. found = true;
  100204. }
  100205. });
  100206. if (!found) {
  100207. node = null;
  100208. }
  100209. }
  100210. if (node instanceof BABYLON.AbstractMesh) {
  100211. _this.attachToMesh(node);
  100212. }
  100213. else {
  100214. _this.attachToMesh(null);
  100215. }
  100216. }
  100217. else {
  100218. _this.attachToMesh(null);
  100219. }
  100220. }
  100221. });
  100222. }
  100223. /**
  100224. * Attaches a set of gizmos to the specified mesh
  100225. * @param mesh The mesh the gizmo's should be attached to
  100226. */
  100227. GizmoManager.prototype.attachToMesh = function (mesh) {
  100228. if (this._attachedMesh) {
  100229. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  100230. }
  100231. this._attachedMesh = mesh;
  100232. for (var key in this.gizmos) {
  100233. var gizmo = (this.gizmos[key]);
  100234. if (gizmo && this._gizmosEnabled[key]) {
  100235. gizmo.attachedMesh = mesh;
  100236. }
  100237. }
  100238. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  100239. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  100240. }
  100241. };
  100242. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  100243. get: function () {
  100244. return this._gizmosEnabled.positionGizmo;
  100245. },
  100246. /**
  100247. * If the position gizmo is enabled
  100248. */
  100249. set: function (value) {
  100250. if (value) {
  100251. if (!this.gizmos.positionGizmo) {
  100252. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  100253. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  100254. }
  100255. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  100256. }
  100257. else if (this.gizmos.positionGizmo) {
  100258. this.gizmos.positionGizmo.attachedMesh = null;
  100259. }
  100260. this._gizmosEnabled.positionGizmo = value;
  100261. },
  100262. enumerable: true,
  100263. configurable: true
  100264. });
  100265. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  100266. get: function () {
  100267. return this._gizmosEnabled.rotationGizmo;
  100268. },
  100269. /**
  100270. * If the rotation gizmo is enabled
  100271. */
  100272. set: function (value) {
  100273. if (value) {
  100274. if (!this.gizmos.rotationGizmo) {
  100275. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  100276. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  100277. }
  100278. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  100279. }
  100280. else if (this.gizmos.rotationGizmo) {
  100281. this.gizmos.rotationGizmo.attachedMesh = null;
  100282. }
  100283. this._gizmosEnabled.rotationGizmo = value;
  100284. },
  100285. enumerable: true,
  100286. configurable: true
  100287. });
  100288. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  100289. get: function () {
  100290. return this._gizmosEnabled.scaleGizmo;
  100291. },
  100292. /**
  100293. * If the scale gizmo is enabled
  100294. */
  100295. set: function (value) {
  100296. if (value) {
  100297. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  100298. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  100299. }
  100300. else if (this.gizmos.scaleGizmo) {
  100301. this.gizmos.scaleGizmo.attachedMesh = null;
  100302. }
  100303. this._gizmosEnabled.scaleGizmo = value;
  100304. },
  100305. enumerable: true,
  100306. configurable: true
  100307. });
  100308. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  100309. get: function () {
  100310. return this._gizmosEnabled.boundingBoxGizmo;
  100311. },
  100312. /**
  100313. * If the boundingBox gizmo is enabled
  100314. */
  100315. set: function (value) {
  100316. if (value) {
  100317. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  100318. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  100319. if (this._attachedMesh) {
  100320. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  100321. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  100322. }
  100323. }
  100324. else if (this.gizmos.boundingBoxGizmo) {
  100325. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  100326. }
  100327. this._gizmosEnabled.boundingBoxGizmo = value;
  100328. },
  100329. enumerable: true,
  100330. configurable: true
  100331. });
  100332. /**
  100333. * Disposes of the gizmo manager
  100334. */
  100335. GizmoManager.prototype.dispose = function () {
  100336. this.scene.onPointerObservable.remove(this._pointerObserver);
  100337. for (var key in this.gizmos) {
  100338. var gizmo = (this.gizmos[key]);
  100339. if (gizmo) {
  100340. gizmo.dispose();
  100341. }
  100342. }
  100343. this.boundingBoxDragBehavior.detach();
  100344. };
  100345. return GizmoManager;
  100346. }());
  100347. BABYLON.GizmoManager = GizmoManager;
  100348. })(BABYLON || (BABYLON = {}));
  100349. //# sourceMappingURL=babylon.gizmoManager.js.map
  100350. var BABYLON;
  100351. (function (BABYLON) {
  100352. /**
  100353. * Defines a target to use with MorphTargetManager
  100354. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  100355. */
  100356. var MorphTarget = /** @class */ (function () {
  100357. /**
  100358. * Creates a new MorphTarget
  100359. * @param name defines the name of the target
  100360. * @param influence defines the influence to use
  100361. */
  100362. function MorphTarget(
  100363. /** defines the name of the target */
  100364. name, influence, scene) {
  100365. if (influence === void 0) { influence = 0; }
  100366. if (scene === void 0) { scene = null; }
  100367. this.name = name;
  100368. /**
  100369. * Gets or sets the list of animations
  100370. */
  100371. this.animations = new Array();
  100372. this._positions = null;
  100373. this._normals = null;
  100374. this._tangents = null;
  100375. /**
  100376. * Observable raised when the influence changes
  100377. */
  100378. this.onInfluenceChanged = new BABYLON.Observable();
  100379. this._animationPropertiesOverride = null;
  100380. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  100381. this.influence = influence;
  100382. }
  100383. Object.defineProperty(MorphTarget.prototype, "influence", {
  100384. /**
  100385. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  100386. */
  100387. get: function () {
  100388. return this._influence;
  100389. },
  100390. set: function (influence) {
  100391. if (this._influence === influence) {
  100392. return;
  100393. }
  100394. var previous = this._influence;
  100395. this._influence = influence;
  100396. if (this.onInfluenceChanged.hasObservers) {
  100397. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  100398. }
  100399. },
  100400. enumerable: true,
  100401. configurable: true
  100402. });
  100403. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  100404. /**
  100405. * Gets or sets the animation properties override
  100406. */
  100407. get: function () {
  100408. if (!this._animationPropertiesOverride && this._scene) {
  100409. return this._scene.animationPropertiesOverride;
  100410. }
  100411. return this._animationPropertiesOverride;
  100412. },
  100413. set: function (value) {
  100414. this._animationPropertiesOverride = value;
  100415. },
  100416. enumerable: true,
  100417. configurable: true
  100418. });
  100419. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  100420. /**
  100421. * Gets a boolean defining if the target contains position data
  100422. */
  100423. get: function () {
  100424. return !!this._positions;
  100425. },
  100426. enumerable: true,
  100427. configurable: true
  100428. });
  100429. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  100430. /**
  100431. * Gets a boolean defining if the target contains normal data
  100432. */
  100433. get: function () {
  100434. return !!this._normals;
  100435. },
  100436. enumerable: true,
  100437. configurable: true
  100438. });
  100439. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  100440. /**
  100441. * Gets a boolean defining if the target contains tangent data
  100442. */
  100443. get: function () {
  100444. return !!this._tangents;
  100445. },
  100446. enumerable: true,
  100447. configurable: true
  100448. });
  100449. /**
  100450. * Affects position data to this target
  100451. * @param data defines the position data to use
  100452. */
  100453. MorphTarget.prototype.setPositions = function (data) {
  100454. this._positions = data;
  100455. };
  100456. /**
  100457. * Gets the position data stored in this target
  100458. * @returns a FloatArray containing the position data (or null if not present)
  100459. */
  100460. MorphTarget.prototype.getPositions = function () {
  100461. return this._positions;
  100462. };
  100463. /**
  100464. * Affects normal data to this target
  100465. * @param data defines the normal data to use
  100466. */
  100467. MorphTarget.prototype.setNormals = function (data) {
  100468. this._normals = data;
  100469. };
  100470. /**
  100471. * Gets the normal data stored in this target
  100472. * @returns a FloatArray containing the normal data (or null if not present)
  100473. */
  100474. MorphTarget.prototype.getNormals = function () {
  100475. return this._normals;
  100476. };
  100477. /**
  100478. * Affects tangent data to this target
  100479. * @param data defines the tangent data to use
  100480. */
  100481. MorphTarget.prototype.setTangents = function (data) {
  100482. this._tangents = data;
  100483. };
  100484. /**
  100485. * Gets the tangent data stored in this target
  100486. * @returns a FloatArray containing the tangent data (or null if not present)
  100487. */
  100488. MorphTarget.prototype.getTangents = function () {
  100489. return this._tangents;
  100490. };
  100491. /**
  100492. * Serializes the current target into a Serialization object
  100493. * @returns the serialized object
  100494. */
  100495. MorphTarget.prototype.serialize = function () {
  100496. var serializationObject = {};
  100497. serializationObject.name = this.name;
  100498. serializationObject.influence = this.influence;
  100499. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  100500. if (this.hasNormals) {
  100501. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  100502. }
  100503. if (this.hasTangents) {
  100504. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  100505. }
  100506. // Animations
  100507. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  100508. return serializationObject;
  100509. };
  100510. // Statics
  100511. /**
  100512. * Creates a new target from serialized data
  100513. * @param serializationObject defines the serialized data to use
  100514. * @returns a new MorphTarget
  100515. */
  100516. MorphTarget.Parse = function (serializationObject) {
  100517. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  100518. result.setPositions(serializationObject.positions);
  100519. if (serializationObject.normals) {
  100520. result.setNormals(serializationObject.normals);
  100521. }
  100522. if (serializationObject.tangents) {
  100523. result.setTangents(serializationObject.tangents);
  100524. }
  100525. // Animations
  100526. if (serializationObject.animations) {
  100527. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  100528. var parsedAnimation = serializationObject.animations[animationIndex];
  100529. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  100530. }
  100531. }
  100532. return result;
  100533. };
  100534. /**
  100535. * Creates a MorphTarget from mesh data
  100536. * @param mesh defines the source mesh
  100537. * @param name defines the name to use for the new target
  100538. * @param influence defines the influence to attach to the target
  100539. * @returns a new MorphTarget
  100540. */
  100541. MorphTarget.FromMesh = function (mesh, name, influence) {
  100542. if (!name) {
  100543. name = mesh.name;
  100544. }
  100545. var result = new MorphTarget(name, influence, mesh.getScene());
  100546. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  100547. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  100548. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  100549. }
  100550. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  100551. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  100552. }
  100553. return result;
  100554. };
  100555. return MorphTarget;
  100556. }());
  100557. BABYLON.MorphTarget = MorphTarget;
  100558. })(BABYLON || (BABYLON = {}));
  100559. //# sourceMappingURL=babylon.morphTarget.js.map
  100560. var BABYLON;
  100561. (function (BABYLON) {
  100562. /**
  100563. * This class is used to deform meshes using morphing between different targets
  100564. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  100565. */
  100566. var MorphTargetManager = /** @class */ (function () {
  100567. /**
  100568. * Creates a new MorphTargetManager
  100569. * @param scene defines the current scene
  100570. */
  100571. function MorphTargetManager(scene) {
  100572. if (scene === void 0) { scene = null; }
  100573. this._targets = new Array();
  100574. this._targetObservable = new Array();
  100575. this._activeTargets = new BABYLON.SmartArray(16);
  100576. this._supportsNormals = false;
  100577. this._supportsTangents = false;
  100578. this._vertexCount = 0;
  100579. this._uniqueId = 0;
  100580. this._tempInfluences = new Array();
  100581. if (!scene) {
  100582. scene = BABYLON.Engine.LastCreatedScene;
  100583. }
  100584. this._scene = scene;
  100585. if (this._scene) {
  100586. this._scene.morphTargetManagers.push(this);
  100587. this._uniqueId = this._scene.getUniqueId();
  100588. }
  100589. }
  100590. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  100591. /**
  100592. * Gets the unique ID of this manager
  100593. */
  100594. get: function () {
  100595. return this._uniqueId;
  100596. },
  100597. enumerable: true,
  100598. configurable: true
  100599. });
  100600. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  100601. /**
  100602. * Gets the number of vertices handled by this manager
  100603. */
  100604. get: function () {
  100605. return this._vertexCount;
  100606. },
  100607. enumerable: true,
  100608. configurable: true
  100609. });
  100610. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  100611. /**
  100612. * Gets a boolean indicating if this manager supports morphing of normals
  100613. */
  100614. get: function () {
  100615. return this._supportsNormals;
  100616. },
  100617. enumerable: true,
  100618. configurable: true
  100619. });
  100620. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  100621. /**
  100622. * Gets a boolean indicating if this manager supports morphing of tangents
  100623. */
  100624. get: function () {
  100625. return this._supportsTangents;
  100626. },
  100627. enumerable: true,
  100628. configurable: true
  100629. });
  100630. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  100631. /**
  100632. * Gets the number of targets stored in this manager
  100633. */
  100634. get: function () {
  100635. return this._targets.length;
  100636. },
  100637. enumerable: true,
  100638. configurable: true
  100639. });
  100640. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  100641. /**
  100642. * Gets the number of influencers (ie. the number of targets with influences > 0)
  100643. */
  100644. get: function () {
  100645. return this._activeTargets.length;
  100646. },
  100647. enumerable: true,
  100648. configurable: true
  100649. });
  100650. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  100651. /**
  100652. * Gets the list of influences (one per target)
  100653. */
  100654. get: function () {
  100655. return this._influences;
  100656. },
  100657. enumerable: true,
  100658. configurable: true
  100659. });
  100660. /**
  100661. * Gets the active target at specified index. An active target is a target with an influence > 0
  100662. * @param index defines the index to check
  100663. * @returns the requested target
  100664. */
  100665. MorphTargetManager.prototype.getActiveTarget = function (index) {
  100666. return this._activeTargets.data[index];
  100667. };
  100668. /**
  100669. * Gets the target at specified index
  100670. * @param index defines the index to check
  100671. * @returns the requested target
  100672. */
  100673. MorphTargetManager.prototype.getTarget = function (index) {
  100674. return this._targets[index];
  100675. };
  100676. /**
  100677. * Add a new target to this manager
  100678. * @param target defines the target to add
  100679. */
  100680. MorphTargetManager.prototype.addTarget = function (target) {
  100681. var _this = this;
  100682. this._targets.push(target);
  100683. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  100684. _this._syncActiveTargets(needUpdate);
  100685. }));
  100686. this._syncActiveTargets(true);
  100687. };
  100688. /**
  100689. * Removes a target from the manager
  100690. * @param target defines the target to remove
  100691. */
  100692. MorphTargetManager.prototype.removeTarget = function (target) {
  100693. var index = this._targets.indexOf(target);
  100694. if (index >= 0) {
  100695. this._targets.splice(index, 1);
  100696. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  100697. this._syncActiveTargets(true);
  100698. }
  100699. };
  100700. /**
  100701. * Serializes the current manager into a Serialization object
  100702. * @returns the serialized object
  100703. */
  100704. MorphTargetManager.prototype.serialize = function () {
  100705. var serializationObject = {};
  100706. serializationObject.id = this.uniqueId;
  100707. serializationObject.targets = [];
  100708. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  100709. var target = _a[_i];
  100710. serializationObject.targets.push(target.serialize());
  100711. }
  100712. return serializationObject;
  100713. };
  100714. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  100715. var influenceCount = 0;
  100716. this._activeTargets.reset();
  100717. this._supportsNormals = true;
  100718. this._supportsTangents = true;
  100719. this._vertexCount = 0;
  100720. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  100721. var target = _a[_i];
  100722. this._activeTargets.push(target);
  100723. this._tempInfluences[influenceCount++] = target.influence;
  100724. var positions = target.getPositions();
  100725. if (positions) {
  100726. this._supportsNormals = this._supportsNormals && target.hasNormals;
  100727. this._supportsTangents = this._supportsTangents && target.hasTangents;
  100728. var vertexCount = positions.length / 3;
  100729. if (this._vertexCount === 0) {
  100730. this._vertexCount = vertexCount;
  100731. }
  100732. else if (this._vertexCount !== vertexCount) {
  100733. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  100734. return;
  100735. }
  100736. }
  100737. }
  100738. if (!this._influences || this._influences.length !== influenceCount) {
  100739. this._influences = new Float32Array(influenceCount);
  100740. }
  100741. for (var index = 0; index < influenceCount; index++) {
  100742. this._influences[index] = this._tempInfluences[index];
  100743. }
  100744. if (needUpdate) {
  100745. this.synchronize();
  100746. }
  100747. };
  100748. /**
  100749. * Syncrhonize the targets with all the meshes using this morph target manager
  100750. */
  100751. MorphTargetManager.prototype.synchronize = function () {
  100752. if (!this._scene) {
  100753. return;
  100754. }
  100755. // Flag meshes as dirty to resync with the active targets
  100756. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  100757. var mesh = _a[_i];
  100758. if (mesh.morphTargetManager === this) {
  100759. mesh._syncGeometryWithMorphTargetManager();
  100760. }
  100761. }
  100762. };
  100763. // Statics
  100764. /**
  100765. * Creates a new MorphTargetManager from serialized data
  100766. * @param serializationObject defines the serialized data
  100767. * @param scene defines the hosting scene
  100768. * @returns the new MorphTargetManager
  100769. */
  100770. MorphTargetManager.Parse = function (serializationObject, scene) {
  100771. var result = new MorphTargetManager(scene);
  100772. result._uniqueId = serializationObject.id;
  100773. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  100774. var targetData = _a[_i];
  100775. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  100776. }
  100777. return result;
  100778. };
  100779. return MorphTargetManager;
  100780. }());
  100781. BABYLON.MorphTargetManager = MorphTargetManager;
  100782. })(BABYLON || (BABYLON = {}));
  100783. //# sourceMappingURL=babylon.morphTargetManager.js.map
  100784. var BABYLON;
  100785. (function (BABYLON) {
  100786. /**
  100787. * Octrees are a really powerful data structure that can quickly select entities based on space coordinates.
  100788. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  100789. */
  100790. var Octree = /** @class */ (function () {
  100791. /**
  100792. * Creates a octree
  100793. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  100794. * @param creationFunc function to be used to instatiate the octree
  100795. * @param maxBlockCapacity defines the maximum number of meshes you want on your octree's leaves (default: 64)
  100796. * @param maxDepth defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.)
  100797. */
  100798. function Octree(creationFunc, maxBlockCapacity,
  100799. /** Defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.) */
  100800. maxDepth) {
  100801. if (maxDepth === void 0) { maxDepth = 2; }
  100802. this.maxDepth = maxDepth;
  100803. /**
  100804. * Content stored in the octree
  100805. */
  100806. this.dynamicContent = new Array();
  100807. this._maxBlockCapacity = maxBlockCapacity || 64;
  100808. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  100809. this._creationFunc = creationFunc;
  100810. }
  100811. // Methods
  100812. /**
  100813. * Updates the octree by adding blocks for the passed in meshes within the min and max world parameters
  100814. * @param worldMin worldMin for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  100815. * @param worldMax worldMax for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  100816. * @param entries meshes to be added to the octree blocks
  100817. */
  100818. Octree.prototype.update = function (worldMin, worldMax, entries) {
  100819. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  100820. };
  100821. /**
  100822. * Adds a mesh to the octree
  100823. * @param entry Mesh to add to the octree
  100824. */
  100825. Octree.prototype.addMesh = function (entry) {
  100826. for (var index = 0; index < this.blocks.length; index++) {
  100827. var block = this.blocks[index];
  100828. block.addEntry(entry);
  100829. }
  100830. };
  100831. /**
  100832. * Selects an array of meshes within the frustum
  100833. * @param frustumPlanes The frustum planes to use which will select all meshes within it
  100834. * @param allowDuplicate If duplicate objects are allowed in the resulting object array
  100835. * @returns array of meshes within the frustum
  100836. */
  100837. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  100838. this._selectionContent.reset();
  100839. for (var index = 0; index < this.blocks.length; index++) {
  100840. var block = this.blocks[index];
  100841. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  100842. }
  100843. if (allowDuplicate) {
  100844. this._selectionContent.concat(this.dynamicContent);
  100845. }
  100846. else {
  100847. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  100848. }
  100849. return this._selectionContent;
  100850. };
  100851. /**
  100852. * Test if the octree intersect with the given bounding sphere and if yes, then add its content to the selection array
  100853. * @param sphereCenter defines the bounding sphere center
  100854. * @param sphereRadius defines the bounding sphere radius
  100855. * @param allowDuplicate defines if the selection array can contains duplicated entries
  100856. * @returns an array of objects that intersect the sphere
  100857. */
  100858. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  100859. this._selectionContent.reset();
  100860. for (var index = 0; index < this.blocks.length; index++) {
  100861. var block = this.blocks[index];
  100862. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  100863. }
  100864. if (allowDuplicate) {
  100865. this._selectionContent.concat(this.dynamicContent);
  100866. }
  100867. else {
  100868. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  100869. }
  100870. return this._selectionContent;
  100871. };
  100872. /**
  100873. * Test if the octree intersect with the given ray and if yes, then add its content to resulting array
  100874. * @param ray defines the ray to test with
  100875. * @returns array of intersected objects
  100876. */
  100877. Octree.prototype.intersectsRay = function (ray) {
  100878. this._selectionContent.reset();
  100879. for (var index = 0; index < this.blocks.length; index++) {
  100880. var block = this.blocks[index];
  100881. block.intersectsRay(ray, this._selectionContent);
  100882. }
  100883. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  100884. return this._selectionContent;
  100885. };
  100886. /**
  100887. * @hidden
  100888. */
  100889. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  100890. target.blocks = new Array();
  100891. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  100892. // Segmenting space
  100893. for (var x = 0; x < 2; x++) {
  100894. for (var y = 0; y < 2; y++) {
  100895. for (var z = 0; z < 2; z++) {
  100896. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  100897. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  100898. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  100899. block.addEntries(entries);
  100900. target.blocks.push(block);
  100901. }
  100902. }
  100903. }
  100904. };
  100905. /**
  100906. * Adds a mesh into the octree block if it intersects the block
  100907. */
  100908. Octree.CreationFuncForMeshes = function (entry, block) {
  100909. var boundingInfo = entry.getBoundingInfo();
  100910. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  100911. block.entries.push(entry);
  100912. }
  100913. };
  100914. /**
  100915. * Adds a submesh into the octree block if it intersects the block
  100916. */
  100917. Octree.CreationFuncForSubMeshes = function (entry, block) {
  100918. var boundingInfo = entry.getBoundingInfo();
  100919. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  100920. block.entries.push(entry);
  100921. }
  100922. };
  100923. return Octree;
  100924. }());
  100925. BABYLON.Octree = Octree;
  100926. })(BABYLON || (BABYLON = {}));
  100927. //# sourceMappingURL=babylon.octree.js.map
  100928. var BABYLON;
  100929. (function (BABYLON) {
  100930. /**
  100931. * Class used to store a cell in an octree
  100932. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  100933. */
  100934. var OctreeBlock = /** @class */ (function () {
  100935. /**
  100936. * Creates a new block
  100937. * @param minPoint defines the minimum vector (in world space) of the block's bounding box
  100938. * @param maxPoint defines the maximum vector (in world space) of the block's bounding box
  100939. * @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  100940. * @param depth defines the current depth of this block in the octree
  100941. * @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored)
  100942. * @param creationFunc defines a callback to call when an element is added to the block
  100943. */
  100944. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  100945. /**
  100946. * Gets the content of the current block
  100947. */
  100948. this.entries = new Array();
  100949. this._boundingVectors = new Array();
  100950. this._capacity = capacity;
  100951. this._depth = depth;
  100952. this._maxDepth = maxDepth;
  100953. this._creationFunc = creationFunc;
  100954. this._minPoint = minPoint;
  100955. this._maxPoint = maxPoint;
  100956. this._boundingVectors.push(minPoint.clone());
  100957. this._boundingVectors.push(maxPoint.clone());
  100958. this._boundingVectors.push(minPoint.clone());
  100959. this._boundingVectors[2].x = maxPoint.x;
  100960. this._boundingVectors.push(minPoint.clone());
  100961. this._boundingVectors[3].y = maxPoint.y;
  100962. this._boundingVectors.push(minPoint.clone());
  100963. this._boundingVectors[4].z = maxPoint.z;
  100964. this._boundingVectors.push(maxPoint.clone());
  100965. this._boundingVectors[5].z = minPoint.z;
  100966. this._boundingVectors.push(maxPoint.clone());
  100967. this._boundingVectors[6].x = minPoint.x;
  100968. this._boundingVectors.push(maxPoint.clone());
  100969. this._boundingVectors[7].y = minPoint.y;
  100970. }
  100971. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  100972. // Property
  100973. /**
  100974. * Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  100975. */
  100976. get: function () {
  100977. return this._capacity;
  100978. },
  100979. enumerable: true,
  100980. configurable: true
  100981. });
  100982. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  100983. /**
  100984. * Gets the minimum vector (in world space) of the block's bounding box
  100985. */
  100986. get: function () {
  100987. return this._minPoint;
  100988. },
  100989. enumerable: true,
  100990. configurable: true
  100991. });
  100992. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  100993. /**
  100994. * Gets the maximum vector (in world space) of the block's bounding box
  100995. */
  100996. get: function () {
  100997. return this._maxPoint;
  100998. },
  100999. enumerable: true,
  101000. configurable: true
  101001. });
  101002. // Methods
  101003. /**
  101004. * Add a new element to this block
  101005. * @param entry defines the element to add
  101006. */
  101007. OctreeBlock.prototype.addEntry = function (entry) {
  101008. if (this.blocks) {
  101009. for (var index = 0; index < this.blocks.length; index++) {
  101010. var block = this.blocks[index];
  101011. block.addEntry(entry);
  101012. }
  101013. return;
  101014. }
  101015. this._creationFunc(entry, this);
  101016. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  101017. this.createInnerBlocks();
  101018. }
  101019. };
  101020. /**
  101021. * Add an array of elements to this block
  101022. * @param entries defines the array of elements to add
  101023. */
  101024. OctreeBlock.prototype.addEntries = function (entries) {
  101025. for (var index = 0; index < entries.length; index++) {
  101026. var mesh = entries[index];
  101027. this.addEntry(mesh);
  101028. }
  101029. };
  101030. /**
  101031. * Test if the current block intersects the furstum planes and if yes, then add its content to the selection array
  101032. * @param frustumPlanes defines the frustum planes to test
  101033. * @param selection defines the array to store current content if selection is positive
  101034. * @param allowDuplicate defines if the selection array can contains duplicated entries
  101035. */
  101036. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  101037. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  101038. if (this.blocks) {
  101039. for (var index = 0; index < this.blocks.length; index++) {
  101040. var block = this.blocks[index];
  101041. block.select(frustumPlanes, selection, allowDuplicate);
  101042. }
  101043. return;
  101044. }
  101045. if (allowDuplicate) {
  101046. selection.concat(this.entries);
  101047. }
  101048. else {
  101049. selection.concatWithNoDuplicate(this.entries);
  101050. }
  101051. }
  101052. };
  101053. /**
  101054. * Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array
  101055. * @param sphereCenter defines the bounding sphere center
  101056. * @param sphereRadius defines the bounding sphere radius
  101057. * @param selection defines the array to store current content if selection is positive
  101058. * @param allowDuplicate defines if the selection array can contains duplicated entries
  101059. */
  101060. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  101061. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  101062. if (this.blocks) {
  101063. for (var index = 0; index < this.blocks.length; index++) {
  101064. var block = this.blocks[index];
  101065. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  101066. }
  101067. return;
  101068. }
  101069. if (allowDuplicate) {
  101070. selection.concat(this.entries);
  101071. }
  101072. else {
  101073. selection.concatWithNoDuplicate(this.entries);
  101074. }
  101075. }
  101076. };
  101077. /**
  101078. * Test if the current block intersect with the given ray and if yes, then add its content to the selection array
  101079. * @param ray defines the ray to test with
  101080. * @param selection defines the array to store current content if selection is positive
  101081. */
  101082. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  101083. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  101084. if (this.blocks) {
  101085. for (var index = 0; index < this.blocks.length; index++) {
  101086. var block = this.blocks[index];
  101087. block.intersectsRay(ray, selection);
  101088. }
  101089. return;
  101090. }
  101091. selection.concatWithNoDuplicate(this.entries);
  101092. }
  101093. };
  101094. /**
  101095. * Subdivide the content into child blocks (this block will then be empty)
  101096. */
  101097. OctreeBlock.prototype.createInnerBlocks = function () {
  101098. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  101099. };
  101100. return OctreeBlock;
  101101. }());
  101102. BABYLON.OctreeBlock = OctreeBlock;
  101103. })(BABYLON || (BABYLON = {}));
  101104. //# sourceMappingURL=babylon.octreeBlock.js.map
  101105. var BABYLON;
  101106. (function (BABYLON) {
  101107. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  101108. if (maxCapacity === void 0) { maxCapacity = 64; }
  101109. if (maxDepth === void 0) { maxDepth = 2; }
  101110. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  101111. if (!component) {
  101112. component = new OctreeSceneComponent(this);
  101113. this._addComponent(component);
  101114. }
  101115. if (!this._selectionOctree) {
  101116. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  101117. }
  101118. var worldExtends = this.getWorldExtends();
  101119. // Update octree
  101120. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  101121. return this._selectionOctree;
  101122. };
  101123. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  101124. get: function () {
  101125. return this._selectionOctree;
  101126. },
  101127. enumerable: true,
  101128. configurable: true
  101129. });
  101130. /**
  101131. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  101132. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  101133. * @param maxCapacity defines the maximum size of each block (64 by default)
  101134. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  101135. * @returns the new octree
  101136. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  101137. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  101138. */
  101139. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  101140. if (maxCapacity === void 0) { maxCapacity = 64; }
  101141. if (maxDepth === void 0) { maxDepth = 2; }
  101142. var scene = this.getScene();
  101143. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  101144. if (!component) {
  101145. component = new OctreeSceneComponent(scene);
  101146. scene._addComponent(component);
  101147. }
  101148. if (!this._submeshesOctree) {
  101149. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  101150. }
  101151. this.computeWorldMatrix(true);
  101152. var boundingInfo = this.getBoundingInfo();
  101153. // Update octree
  101154. var bbox = boundingInfo.boundingBox;
  101155. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  101156. return this._submeshesOctree;
  101157. };
  101158. /**
  101159. * Defines the octree scene component responsible to manage any octrees
  101160. * in a given scene.
  101161. */
  101162. var OctreeSceneComponent = /** @class */ (function () {
  101163. /**
  101164. * Creates a new instance of the component for the given scene
  101165. * @param scene Defines the scene to register the component in
  101166. */
  101167. function OctreeSceneComponent(scene) {
  101168. /**
  101169. * The component name helpfull to identify the component in the list of scene components.
  101170. */
  101171. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  101172. /**
  101173. * Indicates if the meshes have been checked to make sure they are isEnabled()
  101174. */
  101175. this.checksIsEnabled = true;
  101176. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  101177. this.scene = scene;
  101178. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  101179. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  101180. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  101181. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  101182. }
  101183. /**
  101184. * Registers the component in a given scene
  101185. */
  101186. OctreeSceneComponent.prototype.register = function () {
  101187. var _this = this;
  101188. this.scene.onMeshRemovedObservable.add(function (mesh) {
  101189. var sceneOctree = _this.scene.selectionOctree;
  101190. if (sceneOctree !== undefined && sceneOctree !== null) {
  101191. var index = sceneOctree.dynamicContent.indexOf(mesh);
  101192. if (index !== -1) {
  101193. sceneOctree.dynamicContent.splice(index, 1);
  101194. }
  101195. }
  101196. });
  101197. this.scene.onMeshImportedObservable.add(function (mesh) {
  101198. var sceneOctree = _this.scene.selectionOctree;
  101199. if (sceneOctree !== undefined && sceneOctree !== null) {
  101200. sceneOctree.addMesh(mesh);
  101201. }
  101202. });
  101203. };
  101204. /**
  101205. * Return the list of active meshes
  101206. * @returns the list of active meshes
  101207. */
  101208. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  101209. if (this.scene._selectionOctree) {
  101210. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  101211. return selection;
  101212. }
  101213. return this.scene._getDefaultMeshCandidates();
  101214. };
  101215. /**
  101216. * Return the list of active sub meshes
  101217. * @param mesh The mesh to get the candidates sub meshes from
  101218. * @returns the list of active sub meshes
  101219. */
  101220. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  101221. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  101222. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  101223. return intersections;
  101224. }
  101225. return this.scene._getDefaultSubMeshCandidates(mesh);
  101226. };
  101227. /**
  101228. * Return the list of sub meshes intersecting with a given local ray
  101229. * @param mesh defines the mesh to find the submesh for
  101230. * @param localRay defines the ray in local space
  101231. * @returns the list of intersecting sub meshes
  101232. */
  101233. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  101234. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  101235. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  101236. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  101237. return intersections;
  101238. }
  101239. return this.scene._getDefaultSubMeshCandidates(mesh);
  101240. };
  101241. /**
  101242. * Return the list of sub meshes colliding with a collider
  101243. * @param mesh defines the mesh to find the submesh for
  101244. * @param collider defines the collider to evaluate the collision against
  101245. * @returns the list of colliding sub meshes
  101246. */
  101247. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  101248. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  101249. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  101250. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  101251. return intersections;
  101252. }
  101253. return this.scene._getDefaultSubMeshCandidates(mesh);
  101254. };
  101255. /**
  101256. * Rebuilds the elements related to this component in case of
  101257. * context lost for instance.
  101258. */
  101259. OctreeSceneComponent.prototype.rebuild = function () {
  101260. // Nothing to do here.
  101261. };
  101262. /**
  101263. * Disposes the component and the associated ressources.
  101264. */
  101265. OctreeSceneComponent.prototype.dispose = function () {
  101266. // Nothing to do here.
  101267. };
  101268. return OctreeSceneComponent;
  101269. }());
  101270. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  101271. })(BABYLON || (BABYLON = {}));
  101272. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  101273. var BABYLON;
  101274. (function (BABYLON) {
  101275. /**
  101276. * Postprocess used to generate anaglyphic rendering
  101277. */
  101278. var AnaglyphPostProcess = /** @class */ (function (_super) {
  101279. __extends(AnaglyphPostProcess, _super);
  101280. /**
  101281. * Creates a new AnaglyphPostProcess
  101282. * @param name defines postprocess name
  101283. * @param options defines creation options or target ratio scale
  101284. * @param rigCameras defines cameras using this postprocess
  101285. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  101286. * @param engine defines hosting engine
  101287. * @param reusable defines if the postprocess will be reused multiple times per frame
  101288. */
  101289. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  101290. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  101291. _this._passedProcess = rigCameras[0]._rigPostProcess;
  101292. _this.onApplyObservable.add(function (effect) {
  101293. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  101294. });
  101295. return _this;
  101296. }
  101297. return AnaglyphPostProcess;
  101298. }(BABYLON.PostProcess));
  101299. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  101300. })(BABYLON || (BABYLON = {}));
  101301. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  101302. var BABYLON;
  101303. (function (BABYLON) {
  101304. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  101305. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  101306. });
  101307. /**
  101308. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  101309. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  101310. */
  101311. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  101312. __extends(AnaglyphArcRotateCamera, _super);
  101313. /**
  101314. * Creates a new AnaglyphArcRotateCamera
  101315. * @param name defines camera name
  101316. * @param alpha defines alpha angle (in radians)
  101317. * @param beta defines beta angle (in radians)
  101318. * @param radius defines radius
  101319. * @param target defines camera target
  101320. * @param interaxialDistance defines distance between each color axis
  101321. * @param scene defines the hosting scene
  101322. */
  101323. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  101324. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  101325. _this.interaxialDistance = interaxialDistance;
  101326. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  101327. return _this;
  101328. }
  101329. /**
  101330. * Gets camera class name
  101331. * @returns AnaglyphArcRotateCamera
  101332. */
  101333. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  101334. return "AnaglyphArcRotateCamera";
  101335. };
  101336. return AnaglyphArcRotateCamera;
  101337. }(BABYLON.ArcRotateCamera));
  101338. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  101339. })(BABYLON || (BABYLON = {}));
  101340. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  101341. var BABYLON;
  101342. (function (BABYLON) {
  101343. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  101344. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  101345. });
  101346. /**
  101347. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  101348. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  101349. */
  101350. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  101351. __extends(AnaglyphFreeCamera, _super);
  101352. /**
  101353. * Creates a new AnaglyphFreeCamera
  101354. * @param name defines camera name
  101355. * @param position defines initial position
  101356. * @param interaxialDistance defines distance between each color axis
  101357. * @param scene defines the hosting scene
  101358. */
  101359. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  101360. var _this = _super.call(this, name, position, scene) || this;
  101361. _this.interaxialDistance = interaxialDistance;
  101362. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  101363. return _this;
  101364. }
  101365. /**
  101366. * Gets camera class name
  101367. * @returns AnaglyphFreeCamera
  101368. */
  101369. AnaglyphFreeCamera.prototype.getClassName = function () {
  101370. return "AnaglyphFreeCamera";
  101371. };
  101372. return AnaglyphFreeCamera;
  101373. }(BABYLON.FreeCamera));
  101374. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  101375. })(BABYLON || (BABYLON = {}));
  101376. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  101377. var BABYLON;
  101378. (function (BABYLON) {
  101379. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  101380. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  101381. });
  101382. /**
  101383. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  101384. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  101385. */
  101386. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  101387. __extends(AnaglyphGamepadCamera, _super);
  101388. /**
  101389. * Creates a new AnaglyphGamepadCamera
  101390. * @param name defines camera name
  101391. * @param position defines initial position
  101392. * @param interaxialDistance defines distance between each color axis
  101393. * @param scene defines the hosting scene
  101394. */
  101395. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  101396. var _this = _super.call(this, name, position, scene) || this;
  101397. _this.interaxialDistance = interaxialDistance;
  101398. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  101399. return _this;
  101400. }
  101401. /**
  101402. * Gets camera class name
  101403. * @returns AnaglyphGamepadCamera
  101404. */
  101405. AnaglyphGamepadCamera.prototype.getClassName = function () {
  101406. return "AnaglyphGamepadCamera";
  101407. };
  101408. return AnaglyphGamepadCamera;
  101409. }(BABYLON.GamepadCamera));
  101410. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  101411. })(BABYLON || (BABYLON = {}));
  101412. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  101413. var BABYLON;
  101414. (function (BABYLON) {
  101415. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  101416. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  101417. });
  101418. /**
  101419. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  101420. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  101421. */
  101422. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  101423. __extends(AnaglyphUniversalCamera, _super);
  101424. /**
  101425. * Creates a new AnaglyphUniversalCamera
  101426. * @param name defines camera name
  101427. * @param position defines initial position
  101428. * @param interaxialDistance defines distance between each color axis
  101429. * @param scene defines the hosting scene
  101430. */
  101431. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  101432. var _this = _super.call(this, name, position, scene) || this;
  101433. _this.interaxialDistance = interaxialDistance;
  101434. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  101435. return _this;
  101436. }
  101437. /**
  101438. * Gets camera class name
  101439. * @returns AnaglyphUniversalCamera
  101440. */
  101441. AnaglyphUniversalCamera.prototype.getClassName = function () {
  101442. return "AnaglyphUniversalCamera";
  101443. };
  101444. return AnaglyphUniversalCamera;
  101445. }(BABYLON.UniversalCamera));
  101446. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  101447. })(BABYLON || (BABYLON = {}));
  101448. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  101449. var BABYLON;
  101450. (function (BABYLON) {
  101451. /**
  101452. * StereoscopicInterlacePostProcess used to render stereo views from a rigged camera
  101453. */
  101454. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  101455. __extends(StereoscopicInterlacePostProcess, _super);
  101456. /**
  101457. * Initializes a StereoscopicInterlacePostProcess
  101458. * @param name The name of the effect.
  101459. * @param rigCameras The rig cameras to be appled to the post process
  101460. * @param isStereoscopicHoriz If the rendered results are horizontal or verticle
  101461. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  101462. * @param engine The engine which the post process will be applied. (default: current engine)
  101463. * @param reusable If the post process can be reused on the same frame. (default: false)
  101464. */
  101465. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  101466. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  101467. _this._passedProcess = rigCameras[0]._rigPostProcess;
  101468. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  101469. _this.onSizeChangedObservable.add(function () {
  101470. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  101471. });
  101472. _this.onApplyObservable.add(function (effect) {
  101473. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  101474. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  101475. });
  101476. return _this;
  101477. }
  101478. return StereoscopicInterlacePostProcess;
  101479. }(BABYLON.PostProcess));
  101480. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  101481. })(BABYLON || (BABYLON = {}));
  101482. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  101483. var BABYLON;
  101484. (function (BABYLON) {
  101485. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  101486. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  101487. });
  101488. /**
  101489. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  101490. * @see http://doc.babylonjs.com/features/cameras
  101491. */
  101492. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  101493. __extends(StereoscopicArcRotateCamera, _super);
  101494. /**
  101495. * Creates a new StereoscopicArcRotateCamera
  101496. * @param name defines camera name
  101497. * @param alpha defines alpha angle (in radians)
  101498. * @param beta defines beta angle (in radians)
  101499. * @param radius defines radius
  101500. * @param target defines camera target
  101501. * @param interaxialDistance defines distance between each color axis
  101502. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  101503. * @param scene defines the hosting scene
  101504. */
  101505. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  101506. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  101507. _this.interaxialDistance = interaxialDistance;
  101508. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  101509. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  101510. return _this;
  101511. }
  101512. /**
  101513. * Gets camera class name
  101514. * @returns StereoscopicArcRotateCamera
  101515. */
  101516. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  101517. return "StereoscopicArcRotateCamera";
  101518. };
  101519. return StereoscopicArcRotateCamera;
  101520. }(BABYLON.ArcRotateCamera));
  101521. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  101522. })(BABYLON || (BABYLON = {}));
  101523. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  101524. var BABYLON;
  101525. (function (BABYLON) {
  101526. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  101527. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  101528. });
  101529. /**
  101530. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  101531. * @see http://doc.babylonjs.com/features/cameras
  101532. */
  101533. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  101534. __extends(StereoscopicFreeCamera, _super);
  101535. /**
  101536. * Creates a new StereoscopicFreeCamera
  101537. * @param name defines camera name
  101538. * @param position defines initial position
  101539. * @param interaxialDistance defines distance between each color axis
  101540. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  101541. * @param scene defines the hosting scene
  101542. */
  101543. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  101544. var _this = _super.call(this, name, position, scene) || this;
  101545. _this.interaxialDistance = interaxialDistance;
  101546. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  101547. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  101548. return _this;
  101549. }
  101550. /**
  101551. * Gets camera class name
  101552. * @returns StereoscopicFreeCamera
  101553. */
  101554. StereoscopicFreeCamera.prototype.getClassName = function () {
  101555. return "StereoscopicFreeCamera";
  101556. };
  101557. return StereoscopicFreeCamera;
  101558. }(BABYLON.FreeCamera));
  101559. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  101560. })(BABYLON || (BABYLON = {}));
  101561. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  101562. var BABYLON;
  101563. (function (BABYLON) {
  101564. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  101565. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  101566. });
  101567. /**
  101568. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  101569. * @see http://doc.babylonjs.com/features/cameras
  101570. */
  101571. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  101572. __extends(StereoscopicGamepadCamera, _super);
  101573. /**
  101574. * Creates a new StereoscopicGamepadCamera
  101575. * @param name defines camera name
  101576. * @param position defines initial position
  101577. * @param interaxialDistance defines distance between each color axis
  101578. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  101579. * @param scene defines the hosting scene
  101580. */
  101581. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  101582. var _this = _super.call(this, name, position, scene) || this;
  101583. _this.interaxialDistance = interaxialDistance;
  101584. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  101585. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  101586. return _this;
  101587. }
  101588. /**
  101589. * Gets camera class name
  101590. * @returns StereoscopicGamepadCamera
  101591. */
  101592. StereoscopicGamepadCamera.prototype.getClassName = function () {
  101593. return "StereoscopicGamepadCamera";
  101594. };
  101595. return StereoscopicGamepadCamera;
  101596. }(BABYLON.GamepadCamera));
  101597. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  101598. })(BABYLON || (BABYLON = {}));
  101599. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  101600. var BABYLON;
  101601. (function (BABYLON) {
  101602. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  101603. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  101604. });
  101605. /**
  101606. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  101607. * @see http://doc.babylonjs.com/features/cameras
  101608. */
  101609. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  101610. __extends(StereoscopicUniversalCamera, _super);
  101611. /**
  101612. * Creates a new StereoscopicUniversalCamera
  101613. * @param name defines camera name
  101614. * @param position defines initial position
  101615. * @param interaxialDistance defines distance between each color axis
  101616. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  101617. * @param scene defines the hosting scene
  101618. */
  101619. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  101620. var _this = _super.call(this, name, position, scene) || this;
  101621. _this.interaxialDistance = interaxialDistance;
  101622. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  101623. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  101624. return _this;
  101625. }
  101626. /**
  101627. * Gets camera class name
  101628. * @returns StereoscopicUniversalCamera
  101629. */
  101630. StereoscopicUniversalCamera.prototype.getClassName = function () {
  101631. return "StereoscopicUniversalCamera";
  101632. };
  101633. return StereoscopicUniversalCamera;
  101634. }(BABYLON.UniversalCamera));
  101635. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  101636. })(BABYLON || (BABYLON = {}));
  101637. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  101638. var BABYLON;
  101639. (function (BABYLON) {
  101640. /**
  101641. * VRDistortionCorrectionPostProcess used for mobile VR
  101642. */
  101643. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  101644. __extends(VRDistortionCorrectionPostProcess, _super);
  101645. /**
  101646. * Initializes the VRDistortionCorrectionPostProcess
  101647. * @param name The name of the effect.
  101648. * @param camera The camera to apply the render pass to.
  101649. * @param isRightEye If this is for the right eye distortion
  101650. * @param vrMetrics All the required metrics for the VR camera
  101651. */
  101652. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  101653. var _this = _super.call(this, name, "vrDistortionCorrection", [
  101654. 'LensCenter',
  101655. 'Scale',
  101656. 'ScaleIn',
  101657. 'HmdWarpParam'
  101658. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  101659. _this._isRightEye = isRightEye;
  101660. _this._distortionFactors = vrMetrics.distortionK;
  101661. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  101662. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  101663. _this.adaptScaleToCurrentViewport = true;
  101664. _this.onSizeChangedObservable.add(function () {
  101665. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  101666. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  101667. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  101668. });
  101669. _this.onApplyObservable.add(function (effect) {
  101670. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  101671. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  101672. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  101673. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  101674. });
  101675. return _this;
  101676. }
  101677. return VRDistortionCorrectionPostProcess;
  101678. }(BABYLON.PostProcess));
  101679. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  101680. })(BABYLON || (BABYLON = {}));
  101681. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  101682. var BABYLON;
  101683. (function (BABYLON) {
  101684. /**
  101685. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  101686. * Screen rotation is taken into account.
  101687. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  101688. */
  101689. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  101690. /**
  101691. * Instantiates a new input
  101692. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  101693. */
  101694. function FreeCameraDeviceOrientationInput() {
  101695. var _this = this;
  101696. this._screenOrientationAngle = 0;
  101697. this._screenQuaternion = new BABYLON.Quaternion();
  101698. this._alpha = 0;
  101699. this._beta = 0;
  101700. this._gamma = 0;
  101701. this._orientationChanged = function () {
  101702. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  101703. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  101704. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  101705. };
  101706. this._deviceOrientation = function (evt) {
  101707. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  101708. _this._beta = evt.beta !== null ? evt.beta : 0;
  101709. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  101710. };
  101711. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  101712. this._orientationChanged();
  101713. }
  101714. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  101715. /**
  101716. * Define the camera controlled by the input.
  101717. */
  101718. get: function () {
  101719. return this._camera;
  101720. },
  101721. set: function (camera) {
  101722. this._camera = camera;
  101723. if (this._camera != null && !this._camera.rotationQuaternion) {
  101724. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  101725. }
  101726. },
  101727. enumerable: true,
  101728. configurable: true
  101729. });
  101730. /**
  101731. * Attach the input controls to a specific dom element to get the input from.
  101732. * @param element Defines the element the controls should be listened from
  101733. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  101734. */
  101735. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  101736. window.addEventListener("orientationchange", this._orientationChanged);
  101737. window.addEventListener("deviceorientation", this._deviceOrientation);
  101738. //In certain cases, the attach control is called AFTER orientation was changed,
  101739. //So this is needed.
  101740. this._orientationChanged();
  101741. };
  101742. /**
  101743. * Detach the current controls from the specified dom element.
  101744. * @param element Defines the element to stop listening the inputs from
  101745. */
  101746. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  101747. window.removeEventListener("orientationchange", this._orientationChanged);
  101748. window.removeEventListener("deviceorientation", this._deviceOrientation);
  101749. };
  101750. /**
  101751. * Update the current camera state depending on the inputs that have been used this frame.
  101752. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  101753. */
  101754. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  101755. //if no device orientation provided, don't update the rotation.
  101756. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  101757. if (!this._alpha)
  101758. return;
  101759. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  101760. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  101761. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  101762. //Mirror on XY Plane
  101763. this._camera.rotationQuaternion.z *= -1;
  101764. this._camera.rotationQuaternion.w *= -1;
  101765. };
  101766. /**
  101767. * Gets the class name of the current intput.
  101768. * @returns the class name
  101769. */
  101770. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  101771. return "FreeCameraDeviceOrientationInput";
  101772. };
  101773. /**
  101774. * Get the friendly name associated with the input class.
  101775. * @returns the input friendly name
  101776. */
  101777. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  101778. return "deviceOrientation";
  101779. };
  101780. return FreeCameraDeviceOrientationInput;
  101781. }());
  101782. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  101783. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  101784. })(BABYLON || (BABYLON = {}));
  101785. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  101786. var BABYLON;
  101787. (function (BABYLON) {
  101788. /**
  101789. * Manage the device orientation inputs (gyroscope) to control an arc rotate camera.
  101790. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  101791. */
  101792. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  101793. /**
  101794. * Instantiate a new ArcRotateCameraVRDeviceOrientationInput.
  101795. */
  101796. function ArcRotateCameraVRDeviceOrientationInput() {
  101797. /**
  101798. * Defines a correction factor applied on the alpha value retrieved from the orientation events.
  101799. */
  101800. this.alphaCorrection = 1;
  101801. /**
  101802. * Defines a correction factor applied on the beta value retrieved from the orientation events.
  101803. */
  101804. this.betaCorrection = 1;
  101805. /**
  101806. * Defines a correction factor applied on the gamma value retrieved from the orientation events.
  101807. */
  101808. this.gammaCorrection = 1;
  101809. this._alpha = 0;
  101810. this._gamma = 0;
  101811. this._dirty = false;
  101812. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  101813. }
  101814. /**
  101815. * Attach the input controls to a specific dom element to get the input from.
  101816. * @param element Defines the element the controls should be listened from
  101817. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  101818. */
  101819. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  101820. this.camera.attachControl(element, noPreventDefault);
  101821. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  101822. };
  101823. /** @hidden */
  101824. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  101825. if (evt.alpha !== null) {
  101826. this._alpha = +evt.alpha | 0;
  101827. }
  101828. if (evt.gamma !== null) {
  101829. this._gamma = +evt.gamma | 0;
  101830. }
  101831. this._dirty = true;
  101832. };
  101833. /**
  101834. * Update the current camera state depending on the inputs that have been used this frame.
  101835. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  101836. */
  101837. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  101838. if (this._dirty) {
  101839. this._dirty = false;
  101840. if (this._gamma < 0) {
  101841. this._gamma = 180 + this._gamma;
  101842. }
  101843. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  101844. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  101845. }
  101846. };
  101847. /**
  101848. * Detach the current controls from the specified dom element.
  101849. * @param element Defines the element to stop listening the inputs from
  101850. */
  101851. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  101852. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  101853. };
  101854. /**
  101855. * Gets the class name of the current intput.
  101856. * @returns the class name
  101857. */
  101858. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  101859. return "ArcRotateCameraVRDeviceOrientationInput";
  101860. };
  101861. /**
  101862. * Get the friendly name associated with the input class.
  101863. * @returns the input friendly name
  101864. */
  101865. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  101866. return "VRDeviceOrientation";
  101867. };
  101868. return ArcRotateCameraVRDeviceOrientationInput;
  101869. }());
  101870. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  101871. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  101872. })(BABYLON || (BABYLON = {}));
  101873. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  101874. var BABYLON;
  101875. (function (BABYLON) {
  101876. /**
  101877. * This represents all the required metrics to create a VR camera.
  101878. * @see http://doc.babylonjs.com/babylon101/cameras#device-orientation-camera
  101879. */
  101880. var VRCameraMetrics = /** @class */ (function () {
  101881. function VRCameraMetrics() {
  101882. /**
  101883. * Define if the current vr camera should compensate the distortion of the lense or not.
  101884. */
  101885. this.compensateDistortion = true;
  101886. }
  101887. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  101888. /**
  101889. * Gets the rendering aspect ratio based on the provided resolutions.
  101890. */
  101891. get: function () {
  101892. return this.hResolution / (2 * this.vResolution);
  101893. },
  101894. enumerable: true,
  101895. configurable: true
  101896. });
  101897. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  101898. /**
  101899. * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes.
  101900. */
  101901. get: function () {
  101902. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  101903. },
  101904. enumerable: true,
  101905. configurable: true
  101906. });
  101907. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  101908. /**
  101909. * @hidden
  101910. */
  101911. get: function () {
  101912. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  101913. var h = (4 * meters) / this.hScreenSize;
  101914. return BABYLON.Matrix.Translation(h, 0, 0);
  101915. },
  101916. enumerable: true,
  101917. configurable: true
  101918. });
  101919. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  101920. /**
  101921. * @hidden
  101922. */
  101923. get: function () {
  101924. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  101925. var h = (4 * meters) / this.hScreenSize;
  101926. return BABYLON.Matrix.Translation(-h, 0, 0);
  101927. },
  101928. enumerable: true,
  101929. configurable: true
  101930. });
  101931. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  101932. /**
  101933. * @hidden
  101934. */
  101935. get: function () {
  101936. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  101937. },
  101938. enumerable: true,
  101939. configurable: true
  101940. });
  101941. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  101942. /**
  101943. * @hidden
  101944. */
  101945. get: function () {
  101946. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  101947. },
  101948. enumerable: true,
  101949. configurable: true
  101950. });
  101951. /**
  101952. * Get the default VRMetrics based on the most generic setup.
  101953. * @returns the default vr metrics
  101954. */
  101955. VRCameraMetrics.GetDefault = function () {
  101956. var result = new VRCameraMetrics();
  101957. result.hResolution = 1280;
  101958. result.vResolution = 800;
  101959. result.hScreenSize = 0.149759993;
  101960. result.vScreenSize = 0.0935999975;
  101961. result.vScreenCenter = 0.0467999987;
  101962. result.eyeToScreenDistance = 0.0410000011;
  101963. result.lensSeparationDistance = 0.0635000020;
  101964. result.interpupillaryDistance = 0.0640000030;
  101965. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  101966. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  101967. result.postProcessScaleFactor = 1.714605507808412;
  101968. result.lensCenterOffset = 0.151976421;
  101969. return result;
  101970. };
  101971. return VRCameraMetrics;
  101972. }());
  101973. BABYLON.VRCameraMetrics = VRCameraMetrics;
  101974. })(BABYLON || (BABYLON = {}));
  101975. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  101976. var BABYLON;
  101977. (function (BABYLON) {
  101978. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  101979. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  101980. });
  101981. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  101982. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  101983. });
  101984. /**
  101985. * This represents a WebVR camera.
  101986. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  101987. * @example http://doc.babylonjs.com/how_to/webvr_camera
  101988. */
  101989. var WebVRFreeCamera = /** @class */ (function (_super) {
  101990. __extends(WebVRFreeCamera, _super);
  101991. /**
  101992. * Instantiates a WebVRFreeCamera.
  101993. * @param name The name of the WebVRFreeCamera
  101994. * @param position The starting anchor position for the camera
  101995. * @param scene The scene the camera belongs to
  101996. * @param webVROptions a set of customizable options for the webVRCamera
  101997. */
  101998. function WebVRFreeCamera(name, position, scene, webVROptions) {
  101999. if (webVROptions === void 0) { webVROptions = {}; }
  102000. var _this = _super.call(this, name, position, scene) || this;
  102001. _this.webVROptions = webVROptions;
  102002. /**
  102003. * @hidden
  102004. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  102005. */
  102006. _this._vrDevice = null;
  102007. /**
  102008. * The rawPose of the vrDevice.
  102009. */
  102010. _this.rawPose = null;
  102011. _this._specsVersion = "1.1";
  102012. _this._attached = false;
  102013. _this._descendants = [];
  102014. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  102015. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  102016. /** @hidden */
  102017. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  102018. _this._standingMatrix = null;
  102019. /**
  102020. * Represents device position in babylon space.
  102021. */
  102022. _this.devicePosition = BABYLON.Vector3.Zero();
  102023. /**
  102024. * Represents device rotation in babylon space.
  102025. */
  102026. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  102027. /**
  102028. * The scale of the device to be used when translating from device space to babylon space.
  102029. */
  102030. _this.deviceScaleFactor = 1;
  102031. _this._deviceToWorld = BABYLON.Matrix.Identity();
  102032. _this._worldToDevice = BABYLON.Matrix.Identity();
  102033. /**
  102034. * References to the webVR controllers for the vrDevice.
  102035. */
  102036. _this.controllers = [];
  102037. /**
  102038. * Emits an event when a controller is attached.
  102039. */
  102040. _this.onControllersAttachedObservable = new BABYLON.Observable();
  102041. /**
  102042. * Emits an event when a controller's mesh has been loaded;
  102043. */
  102044. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  102045. /**
  102046. * Emits an event when the HMD's pose has been updated.
  102047. */
  102048. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  102049. _this._poseSet = false;
  102050. /**
  102051. * If the rig cameras be used as parent instead of this camera.
  102052. */
  102053. _this.rigParenting = true;
  102054. _this._defaultHeight = undefined;
  102055. _this._htmlElementAttached = null;
  102056. _this._detachIfAttached = function () {
  102057. var vrDisplay = _this.getEngine().getVRDevice();
  102058. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  102059. _this.detachControl(_this._htmlElementAttached);
  102060. }
  102061. };
  102062. _this._workingVector = BABYLON.Vector3.Zero();
  102063. _this._oneVector = BABYLON.Vector3.One();
  102064. _this._workingMatrix = BABYLON.Matrix.Identity();
  102065. _this._tmpMatrix = new BABYLON.Matrix();
  102066. _this._cache.position = BABYLON.Vector3.Zero();
  102067. if (webVROptions.defaultHeight) {
  102068. _this._defaultHeight = webVROptions.defaultHeight;
  102069. _this.position.y = _this._defaultHeight;
  102070. }
  102071. _this.minZ = 0.1;
  102072. //legacy support - the compensation boolean was removed.
  102073. if (arguments.length === 5) {
  102074. _this.webVROptions = arguments[4];
  102075. }
  102076. // default webVR options
  102077. if (_this.webVROptions.trackPosition == undefined) {
  102078. _this.webVROptions.trackPosition = true;
  102079. }
  102080. if (_this.webVROptions.controllerMeshes == undefined) {
  102081. _this.webVROptions.controllerMeshes = true;
  102082. }
  102083. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  102084. _this.webVROptions.defaultLightingOnControllers = true;
  102085. }
  102086. _this.rotationQuaternion = new BABYLON.Quaternion();
  102087. if (_this.webVROptions && _this.webVROptions.positionScale) {
  102088. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  102089. }
  102090. //enable VR
  102091. var engine = _this.getEngine();
  102092. _this._onVREnabled = function (success) { if (success) {
  102093. _this.initControllers();
  102094. } };
  102095. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  102096. engine.initWebVR().add(function (event) {
  102097. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  102098. return;
  102099. }
  102100. _this._vrDevice = event.vrDisplay;
  102101. //reset the rig parameters.
  102102. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  102103. if (_this._attached) {
  102104. _this.getEngine().enableVR();
  102105. }
  102106. });
  102107. if (typeof (VRFrameData) !== "undefined")
  102108. _this._frameData = new VRFrameData();
  102109. /**
  102110. * The idea behind the following lines:
  102111. * objects that have the camera as parent should actually have the rig cameras as a parent.
  102112. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  102113. * the second will not show it correctly.
  102114. *
  102115. * To solve this - each object that has the camera as parent will be added to a protected array.
  102116. * When the rig camera renders, it will take this array and set all of those to be its children.
  102117. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  102118. * Amazing!
  102119. */
  102120. scene.onBeforeCameraRenderObservable.add(function (camera) {
  102121. if (camera.parent === _this && _this.rigParenting) {
  102122. _this._descendants = _this.getDescendants(true, function (n) {
  102123. // don't take the cameras or the controllers!
  102124. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  102125. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  102126. return !isController && !isRigCamera;
  102127. });
  102128. _this._descendants.forEach(function (node) {
  102129. node.parent = camera;
  102130. });
  102131. }
  102132. });
  102133. scene.onAfterCameraRenderObservable.add(function (camera) {
  102134. if (camera.parent === _this && _this.rigParenting) {
  102135. _this._descendants.forEach(function (node) {
  102136. node.parent = _this;
  102137. });
  102138. }
  102139. });
  102140. return _this;
  102141. }
  102142. /**
  102143. * Gets the device distance from the ground in meters.
  102144. * @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.
  102145. */
  102146. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  102147. if (this._standingMatrix) {
  102148. // Add standing matrix offset to get real offset from ground in room
  102149. this._standingMatrix.getTranslationToRef(this._workingVector);
  102150. return this._deviceRoomPosition.y + this._workingVector.y;
  102151. }
  102152. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  102153. return this._defaultHeight || 0;
  102154. };
  102155. /**
  102156. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  102157. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  102158. */
  102159. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  102160. var _this = this;
  102161. if (callback === void 0) { callback = function (bool) { }; }
  102162. // Use standing matrix if available
  102163. this.getEngine().initWebVRAsync().then(function (result) {
  102164. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform || !_this.webVROptions.trackPosition) {
  102165. callback(false);
  102166. }
  102167. else {
  102168. _this._standingMatrix = new BABYLON.Matrix();
  102169. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  102170. if (!_this.getScene().useRightHandedSystem) {
  102171. [2, 6, 8, 9, 14].forEach(function (num) {
  102172. if (_this._standingMatrix) {
  102173. _this._standingMatrix.m[num] *= -1;
  102174. }
  102175. });
  102176. }
  102177. callback(true);
  102178. }
  102179. });
  102180. };
  102181. /**
  102182. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  102183. * @returns A promise with a boolean set to if the standing matrix is supported.
  102184. */
  102185. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  102186. var _this = this;
  102187. return new Promise(function (res, rej) {
  102188. _this.useStandingMatrix(function (supported) {
  102189. res(supported);
  102190. });
  102191. });
  102192. };
  102193. /**
  102194. * Disposes the camera
  102195. */
  102196. WebVRFreeCamera.prototype.dispose = function () {
  102197. this._detachIfAttached();
  102198. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  102199. if (this._updateCacheWhenTrackingDisabledObserver) {
  102200. this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver);
  102201. }
  102202. _super.prototype.dispose.call(this);
  102203. };
  102204. /**
  102205. * Gets a vrController by name.
  102206. * @param name The name of the controller to retreive
  102207. * @returns the controller matching the name specified or null if not found
  102208. */
  102209. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  102210. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  102211. var gp = _a[_i];
  102212. if (gp.hand === name) {
  102213. return gp;
  102214. }
  102215. }
  102216. return null;
  102217. };
  102218. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  102219. /**
  102220. * The controller corrisponding to the users left hand.
  102221. */
  102222. get: function () {
  102223. if (!this._leftController) {
  102224. this._leftController = this.getControllerByName("left");
  102225. }
  102226. return this._leftController;
  102227. },
  102228. enumerable: true,
  102229. configurable: true
  102230. });
  102231. ;
  102232. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  102233. /**
  102234. * The controller corrisponding to the users right hand.
  102235. */
  102236. get: function () {
  102237. if (!this._rightController) {
  102238. this._rightController = this.getControllerByName("right");
  102239. }
  102240. return this._rightController;
  102241. },
  102242. enumerable: true,
  102243. configurable: true
  102244. });
  102245. ;
  102246. /**
  102247. * Casts a ray forward from the vrCamera's gaze.
  102248. * @param length Length of the ray (default: 100)
  102249. * @returns the ray corrisponding to the gaze
  102250. */
  102251. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  102252. if (length === void 0) { length = 100; }
  102253. if (this.leftCamera) {
  102254. // Use left eye to avoid computation to compute center on every call
  102255. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  102256. }
  102257. else {
  102258. return _super.prototype.getForwardRay.call(this, length);
  102259. }
  102260. };
  102261. /**
  102262. * @hidden
  102263. * Updates the camera based on device's frame data
  102264. */
  102265. WebVRFreeCamera.prototype._checkInputs = function () {
  102266. if (this._vrDevice && this._vrDevice.isPresenting) {
  102267. this._vrDevice.getFrameData(this._frameData);
  102268. this.updateFromDevice(this._frameData.pose);
  102269. }
  102270. _super.prototype._checkInputs.call(this);
  102271. };
  102272. /**
  102273. * Updates the poseControlled values based on the input device pose.
  102274. * @param poseData Pose coming from the device
  102275. */
  102276. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  102277. if (poseData && poseData.orientation) {
  102278. this.rawPose = poseData;
  102279. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  102280. if (this.getScene().useRightHandedSystem) {
  102281. this._deviceRoomRotationQuaternion.z *= -1;
  102282. this._deviceRoomRotationQuaternion.w *= -1;
  102283. }
  102284. if (this.webVROptions.trackPosition && this.rawPose.position) {
  102285. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  102286. if (this.getScene().useRightHandedSystem) {
  102287. this._deviceRoomPosition.z *= -1;
  102288. }
  102289. }
  102290. this._poseSet = true;
  102291. }
  102292. };
  102293. /**
  102294. * WebVR's attach control will start broadcasting frames to the device.
  102295. * Note that in certain browsers (chrome for example) this function must be called
  102296. * within a user-interaction callback. Example:
  102297. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  102298. *
  102299. * @param element html element to attach the vrDevice to
  102300. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  102301. */
  102302. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  102303. _super.prototype.attachControl.call(this, element, noPreventDefault);
  102304. this._attached = true;
  102305. this._htmlElementAttached = element;
  102306. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  102307. if (this._vrDevice) {
  102308. this.getEngine().enableVR();
  102309. }
  102310. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  102311. };
  102312. /**
  102313. * Detaches the camera from the html element and disables VR
  102314. *
  102315. * @param element html element to detach from
  102316. */
  102317. WebVRFreeCamera.prototype.detachControl = function (element) {
  102318. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  102319. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  102320. _super.prototype.detachControl.call(this, element);
  102321. this._attached = false;
  102322. this.getEngine().disableVR();
  102323. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  102324. };
  102325. /**
  102326. * @returns the name of this class
  102327. */
  102328. WebVRFreeCamera.prototype.getClassName = function () {
  102329. return "WebVRFreeCamera";
  102330. };
  102331. /**
  102332. * Calls resetPose on the vrDisplay
  102333. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  102334. */
  102335. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  102336. //uses the vrDisplay's "resetPose()".
  102337. //pitch and roll won't be affected.
  102338. this._vrDevice.resetPose();
  102339. };
  102340. /**
  102341. * @hidden
  102342. * Updates the rig cameras (left and right eye)
  102343. */
  102344. WebVRFreeCamera.prototype._updateRigCameras = function () {
  102345. var camLeft = this._rigCameras[0];
  102346. var camRight = this._rigCameras[1];
  102347. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  102348. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  102349. camLeft.position.copyFrom(this._deviceRoomPosition);
  102350. camRight.position.copyFrom(this._deviceRoomPosition);
  102351. };
  102352. // Remove translation from 6dof headset if trackposition is set to false
  102353. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  102354. if (isViewMatrix === void 0) { isViewMatrix = false; }
  102355. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  102356. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  102357. if (!isViewMatrix) {
  102358. this._tmpMatrix.invert();
  102359. }
  102360. this._tmpMatrix.multiplyToRef(matrix, matrix);
  102361. }
  102362. };
  102363. /**
  102364. * @hidden
  102365. * Updates the cached values of the camera
  102366. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  102367. */
  102368. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  102369. var _this = this;
  102370. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  102371. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  102372. if (!this.updateCacheCalled) {
  102373. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  102374. this.updateCacheCalled = true;
  102375. this.update();
  102376. }
  102377. // Set working vector to the device position in room space rotated by the new rotation
  102378. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  102379. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  102380. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  102381. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  102382. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  102383. // Add translation from anchor position
  102384. this._deviceToWorld.getTranslationToRef(this._workingVector);
  102385. this._workingVector.addInPlace(this.position);
  102386. this._workingVector.subtractInPlace(this._cache.position);
  102387. this._deviceToWorld.setTranslation(this._workingVector);
  102388. // Set an inverted matrix to be used when updating the camera
  102389. this._deviceToWorld.invertToRef(this._worldToDevice);
  102390. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  102391. this.controllers.forEach(function (controller) {
  102392. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  102393. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  102394. controller.update();
  102395. });
  102396. }
  102397. if (!ignoreParentClass) {
  102398. _super.prototype._updateCache.call(this);
  102399. }
  102400. this.updateCacheCalled = false;
  102401. };
  102402. /**
  102403. * @hidden
  102404. * Get current device position in babylon world
  102405. */
  102406. WebVRFreeCamera.prototype._computeDevicePosition = function () {
  102407. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  102408. };
  102409. /**
  102410. * Updates the current device position and rotation in the babylon world
  102411. */
  102412. WebVRFreeCamera.prototype.update = function () {
  102413. this._computeDevicePosition();
  102414. // Get current device rotation in babylon world
  102415. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  102416. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  102417. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  102418. if (this._poseSet) {
  102419. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  102420. }
  102421. _super.prototype.update.call(this);
  102422. };
  102423. /**
  102424. * @hidden
  102425. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  102426. * @returns an identity matrix
  102427. */
  102428. WebVRFreeCamera.prototype._getViewMatrix = function () {
  102429. return BABYLON.Matrix.Identity();
  102430. };
  102431. /**
  102432. * This function is called by the two RIG cameras.
  102433. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  102434. */
  102435. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  102436. var _this = this;
  102437. // Update the parent camera prior to using a child camera to avoid desynchronization
  102438. var parentCamera = this._cameraRigParams["parentCamera"];
  102439. parentCamera._updateCache();
  102440. //WebVR 1.1
  102441. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  102442. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  102443. if (!this.getScene().useRightHandedSystem) {
  102444. [2, 6, 8, 9, 14].forEach(function (num) {
  102445. _this._webvrViewMatrix.m[num] *= -1;
  102446. });
  102447. }
  102448. // update the camera rotation matrix
  102449. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  102450. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  102451. // Computing target and final matrix
  102452. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  102453. // should the view matrix be updated with scale and position offset?
  102454. if (parentCamera.deviceScaleFactor !== 1) {
  102455. this._webvrViewMatrix.invert();
  102456. // scale the position, if set
  102457. if (parentCamera.deviceScaleFactor) {
  102458. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  102459. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  102460. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  102461. }
  102462. this._webvrViewMatrix.invert();
  102463. }
  102464. // Remove translation from 6dof headset if trackposition is set to false
  102465. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  102466. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  102467. // Compute global position
  102468. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  102469. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  102470. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  102471. this._workingMatrix.getTranslationToRef(this._globalPosition);
  102472. this._markSyncedWithParent();
  102473. return this._webvrViewMatrix;
  102474. };
  102475. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  102476. var _this = this;
  102477. var parentCamera = this.parent;
  102478. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  102479. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  102480. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  102481. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  102482. //babylon compatible matrix
  102483. if (!this.getScene().useRightHandedSystem) {
  102484. [8, 9, 10, 11].forEach(function (num) {
  102485. _this._projectionMatrix.m[num] *= -1;
  102486. });
  102487. }
  102488. return this._projectionMatrix;
  102489. };
  102490. /**
  102491. * Initializes the controllers and their meshes
  102492. */
  102493. WebVRFreeCamera.prototype.initControllers = function () {
  102494. var _this = this;
  102495. this.controllers = [];
  102496. var manager = this.getScene().gamepadManager;
  102497. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  102498. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  102499. var webVrController = gamepad;
  102500. if (webVrController.defaultModel) {
  102501. webVrController.defaultModel.setEnabled(false);
  102502. }
  102503. if (webVrController.hand === "right") {
  102504. _this._rightController = null;
  102505. }
  102506. if (webVrController.hand === "left") {
  102507. _this._leftController = null;
  102508. }
  102509. var controllerIndex = _this.controllers.indexOf(webVrController);
  102510. if (controllerIndex !== -1) {
  102511. _this.controllers.splice(controllerIndex, 1);
  102512. }
  102513. }
  102514. });
  102515. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  102516. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  102517. var webVrController_1 = gamepad;
  102518. if (!_this.webVROptions.trackPosition) {
  102519. webVrController_1._disableTrackPosition(new BABYLON.Vector3(webVrController_1.hand == "left" ? -0.15 : 0.15, -0.5, 0.25));
  102520. // Cache must be updated before rendering controllers to avoid them being one frame behind
  102521. if (!_this._updateCacheWhenTrackingDisabledObserver) {
  102522. _this._updateCacheWhenTrackingDisabledObserver = _this._scene.onBeforeRenderObservable.add(function () {
  102523. _this._updateCache();
  102524. });
  102525. }
  102526. }
  102527. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  102528. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  102529. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  102530. if (_this.webVROptions.controllerMeshes) {
  102531. if (webVrController_1.defaultModel) {
  102532. webVrController_1.defaultModel.setEnabled(true);
  102533. }
  102534. else {
  102535. // Load the meshes
  102536. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  102537. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  102538. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  102539. if (_this.webVROptions.defaultLightingOnControllers) {
  102540. if (!_this._lightOnControllers) {
  102541. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  102542. }
  102543. var activateLightOnSubMeshes_1 = function (mesh, light) {
  102544. var children = mesh.getChildren();
  102545. if (children && children.length !== 0) {
  102546. children.forEach(function (mesh) {
  102547. light.includedOnlyMeshes.push(mesh);
  102548. activateLightOnSubMeshes_1(mesh, light);
  102549. });
  102550. }
  102551. };
  102552. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  102553. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  102554. }
  102555. });
  102556. }
  102557. }
  102558. webVrController_1.attachToPoseControlledCamera(_this);
  102559. // since this is async - sanity check. Is the controller already stored?
  102560. if (_this.controllers.indexOf(webVrController_1) === -1) {
  102561. //add to the controllers array
  102562. _this.controllers.push(webVrController_1);
  102563. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  102564. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  102565. // So we're overriding setting left & right manually to be sure
  102566. var firstViveWandDetected = false;
  102567. for (var i = 0; i < _this.controllers.length; i++) {
  102568. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  102569. if (!firstViveWandDetected) {
  102570. firstViveWandDetected = true;
  102571. _this.controllers[i].hand = "left";
  102572. }
  102573. else {
  102574. _this.controllers[i].hand = "right";
  102575. }
  102576. }
  102577. }
  102578. //did we find enough controllers? Great! let the developer know.
  102579. if (_this.controllers.length >= 2) {
  102580. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  102581. }
  102582. }
  102583. }
  102584. });
  102585. };
  102586. return WebVRFreeCamera;
  102587. }(BABYLON.FreeCamera));
  102588. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  102589. })(BABYLON || (BABYLON = {}));
  102590. //# sourceMappingURL=babylon.webVRCamera.js.map
  102591. var BABYLON;
  102592. (function (BABYLON) {
  102593. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  102594. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  102595. });
  102596. // We're mainly based on the logic defined into the FreeCamera code
  102597. /**
  102598. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  102599. * being tilted forward or back and left or right.
  102600. */
  102601. var DeviceOrientationCamera = /** @class */ (function (_super) {
  102602. __extends(DeviceOrientationCamera, _super);
  102603. /**
  102604. * Creates a new device orientation camera
  102605. * @param name The name of the camera
  102606. * @param position The start position camera
  102607. * @param scene The scene the camera belongs to
  102608. */
  102609. function DeviceOrientationCamera(name, position, scene) {
  102610. var _this = _super.call(this, name, position, scene) || this;
  102611. _this._quaternionCache = new BABYLON.Quaternion();
  102612. _this.inputs.addDeviceOrientation();
  102613. return _this;
  102614. }
  102615. /**
  102616. * Gets the current instance class name ("DeviceOrientationCamera").
  102617. * This helps avoiding instanceof at run time.
  102618. * @returns the class name
  102619. */
  102620. DeviceOrientationCamera.prototype.getClassName = function () {
  102621. return "DeviceOrientationCamera";
  102622. };
  102623. /**
  102624. * @hidden
  102625. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  102626. */
  102627. DeviceOrientationCamera.prototype._checkInputs = function () {
  102628. _super.prototype._checkInputs.call(this);
  102629. this._quaternionCache.copyFrom(this.rotationQuaternion);
  102630. if (this._initialQuaternion) {
  102631. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  102632. }
  102633. };
  102634. /**
  102635. * Reset the camera to its default orientation on the specified axis only.
  102636. * @param axis The axis to reset
  102637. */
  102638. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  102639. var _this = this;
  102640. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  102641. //can only work if this camera has a rotation quaternion already.
  102642. if (!this.rotationQuaternion)
  102643. return;
  102644. if (!this._initialQuaternion) {
  102645. this._initialQuaternion = new BABYLON.Quaternion();
  102646. }
  102647. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  102648. ['x', 'y', 'z'].forEach(function (axisName) {
  102649. if (!axis[axisName]) {
  102650. _this._initialQuaternion[axisName] = 0;
  102651. }
  102652. else {
  102653. _this._initialQuaternion[axisName] *= -1;
  102654. }
  102655. });
  102656. this._initialQuaternion.normalize();
  102657. //force rotation update
  102658. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  102659. };
  102660. return DeviceOrientationCamera;
  102661. }(BABYLON.FreeCamera));
  102662. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  102663. })(BABYLON || (BABYLON = {}));
  102664. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  102665. var BABYLON;
  102666. (function (BABYLON) {
  102667. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  102668. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  102669. });
  102670. /**
  102671. * Camera used to simulate VR rendering (based on FreeCamera)
  102672. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  102673. */
  102674. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  102675. __extends(VRDeviceOrientationFreeCamera, _super);
  102676. /**
  102677. * Creates a new VRDeviceOrientationFreeCamera
  102678. * @param name defines camera name
  102679. * @param position defines the start position of the camera
  102680. * @param scene defines the scene the camera belongs to
  102681. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  102682. * @param vrCameraMetrics defines the vr metrics associated to the camera
  102683. */
  102684. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  102685. if (compensateDistortion === void 0) { compensateDistortion = true; }
  102686. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  102687. var _this = _super.call(this, name, position, scene) || this;
  102688. vrCameraMetrics.compensateDistortion = compensateDistortion;
  102689. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  102690. return _this;
  102691. }
  102692. /**
  102693. * Gets camera class name
  102694. * @returns VRDeviceOrientationFreeCamera
  102695. */
  102696. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  102697. return "VRDeviceOrientationFreeCamera";
  102698. };
  102699. return VRDeviceOrientationFreeCamera;
  102700. }(BABYLON.DeviceOrientationCamera));
  102701. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  102702. })(BABYLON || (BABYLON = {}));
  102703. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  102704. var BABYLON;
  102705. (function (BABYLON) {
  102706. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  102707. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  102708. });
  102709. /**
  102710. * Camera used to simulate VR rendering (based on ArcRotateCamera)
  102711. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  102712. */
  102713. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  102714. __extends(VRDeviceOrientationArcRotateCamera, _super);
  102715. /**
  102716. * Creates a new VRDeviceOrientationArcRotateCamera
  102717. * @param name defines camera name
  102718. * @param alpha defines the camera rotation along the logitudinal axis
  102719. * @param beta defines the camera rotation along the latitudinal axis
  102720. * @param radius defines the camera distance from its target
  102721. * @param target defines the camera target
  102722. * @param scene defines the scene the camera belongs to
  102723. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  102724. * @param vrCameraMetrics defines the vr metrics associated to the camera
  102725. */
  102726. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  102727. if (compensateDistortion === void 0) { compensateDistortion = true; }
  102728. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  102729. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  102730. vrCameraMetrics.compensateDistortion = compensateDistortion;
  102731. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  102732. _this.inputs.addVRDeviceOrientation();
  102733. return _this;
  102734. }
  102735. /**
  102736. * Gets camera class name
  102737. * @returns VRDeviceOrientationArcRotateCamera
  102738. */
  102739. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  102740. return "VRDeviceOrientationArcRotateCamera";
  102741. };
  102742. return VRDeviceOrientationArcRotateCamera;
  102743. }(BABYLON.ArcRotateCamera));
  102744. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  102745. })(BABYLON || (BABYLON = {}));
  102746. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  102747. var BABYLON;
  102748. (function (BABYLON) {
  102749. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  102750. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  102751. });
  102752. /**
  102753. * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera)
  102754. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  102755. */
  102756. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  102757. __extends(VRDeviceOrientationGamepadCamera, _super);
  102758. /**
  102759. * Creates a new VRDeviceOrientationGamepadCamera
  102760. * @param name defines camera name
  102761. * @param position defines the start position of the camera
  102762. * @param scene defines the scene the camera belongs to
  102763. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  102764. * @param vrCameraMetrics defines the vr metrics associated to the camera
  102765. */
  102766. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  102767. if (compensateDistortion === void 0) { compensateDistortion = true; }
  102768. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  102769. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  102770. _this.inputs.addGamepad();
  102771. return _this;
  102772. }
  102773. /**
  102774. * Gets camera class name
  102775. * @returns VRDeviceOrientationGamepadCamera
  102776. */
  102777. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  102778. return "VRDeviceOrientationGamepadCamera";
  102779. };
  102780. return VRDeviceOrientationGamepadCamera;
  102781. }(BABYLON.VRDeviceOrientationFreeCamera));
  102782. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  102783. })(BABYLON || (BABYLON = {}));
  102784. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  102785. var BABYLON;
  102786. (function (BABYLON) {
  102787. var VRExperienceHelperGazer = /** @class */ (function () {
  102788. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  102789. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  102790. this.scene = scene;
  102791. /** @hidden */
  102792. this._pointerDownOnMeshAsked = false;
  102793. /** @hidden */
  102794. this._isActionableMesh = false;
  102795. /** @hidden */
  102796. this._teleportationRequestInitiated = false;
  102797. /** @hidden */
  102798. this._teleportationBackRequestInitiated = false;
  102799. /** @hidden */
  102800. this._rotationRightAsked = false;
  102801. /** @hidden */
  102802. this._rotationLeftAsked = false;
  102803. /** @hidden */
  102804. this._dpadPressed = true;
  102805. /** @hidden */
  102806. this._activePointer = false;
  102807. this._id = VRExperienceHelperGazer._idCounter++;
  102808. // Gaze tracker
  102809. if (!gazeTrackerToClone) {
  102810. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  102811. this._gazeTracker.bakeCurrentTransformIntoVertices();
  102812. this._gazeTracker.isPickable = false;
  102813. this._gazeTracker.isVisible = false;
  102814. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  102815. targetMat.specularColor = BABYLON.Color3.Black();
  102816. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  102817. targetMat.backFaceCulling = false;
  102818. this._gazeTracker.material = targetMat;
  102819. }
  102820. else {
  102821. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  102822. }
  102823. }
  102824. /** @hidden */
  102825. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  102826. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  102827. };
  102828. /** @hidden */
  102829. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  102830. this._pointerDownOnMeshAsked = true;
  102831. if (this._currentHit) {
  102832. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  102833. }
  102834. };
  102835. /** @hidden */
  102836. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  102837. if (this._currentHit) {
  102838. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  102839. }
  102840. this._pointerDownOnMeshAsked = false;
  102841. };
  102842. /** @hidden */
  102843. VRExperienceHelperGazer.prototype._activatePointer = function () {
  102844. this._activePointer = true;
  102845. };
  102846. /** @hidden */
  102847. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  102848. this._activePointer = false;
  102849. };
  102850. /** @hidden */
  102851. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  102852. if (distance === void 0) { distance = 100; }
  102853. };
  102854. VRExperienceHelperGazer.prototype.dispose = function () {
  102855. this._interactionsEnabled = false;
  102856. this._teleportationEnabled = false;
  102857. if (this._gazeTracker) {
  102858. this._gazeTracker.dispose();
  102859. }
  102860. };
  102861. VRExperienceHelperGazer._idCounter = 0;
  102862. return VRExperienceHelperGazer;
  102863. }());
  102864. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  102865. __extends(VRExperienceHelperControllerGazer, _super);
  102866. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  102867. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  102868. _this.webVRController = webVRController;
  102869. // Laser pointer
  102870. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  102871. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  102872. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  102873. laserPointerMaterial.alpha = 0.6;
  102874. _this._laserPointer.material = laserPointerMaterial;
  102875. _this._laserPointer.rotation.x = Math.PI / 2;
  102876. _this._laserPointer.position.z = -0.5;
  102877. _this._laserPointer.isVisible = false;
  102878. _this._laserPointer.isPickable = false;
  102879. if (!webVRController.mesh) {
  102880. // Create an empty mesh that is used prior to loading the high quality model
  102881. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  102882. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  102883. preloadPointerPose.rotation.x = -0.7;
  102884. preloadMesh.addChild(preloadPointerPose);
  102885. webVRController.attachToMesh(preloadMesh);
  102886. }
  102887. _this._setLaserPointerParent(webVRController.mesh);
  102888. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  102889. _this._setLaserPointerParent(mesh);
  102890. });
  102891. return _this;
  102892. }
  102893. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  102894. return this.webVRController.getForwardRay(length);
  102895. };
  102896. /** @hidden */
  102897. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  102898. _super.prototype._activatePointer.call(this);
  102899. this._laserPointer.isVisible = true;
  102900. };
  102901. /** @hidden */
  102902. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  102903. _super.prototype._deactivatePointer.call(this);
  102904. this._laserPointer.isVisible = false;
  102905. };
  102906. /** @hidden */
  102907. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  102908. this._laserPointer.material.emissiveColor = color;
  102909. };
  102910. /** @hidden */
  102911. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  102912. var makeNotPick = function (root) {
  102913. root.isPickable = false;
  102914. root.getChildMeshes().forEach(function (c) {
  102915. makeNotPick(c);
  102916. });
  102917. };
  102918. makeNotPick(mesh);
  102919. var childMeshes = mesh.getChildMeshes();
  102920. this.webVRController._pointingPoseNode = null;
  102921. for (var i = 0; i < childMeshes.length; i++) {
  102922. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  102923. mesh = childMeshes[i];
  102924. this.webVRController._pointingPoseNode = mesh;
  102925. break;
  102926. }
  102927. }
  102928. this._laserPointer.parent = mesh;
  102929. };
  102930. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  102931. if (distance === void 0) { distance = 100; }
  102932. this._laserPointer.scaling.y = distance;
  102933. this._laserPointer.position.z = -distance / 2;
  102934. };
  102935. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  102936. _super.prototype.dispose.call(this);
  102937. this._laserPointer.dispose();
  102938. if (this._meshAttachedObserver) {
  102939. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  102940. }
  102941. };
  102942. return VRExperienceHelperControllerGazer;
  102943. }(VRExperienceHelperGazer));
  102944. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  102945. __extends(VRExperienceHelperCameraGazer, _super);
  102946. function VRExperienceHelperCameraGazer(getCamera, scene) {
  102947. var _this = _super.call(this, scene) || this;
  102948. _this.getCamera = getCamera;
  102949. return _this;
  102950. }
  102951. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  102952. var camera = this.getCamera();
  102953. if (camera) {
  102954. return camera.getForwardRay(length);
  102955. }
  102956. else {
  102957. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  102958. }
  102959. };
  102960. return VRExperienceHelperCameraGazer;
  102961. }(VRExperienceHelperGazer));
  102962. /**
  102963. * Helps to quickly add VR support to an existing scene.
  102964. * See http://doc.babylonjs.com/how_to/webvr_helper
  102965. */
  102966. var VRExperienceHelper = /** @class */ (function () {
  102967. /**
  102968. * Instantiates a VRExperienceHelper.
  102969. * Helps to quickly add VR support to an existing scene.
  102970. * @param scene The scene the VRExperienceHelper belongs to.
  102971. * @param webVROptions Options to modify the vr experience helper's behavior.
  102972. */
  102973. function VRExperienceHelper(scene,
  102974. /** Options to modify the vr experience helper's behavior. */
  102975. webVROptions) {
  102976. if (webVROptions === void 0) { webVROptions = {}; }
  102977. var _this = this;
  102978. this.webVROptions = webVROptions;
  102979. // Can the system support WebVR, even if a headset isn't plugged in?
  102980. this._webVRsupported = false;
  102981. // If WebVR is supported, is a headset plugged in and are we ready to present?
  102982. this._webVRready = false;
  102983. // Are we waiting for the requestPresent callback to complete?
  102984. this._webVRrequesting = false;
  102985. // Are we presenting to the headset right now? (this is the vrDevice state)
  102986. this._webVRpresenting = false;
  102987. // Are we presenting in the fullscreen fallback?
  102988. this._fullscreenVRpresenting = false;
  102989. /**
  102990. * Observable raised when entering VR.
  102991. */
  102992. this.onEnteringVRObservable = new BABYLON.Observable();
  102993. /**
  102994. * Observable raised when exiting VR.
  102995. */
  102996. this.onExitingVRObservable = new BABYLON.Observable();
  102997. /**
  102998. * Observable raised when controller mesh is loaded.
  102999. */
  103000. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  103001. this._useCustomVRButton = false;
  103002. this._teleportationRequested = false;
  103003. this._teleportActive = false;
  103004. this._floorMeshesCollection = [];
  103005. this._rotationAllowed = true;
  103006. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  103007. this._isDefaultTeleportationTarget = true;
  103008. this._teleportationFillColor = "#444444";
  103009. this._teleportationBorderColor = "#FFFFFF";
  103010. this._rotationAngle = 0;
  103011. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  103012. this._padSensibilityUp = 0.65;
  103013. this._padSensibilityDown = 0.35;
  103014. this._leftController = null;
  103015. this._rightController = null;
  103016. /**
  103017. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  103018. */
  103019. this.onNewMeshSelected = new BABYLON.Observable();
  103020. /**
  103021. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  103022. */
  103023. this.onNewMeshPicked = new BABYLON.Observable();
  103024. /**
  103025. * Observable raised before camera teleportation
  103026. */
  103027. this.onBeforeCameraTeleport = new BABYLON.Observable();
  103028. /**
  103029. * Observable raised after camera teleportation
  103030. */
  103031. this.onAfterCameraTeleport = new BABYLON.Observable();
  103032. /**
  103033. * Observable raised when current selected mesh gets unselected
  103034. */
  103035. this.onSelectedMeshUnselected = new BABYLON.Observable();
  103036. /**
  103037. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  103038. */
  103039. this.teleportationEnabled = true;
  103040. this._teleportationInitialized = false;
  103041. this._interactionsEnabled = false;
  103042. this._interactionsRequested = false;
  103043. this._displayGaze = true;
  103044. this._displayLaserPointer = true;
  103045. /**
  103046. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  103047. */
  103048. this.updateGazeTrackerScale = true;
  103049. this._onResize = function () {
  103050. _this.moveButtonToBottomRight();
  103051. if (_this._fullscreenVRpresenting && _this._webVRready) {
  103052. _this.exitVR();
  103053. }
  103054. };
  103055. this._onFullscreenChange = function () {
  103056. if (document.fullscreen !== undefined) {
  103057. _this._fullscreenVRpresenting = document.fullscreen;
  103058. }
  103059. else if (document.mozFullScreen !== undefined) {
  103060. _this._fullscreenVRpresenting = document.mozFullScreen;
  103061. }
  103062. else if (document.webkitIsFullScreen !== undefined) {
  103063. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  103064. }
  103065. else if (document.msIsFullScreen !== undefined) {
  103066. _this._fullscreenVRpresenting = document.msIsFullScreen;
  103067. }
  103068. else if (document.msFullscreenElement !== undefined) {
  103069. _this._fullscreenVRpresenting = document.msFullscreenElement;
  103070. }
  103071. if (!_this._fullscreenVRpresenting && _this._canvas) {
  103072. _this.exitVR();
  103073. if (!_this._useCustomVRButton) {
  103074. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  103075. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  103076. }
  103077. }
  103078. };
  103079. this.beforeRender = function () {
  103080. if (_this._leftController && _this._leftController._activePointer) {
  103081. _this._castRayAndSelectObject(_this._leftController);
  103082. }
  103083. if (_this._rightController && _this._rightController._activePointer) {
  103084. _this._castRayAndSelectObject(_this._rightController);
  103085. }
  103086. if (_this._noControllerIsActive) {
  103087. _this._castRayAndSelectObject(_this._cameraGazer);
  103088. }
  103089. else {
  103090. _this._cameraGazer._gazeTracker.isVisible = false;
  103091. }
  103092. };
  103093. this._onNewGamepadConnected = function (gamepad) {
  103094. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  103095. if (gamepad.leftStick) {
  103096. gamepad.onleftstickchanged(function (stickValues) {
  103097. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  103098. // Listening to classic/xbox gamepad only if no VR controller is active
  103099. if ((!_this._leftController && !_this._rightController) ||
  103100. ((_this._leftController && !_this._leftController._activePointer) &&
  103101. (_this._rightController && !_this._rightController._activePointer))) {
  103102. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  103103. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  103104. }
  103105. }
  103106. });
  103107. }
  103108. if (gamepad.rightStick) {
  103109. gamepad.onrightstickchanged(function (stickValues) {
  103110. if (_this._teleportationInitialized) {
  103111. _this._checkRotate(stickValues, _this._cameraGazer);
  103112. }
  103113. });
  103114. }
  103115. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  103116. gamepad.onbuttondown(function (buttonPressed) {
  103117. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  103118. _this._cameraGazer._selectionPointerDown();
  103119. }
  103120. });
  103121. gamepad.onbuttonup(function (buttonPressed) {
  103122. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  103123. _this._cameraGazer._selectionPointerUp();
  103124. }
  103125. });
  103126. }
  103127. }
  103128. else {
  103129. var webVRController = gamepad;
  103130. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  103131. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  103132. _this._rightController = controller;
  103133. }
  103134. else {
  103135. _this._leftController = controller;
  103136. }
  103137. _this._tryEnableInteractionOnController(controller);
  103138. }
  103139. };
  103140. // 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
  103141. this._tryEnableInteractionOnController = function (controller) {
  103142. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  103143. _this._enableInteractionOnController(controller);
  103144. }
  103145. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  103146. _this._enableTeleportationOnController(controller);
  103147. }
  103148. };
  103149. this._onNewGamepadDisconnected = function (gamepad) {
  103150. if (gamepad instanceof BABYLON.WebVRController) {
  103151. if (gamepad.hand === "left" && _this._leftController != null) {
  103152. _this._leftController.dispose();
  103153. _this._leftController = null;
  103154. }
  103155. if (gamepad.hand === "right" && _this._rightController != null) {
  103156. _this._rightController.dispose();
  103157. _this._rightController = null;
  103158. }
  103159. }
  103160. };
  103161. this._workingVector = BABYLON.Vector3.Zero();
  103162. this._workingQuaternion = BABYLON.Quaternion.Identity();
  103163. this._workingMatrix = BABYLON.Matrix.Identity();
  103164. this._scene = scene;
  103165. this._canvas = scene.getEngine().getRenderingCanvas();
  103166. // Parse options
  103167. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  103168. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  103169. }
  103170. if (webVROptions.createDeviceOrientationCamera === undefined) {
  103171. webVROptions.createDeviceOrientationCamera = true;
  103172. }
  103173. if (webVROptions.laserToggle === undefined) {
  103174. webVROptions.laserToggle = true;
  103175. }
  103176. if (webVROptions.defaultHeight === undefined) {
  103177. webVROptions.defaultHeight = 1.7;
  103178. }
  103179. if (webVROptions.useCustomVRButton) {
  103180. this._useCustomVRButton = true;
  103181. if (webVROptions.customVRButton) {
  103182. this._btnVR = webVROptions.customVRButton;
  103183. }
  103184. }
  103185. if (webVROptions.rayLength) {
  103186. this._rayLength = webVROptions.rayLength;
  103187. }
  103188. this._defaultHeight = webVROptions.defaultHeight;
  103189. if (webVROptions.positionScale) {
  103190. this._rayLength *= webVROptions.positionScale;
  103191. this._defaultHeight *= webVROptions.positionScale;
  103192. }
  103193. this._hasEnteredVR = false;
  103194. // Set position
  103195. if (this._scene.activeCamera) {
  103196. this._position = this._scene.activeCamera.position.clone();
  103197. }
  103198. else {
  103199. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  103200. }
  103201. // Set non-vr camera
  103202. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  103203. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  103204. // Copy data from existing camera
  103205. if (this._scene.activeCamera) {
  103206. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  103207. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  103208. // Set rotation from previous camera
  103209. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  103210. var targetCamera = this._scene.activeCamera;
  103211. if (targetCamera.rotationQuaternion) {
  103212. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  103213. }
  103214. else {
  103215. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  103216. }
  103217. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  103218. }
  103219. }
  103220. this._scene.activeCamera = this._deviceOrientationCamera;
  103221. if (this._canvas) {
  103222. this._scene.activeCamera.attachControl(this._canvas);
  103223. }
  103224. }
  103225. else {
  103226. this._existingCamera = this._scene.activeCamera;
  103227. }
  103228. // Create VR cameras
  103229. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  103230. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  103231. }
  103232. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  103233. this._webVRCamera.useStandingMatrix();
  103234. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  103235. // Create default button
  103236. if (!this._useCustomVRButton) {
  103237. this._btnVR = document.createElement("BUTTON");
  103238. this._btnVR.className = "babylonVRicon";
  103239. this._btnVR.id = "babylonVRiconbtn";
  103240. this._btnVR.title = "Click to switch to VR";
  103241. 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) }";
  103242. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  103243. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  103244. // css += ".babylonVRicon.vrdisplaysupported { }";
  103245. // css += ".babylonVRicon.vrdisplayready { }";
  103246. // css += ".babylonVRicon.vrdisplayrequesting { }";
  103247. var style = document.createElement('style');
  103248. style.appendChild(document.createTextNode(css));
  103249. document.getElementsByTagName('head')[0].appendChild(style);
  103250. this.moveButtonToBottomRight();
  103251. }
  103252. // VR button click event
  103253. if (this._btnVR) {
  103254. this._btnVR.addEventListener("click", function () {
  103255. if (!_this.isInVRMode) {
  103256. _this.enterVR();
  103257. }
  103258. else {
  103259. _this.exitVR();
  103260. }
  103261. });
  103262. }
  103263. // Window events
  103264. window.addEventListener("resize", this._onResize);
  103265. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  103266. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  103267. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  103268. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  103269. document.onmsfullscreenchange = this._onFullscreenChange;
  103270. // Display vr button when headset is connected
  103271. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  103272. this.displayVRButton();
  103273. }
  103274. else {
  103275. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  103276. if (e.vrDisplay) {
  103277. _this.displayVRButton();
  103278. }
  103279. });
  103280. }
  103281. // Exiting VR mode using 'ESC' key on desktop
  103282. this._onKeyDown = function (event) {
  103283. if (event.keyCode === 27 && _this.isInVRMode) {
  103284. _this.exitVR();
  103285. }
  103286. };
  103287. document.addEventListener("keydown", this._onKeyDown);
  103288. // Exiting VR mode double tapping the touch screen
  103289. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  103290. if (_this.isInVRMode) {
  103291. _this.exitVR();
  103292. if (_this._fullscreenVRpresenting) {
  103293. _this._scene.getEngine().switchFullscreen(true);
  103294. }
  103295. }
  103296. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  103297. // Listen for WebVR display changes
  103298. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  103299. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  103300. this._onVRRequestPresentStart = function () {
  103301. _this._webVRrequesting = true;
  103302. _this.updateButtonVisibility();
  103303. };
  103304. this._onVRRequestPresentComplete = function (success) {
  103305. _this._webVRrequesting = false;
  103306. _this.updateButtonVisibility();
  103307. };
  103308. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  103309. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  103310. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  103311. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  103312. scene.onDisposeObservable.add(function () {
  103313. _this.dispose();
  103314. });
  103315. // Gamepad connection events
  103316. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  103317. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  103318. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  103319. this.updateButtonVisibility();
  103320. //create easing functions
  103321. this._circleEase = new BABYLON.CircleEase();
  103322. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  103323. if (this.webVROptions.floorMeshes) {
  103324. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  103325. }
  103326. }
  103327. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  103328. /** Return this.onEnteringVRObservable
  103329. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  103330. */
  103331. get: function () {
  103332. return this.onEnteringVRObservable;
  103333. },
  103334. enumerable: true,
  103335. configurable: true
  103336. });
  103337. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  103338. /** Return this.onExitingVRObservable
  103339. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  103340. */
  103341. get: function () {
  103342. return this.onExitingVRObservable;
  103343. },
  103344. enumerable: true,
  103345. configurable: true
  103346. });
  103347. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  103348. /** Return this.onControllerMeshLoadedObservable
  103349. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  103350. */
  103351. get: function () {
  103352. return this.onControllerMeshLoadedObservable;
  103353. },
  103354. enumerable: true,
  103355. configurable: true
  103356. });
  103357. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  103358. /**
  103359. * The mesh used to display where the user is going to teleport.
  103360. */
  103361. get: function () {
  103362. return this._teleportationTarget;
  103363. },
  103364. /**
  103365. * Sets the mesh to be used to display where the user is going to teleport.
  103366. */
  103367. set: function (value) {
  103368. if (value) {
  103369. value.name = "teleportationTarget";
  103370. this._isDefaultTeleportationTarget = false;
  103371. this._teleportationTarget = value;
  103372. }
  103373. },
  103374. enumerable: true,
  103375. configurable: true
  103376. });
  103377. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  103378. /**
  103379. * 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
  103380. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  103381. * See http://doc.babylonjs.com/resources/baking_transformations
  103382. */
  103383. get: function () {
  103384. return this._cameraGazer._gazeTracker;
  103385. },
  103386. set: function (value) {
  103387. if (value) {
  103388. // Dispose of existing meshes
  103389. if (this._cameraGazer._gazeTracker) {
  103390. this._cameraGazer._gazeTracker.dispose();
  103391. }
  103392. if (this._leftController && this._leftController._gazeTracker) {
  103393. this._leftController._gazeTracker.dispose();
  103394. }
  103395. if (this._rightController && this._rightController._gazeTracker) {
  103396. this._rightController._gazeTracker.dispose();
  103397. }
  103398. // Set and create gaze trackers on head and controllers
  103399. this._cameraGazer._gazeTracker = value;
  103400. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  103401. this._cameraGazer._gazeTracker.isPickable = false;
  103402. this._cameraGazer._gazeTracker.isVisible = false;
  103403. this._cameraGazer._gazeTracker.name = "gazeTracker";
  103404. if (this._leftController) {
  103405. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  103406. }
  103407. if (this._rightController) {
  103408. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  103409. }
  103410. }
  103411. },
  103412. enumerable: true,
  103413. configurable: true
  103414. });
  103415. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  103416. /**
  103417. * The gaze tracking mesh corresponding to the left controller
  103418. */
  103419. get: function () {
  103420. if (this._leftController) {
  103421. return this._leftController._gazeTracker;
  103422. }
  103423. return null;
  103424. },
  103425. enumerable: true,
  103426. configurable: true
  103427. });
  103428. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  103429. /**
  103430. * The gaze tracking mesh corresponding to the right controller
  103431. */
  103432. get: function () {
  103433. if (this._rightController) {
  103434. return this._rightController._gazeTracker;
  103435. }
  103436. return null;
  103437. },
  103438. enumerable: true,
  103439. configurable: true
  103440. });
  103441. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  103442. /**
  103443. * If the ray of the gaze should be displayed.
  103444. */
  103445. get: function () {
  103446. return this._displayGaze;
  103447. },
  103448. /**
  103449. * Sets if the ray of the gaze should be displayed.
  103450. */
  103451. set: function (value) {
  103452. this._displayGaze = value;
  103453. if (!value) {
  103454. this._cameraGazer._gazeTracker.isVisible = false;
  103455. if (this._leftController) {
  103456. this._leftController._gazeTracker.isVisible = false;
  103457. }
  103458. if (this._rightController) {
  103459. this._rightController._gazeTracker.isVisible = false;
  103460. }
  103461. }
  103462. },
  103463. enumerable: true,
  103464. configurable: true
  103465. });
  103466. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  103467. /**
  103468. * If the ray of the LaserPointer should be displayed.
  103469. */
  103470. get: function () {
  103471. return this._displayLaserPointer;
  103472. },
  103473. /**
  103474. * Sets if the ray of the LaserPointer should be displayed.
  103475. */
  103476. set: function (value) {
  103477. this._displayLaserPointer = value;
  103478. if (!value) {
  103479. if (this._rightController) {
  103480. this._rightController._deactivatePointer();
  103481. this._rightController._gazeTracker.isVisible = false;
  103482. }
  103483. if (this._leftController) {
  103484. this._leftController._deactivatePointer();
  103485. this._leftController._gazeTracker.isVisible = false;
  103486. }
  103487. }
  103488. else {
  103489. if (this._rightController) {
  103490. this._rightController._activatePointer();
  103491. }
  103492. if (this._leftController) {
  103493. this._leftController._activatePointer();
  103494. }
  103495. }
  103496. },
  103497. enumerable: true,
  103498. configurable: true
  103499. });
  103500. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  103501. /**
  103502. * The deviceOrientationCamera used as the camera when not in VR.
  103503. */
  103504. get: function () {
  103505. return this._deviceOrientationCamera;
  103506. },
  103507. enumerable: true,
  103508. configurable: true
  103509. });
  103510. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  103511. /**
  103512. * Based on the current WebVR support, returns the current VR camera used.
  103513. */
  103514. get: function () {
  103515. if (this._webVRready) {
  103516. return this._webVRCamera;
  103517. }
  103518. else {
  103519. return this._scene.activeCamera;
  103520. }
  103521. },
  103522. enumerable: true,
  103523. configurable: true
  103524. });
  103525. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  103526. /**
  103527. * The webVRCamera which is used when in VR.
  103528. */
  103529. get: function () {
  103530. return this._webVRCamera;
  103531. },
  103532. enumerable: true,
  103533. configurable: true
  103534. });
  103535. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  103536. /**
  103537. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  103538. */
  103539. get: function () {
  103540. return this._vrDeviceOrientationCamera;
  103541. },
  103542. enumerable: true,
  103543. configurable: true
  103544. });
  103545. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  103546. get: function () {
  103547. var result = this._cameraGazer._teleportationRequestInitiated
  103548. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  103549. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  103550. return result;
  103551. },
  103552. enumerable: true,
  103553. configurable: true
  103554. });
  103555. // Raised when one of the controller has loaded successfully its associated default mesh
  103556. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  103557. if (this._leftController && this._leftController.webVRController == webVRController) {
  103558. if (webVRController.mesh) {
  103559. this._leftController._setLaserPointerParent(webVRController.mesh);
  103560. }
  103561. }
  103562. if (this._rightController && this._rightController.webVRController == webVRController) {
  103563. if (webVRController.mesh) {
  103564. this._rightController._setLaserPointerParent(webVRController.mesh);
  103565. }
  103566. }
  103567. try {
  103568. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  103569. }
  103570. catch (err) {
  103571. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  103572. }
  103573. };
  103574. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  103575. /**
  103576. * Gets a value indicating if we are currently in VR mode.
  103577. */
  103578. get: function () {
  103579. return this._webVRpresenting || this._fullscreenVRpresenting;
  103580. },
  103581. enumerable: true,
  103582. configurable: true
  103583. });
  103584. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  103585. var vrDisplay = this._scene.getEngine().getVRDevice();
  103586. if (vrDisplay) {
  103587. var wasPresenting = this._webVRpresenting;
  103588. this._webVRpresenting = vrDisplay.isPresenting;
  103589. if (wasPresenting && !this._webVRpresenting)
  103590. this.exitVR();
  103591. }
  103592. else {
  103593. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  103594. }
  103595. this.updateButtonVisibility();
  103596. };
  103597. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  103598. this._webVRsupported = eventArgs.vrSupported;
  103599. this._webVRready = !!eventArgs.vrDisplay;
  103600. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  103601. this.updateButtonVisibility();
  103602. };
  103603. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  103604. if (this._canvas && !this._useCustomVRButton) {
  103605. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  103606. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  103607. }
  103608. };
  103609. VRExperienceHelper.prototype.displayVRButton = function () {
  103610. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  103611. document.body.appendChild(this._btnVR);
  103612. this._btnVRDisplayed = true;
  103613. }
  103614. };
  103615. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  103616. if (!this._btnVR || this._useCustomVRButton) {
  103617. return;
  103618. }
  103619. this._btnVR.className = "babylonVRicon";
  103620. if (this.isInVRMode) {
  103621. this._btnVR.className += " vrdisplaypresenting";
  103622. }
  103623. else {
  103624. if (this._webVRready)
  103625. this._btnVR.className += " vrdisplayready";
  103626. if (this._webVRsupported)
  103627. this._btnVR.className += " vrdisplaysupported";
  103628. if (this._webVRrequesting)
  103629. this._btnVR.className += " vrdisplayrequesting";
  103630. }
  103631. };
  103632. /**
  103633. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  103634. * Otherwise, will use the fullscreen API.
  103635. */
  103636. VRExperienceHelper.prototype.enterVR = function () {
  103637. if (this.onEnteringVRObservable) {
  103638. try {
  103639. this.onEnteringVRObservable.notifyObservers(this);
  103640. }
  103641. catch (err) {
  103642. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  103643. }
  103644. }
  103645. if (this._scene.activeCamera) {
  103646. this._position = this._scene.activeCamera.position.clone();
  103647. // make sure that we return to the last active camera
  103648. this._existingCamera = this._scene.activeCamera;
  103649. }
  103650. if (this._webVRrequesting)
  103651. return;
  103652. // If WebVR is supported and a headset is connected
  103653. if (this._webVRready) {
  103654. if (!this._webVRpresenting) {
  103655. this._webVRCamera.position = this._position;
  103656. this._scene.activeCamera = this._webVRCamera;
  103657. }
  103658. }
  103659. else if (this._vrDeviceOrientationCamera) {
  103660. this._vrDeviceOrientationCamera.position = this._position;
  103661. if (this._scene.activeCamera) {
  103662. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  103663. }
  103664. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  103665. this._scene.getEngine().switchFullscreen(true);
  103666. this.updateButtonVisibility();
  103667. }
  103668. if (this._scene.activeCamera && this._canvas) {
  103669. this._scene.activeCamera.attachControl(this._canvas);
  103670. }
  103671. if (this._interactionsEnabled) {
  103672. this._scene.registerBeforeRender(this.beforeRender);
  103673. }
  103674. this._hasEnteredVR = true;
  103675. };
  103676. /**
  103677. * Attempt to exit VR, or fullscreen.
  103678. */
  103679. VRExperienceHelper.prototype.exitVR = function () {
  103680. if (this._hasEnteredVR) {
  103681. if (this.onExitingVRObservable) {
  103682. try {
  103683. this.onExitingVRObservable.notifyObservers(this);
  103684. }
  103685. catch (err) {
  103686. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  103687. }
  103688. }
  103689. if (this._webVRpresenting) {
  103690. this._scene.getEngine().disableVR();
  103691. }
  103692. if (this._scene.activeCamera) {
  103693. this._position = this._scene.activeCamera.position.clone();
  103694. }
  103695. if (this._deviceOrientationCamera) {
  103696. this._deviceOrientationCamera.position = this._position;
  103697. this._scene.activeCamera = this._deviceOrientationCamera;
  103698. if (this._canvas) {
  103699. this._scene.activeCamera.attachControl(this._canvas);
  103700. }
  103701. }
  103702. else if (this._existingCamera) {
  103703. this._existingCamera.position = this._position;
  103704. this._scene.activeCamera = this._existingCamera;
  103705. }
  103706. this.updateButtonVisibility();
  103707. if (this._interactionsEnabled) {
  103708. this._scene.unregisterBeforeRender(this.beforeRender);
  103709. this._cameraGazer._gazeTracker.isVisible = false;
  103710. if (this._leftController) {
  103711. this._leftController._gazeTracker.isVisible = false;
  103712. }
  103713. if (this._rightController) {
  103714. this._rightController._gazeTracker.isVisible = false;
  103715. }
  103716. }
  103717. // resize to update width and height when exiting vr exits fullscreen
  103718. this._scene.getEngine().resize();
  103719. this._hasEnteredVR = false;
  103720. }
  103721. };
  103722. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  103723. /**
  103724. * The position of the vr experience helper.
  103725. */
  103726. get: function () {
  103727. return this._position;
  103728. },
  103729. /**
  103730. * Sets the position of the vr experience helper.
  103731. */
  103732. set: function (value) {
  103733. this._position = value;
  103734. if (this._scene.activeCamera) {
  103735. this._scene.activeCamera.position = value;
  103736. }
  103737. },
  103738. enumerable: true,
  103739. configurable: true
  103740. });
  103741. /**
  103742. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  103743. */
  103744. VRExperienceHelper.prototype.enableInteractions = function () {
  103745. var _this = this;
  103746. if (!this._interactionsEnabled) {
  103747. this._interactionsRequested = true;
  103748. if (this._leftController) {
  103749. this._enableInteractionOnController(this._leftController);
  103750. }
  103751. if (this._rightController) {
  103752. this._enableInteractionOnController(this._rightController);
  103753. }
  103754. this.raySelectionPredicate = function (mesh) {
  103755. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  103756. };
  103757. this.meshSelectionPredicate = function (mesh) {
  103758. return true;
  103759. };
  103760. this._raySelectionPredicate = function (mesh) {
  103761. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  103762. && mesh.name.indexOf("teleportationTarget") === -1
  103763. && mesh.name.indexOf("torusTeleportation") === -1)) {
  103764. return _this.raySelectionPredicate(mesh);
  103765. }
  103766. return false;
  103767. };
  103768. this._interactionsEnabled = true;
  103769. }
  103770. };
  103771. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  103772. get: function () {
  103773. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  103774. },
  103775. enumerable: true,
  103776. configurable: true
  103777. });
  103778. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  103779. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  103780. if (this._floorMeshesCollection[i].id === mesh.id) {
  103781. return true;
  103782. }
  103783. }
  103784. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  103785. return true;
  103786. }
  103787. return false;
  103788. };
  103789. /**
  103790. * Adds a floor mesh to be used for teleportation.
  103791. * @param floorMesh the mesh to be used for teleportation.
  103792. */
  103793. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  103794. if (!this._floorMeshesCollection) {
  103795. return;
  103796. }
  103797. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  103798. return;
  103799. }
  103800. this._floorMeshesCollection.push(floorMesh);
  103801. };
  103802. /**
  103803. * Removes a floor mesh from being used for teleportation.
  103804. * @param floorMesh the mesh to be removed.
  103805. */
  103806. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  103807. if (!this._floorMeshesCollection) {
  103808. return;
  103809. }
  103810. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  103811. if (meshIndex !== -1) {
  103812. this._floorMeshesCollection.splice(meshIndex, 1);
  103813. }
  103814. };
  103815. /**
  103816. * Enables interactions and teleportation using the VR controllers and gaze.
  103817. * @param vrTeleportationOptions options to modify teleportation behavior.
  103818. */
  103819. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  103820. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  103821. if (!this._teleportationInitialized) {
  103822. this._teleportationRequested = true;
  103823. this.enableInteractions();
  103824. if (vrTeleportationOptions.floorMeshName) {
  103825. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  103826. }
  103827. if (vrTeleportationOptions.floorMeshes) {
  103828. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  103829. }
  103830. if (this._leftController != null) {
  103831. this._enableTeleportationOnController(this._leftController);
  103832. }
  103833. if (this._rightController != null) {
  103834. this._enableTeleportationOnController(this._rightController);
  103835. }
  103836. // Creates an image processing post process for the vignette not relying
  103837. // on the main scene configuration for image processing to reduce setup and spaces
  103838. // (gamma/linear) conflicts.
  103839. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  103840. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  103841. imageProcessingConfiguration.vignetteEnabled = true;
  103842. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  103843. this._webVRCamera.detachPostProcess(this._postProcessMove);
  103844. this._teleportationInitialized = true;
  103845. if (this._isDefaultTeleportationTarget) {
  103846. this._createTeleportationCircles();
  103847. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  103848. }
  103849. }
  103850. };
  103851. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  103852. var _this = this;
  103853. var controllerMesh = controller.webVRController.mesh;
  103854. if (controllerMesh) {
  103855. controller._interactionsEnabled = true;
  103856. controller._activatePointer();
  103857. if (this.webVROptions.laserToggle) {
  103858. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  103859. // Enabling / disabling laserPointer
  103860. if (_this._displayLaserPointer && stateObject.value === 1) {
  103861. if (controller._activePointer) {
  103862. controller._deactivatePointer();
  103863. }
  103864. else {
  103865. controller._activatePointer();
  103866. }
  103867. if (_this.displayGaze) {
  103868. controller._gazeTracker.isVisible = controller._activePointer;
  103869. }
  103870. }
  103871. });
  103872. }
  103873. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  103874. var gazer = controller;
  103875. if (_this._noControllerIsActive) {
  103876. gazer = _this._cameraGazer;
  103877. }
  103878. if (!gazer._pointerDownOnMeshAsked) {
  103879. if (stateObject.value > _this._padSensibilityUp) {
  103880. gazer._selectionPointerDown();
  103881. }
  103882. }
  103883. else if (stateObject.value < _this._padSensibilityDown) {
  103884. gazer._selectionPointerUp();
  103885. }
  103886. });
  103887. }
  103888. };
  103889. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  103890. // Dont teleport if another gaze already requested teleportation
  103891. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  103892. return;
  103893. }
  103894. if (!gazer._teleportationRequestInitiated) {
  103895. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  103896. gazer._activatePointer();
  103897. gazer._teleportationRequestInitiated = true;
  103898. }
  103899. }
  103900. else {
  103901. // Listening to the proper controller values changes to confirm teleportation
  103902. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  103903. if (this._teleportActive) {
  103904. this.teleportCamera(this._haloCenter);
  103905. }
  103906. gazer._teleportationRequestInitiated = false;
  103907. }
  103908. }
  103909. };
  103910. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  103911. // Only rotate when user is not currently selecting a teleportation location
  103912. if (gazer._teleportationRequestInitiated) {
  103913. return;
  103914. }
  103915. if (!gazer._rotationLeftAsked) {
  103916. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  103917. gazer._rotationLeftAsked = true;
  103918. if (this._rotationAllowed) {
  103919. this._rotateCamera(false);
  103920. }
  103921. }
  103922. }
  103923. else {
  103924. if (stateObject.x > -this._padSensibilityDown) {
  103925. gazer._rotationLeftAsked = false;
  103926. }
  103927. }
  103928. if (!gazer._rotationRightAsked) {
  103929. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  103930. gazer._rotationRightAsked = true;
  103931. if (this._rotationAllowed) {
  103932. this._rotateCamera(true);
  103933. }
  103934. }
  103935. }
  103936. else {
  103937. if (stateObject.x < this._padSensibilityDown) {
  103938. gazer._rotationRightAsked = false;
  103939. }
  103940. }
  103941. };
  103942. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  103943. // Only teleport backwards when user is not currently selecting a teleportation location
  103944. if (gazer._teleportationRequestInitiated) {
  103945. return;
  103946. }
  103947. // Teleport backwards
  103948. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  103949. if (!gazer._teleportationBackRequestInitiated) {
  103950. if (!this.currentVRCamera) {
  103951. return;
  103952. }
  103953. // Get rotation and position of the current camera
  103954. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  103955. var position = this.currentVRCamera.position;
  103956. // If the camera has device position, use that instead
  103957. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  103958. rotation = this.currentVRCamera.deviceRotationQuaternion;
  103959. position = this.currentVRCamera.devicePosition;
  103960. }
  103961. // Get matrix with only the y rotation of the device rotation
  103962. rotation.toEulerAnglesToRef(this._workingVector);
  103963. this._workingVector.z = 0;
  103964. this._workingVector.x = 0;
  103965. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  103966. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  103967. // Rotate backwards ray by device rotation to cast at the ground behind the user
  103968. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  103969. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  103970. var ray = new BABYLON.Ray(position, this._workingVector);
  103971. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  103972. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  103973. this.teleportCamera(hit.pickedPoint);
  103974. }
  103975. gazer._teleportationBackRequestInitiated = true;
  103976. }
  103977. }
  103978. else {
  103979. gazer._teleportationBackRequestInitiated = false;
  103980. }
  103981. };
  103982. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  103983. var _this = this;
  103984. var controllerMesh = controller.webVRController.mesh;
  103985. if (controllerMesh) {
  103986. if (!controller._interactionsEnabled) {
  103987. this._enableInteractionOnController(controller);
  103988. }
  103989. controller._interactionsEnabled = true;
  103990. controller._teleportationEnabled = true;
  103991. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  103992. controller._dpadPressed = false;
  103993. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  103994. controller._dpadPressed = stateObject.pressed;
  103995. if (!controller._dpadPressed) {
  103996. controller._rotationLeftAsked = false;
  103997. controller._rotationRightAsked = false;
  103998. controller._teleportationBackRequestInitiated = false;
  103999. }
  104000. });
  104001. }
  104002. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  104003. if (_this.teleportationEnabled) {
  104004. _this._checkTeleportBackwards(stateObject, controller);
  104005. _this._checkTeleportWithRay(stateObject, controller);
  104006. }
  104007. _this._checkRotate(stateObject, controller);
  104008. });
  104009. }
  104010. };
  104011. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  104012. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  104013. this._teleportationTarget.isPickable = false;
  104014. var length = 512;
  104015. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  104016. dynamicTexture.hasAlpha = true;
  104017. var context = dynamicTexture.getContext();
  104018. var centerX = length / 2;
  104019. var centerY = length / 2;
  104020. var radius = 200;
  104021. context.beginPath();
  104022. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  104023. context.fillStyle = this._teleportationFillColor;
  104024. context.fill();
  104025. context.lineWidth = 10;
  104026. context.strokeStyle = this._teleportationBorderColor;
  104027. context.stroke();
  104028. context.closePath();
  104029. dynamicTexture.update();
  104030. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  104031. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  104032. this._teleportationTarget.material = teleportationCircleMaterial;
  104033. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  104034. torus.isPickable = false;
  104035. torus.parent = this._teleportationTarget;
  104036. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  104037. var keys = [];
  104038. keys.push({
  104039. frame: 0,
  104040. value: 0
  104041. });
  104042. keys.push({
  104043. frame: 30,
  104044. value: 0.4
  104045. });
  104046. keys.push({
  104047. frame: 60,
  104048. value: 0
  104049. });
  104050. animationInnerCircle.setKeys(keys);
  104051. var easingFunction = new BABYLON.SineEase();
  104052. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  104053. animationInnerCircle.setEasingFunction(easingFunction);
  104054. torus.animations = [];
  104055. torus.animations.push(animationInnerCircle);
  104056. this._scene.beginAnimation(torus, 0, 60, true);
  104057. this._hideTeleportationTarget();
  104058. };
  104059. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  104060. this._teleportActive = true;
  104061. if (this._teleportationInitialized) {
  104062. this._teleportationTarget.isVisible = true;
  104063. if (this._isDefaultTeleportationTarget) {
  104064. this._teleportationTarget.getChildren()[0].isVisible = true;
  104065. }
  104066. }
  104067. };
  104068. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  104069. this._teleportActive = false;
  104070. if (this._teleportationInitialized) {
  104071. this._teleportationTarget.isVisible = false;
  104072. if (this._isDefaultTeleportationTarget) {
  104073. this._teleportationTarget.getChildren()[0].isVisible = false;
  104074. }
  104075. }
  104076. };
  104077. VRExperienceHelper.prototype._rotateCamera = function (right) {
  104078. var _this = this;
  104079. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  104080. return;
  104081. }
  104082. if (right) {
  104083. this._rotationAngle++;
  104084. }
  104085. else {
  104086. this._rotationAngle--;
  104087. }
  104088. this.currentVRCamera.animations = [];
  104089. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  104090. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  104091. var animationRotationKeys = [];
  104092. animationRotationKeys.push({
  104093. frame: 0,
  104094. value: this.currentVRCamera.rotationQuaternion
  104095. });
  104096. animationRotationKeys.push({
  104097. frame: 6,
  104098. value: target
  104099. });
  104100. animationRotation.setKeys(animationRotationKeys);
  104101. animationRotation.setEasingFunction(this._circleEase);
  104102. this.currentVRCamera.animations.push(animationRotation);
  104103. this._postProcessMove.animations = [];
  104104. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  104105. var vignetteWeightKeys = [];
  104106. vignetteWeightKeys.push({
  104107. frame: 0,
  104108. value: 0
  104109. });
  104110. vignetteWeightKeys.push({
  104111. frame: 3,
  104112. value: 4
  104113. });
  104114. vignetteWeightKeys.push({
  104115. frame: 6,
  104116. value: 0
  104117. });
  104118. animationPP.setKeys(vignetteWeightKeys);
  104119. animationPP.setEasingFunction(this._circleEase);
  104120. this._postProcessMove.animations.push(animationPP);
  104121. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  104122. var vignetteStretchKeys = [];
  104123. vignetteStretchKeys.push({
  104124. frame: 0,
  104125. value: 0
  104126. });
  104127. vignetteStretchKeys.push({
  104128. frame: 3,
  104129. value: 10
  104130. });
  104131. vignetteStretchKeys.push({
  104132. frame: 6,
  104133. value: 0
  104134. });
  104135. animationPP2.setKeys(vignetteStretchKeys);
  104136. animationPP2.setEasingFunction(this._circleEase);
  104137. this._postProcessMove.animations.push(animationPP2);
  104138. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  104139. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  104140. this._postProcessMove.samples = 4;
  104141. this._webVRCamera.attachPostProcess(this._postProcessMove);
  104142. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  104143. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  104144. });
  104145. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  104146. };
  104147. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  104148. if (hit.pickedPoint) {
  104149. if (gazer._teleportationRequestInitiated) {
  104150. this._displayTeleportationTarget();
  104151. this._haloCenter.copyFrom(hit.pickedPoint);
  104152. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  104153. }
  104154. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  104155. if (pickNormal) {
  104156. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  104157. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  104158. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  104159. }
  104160. this._teleportationTarget.position.y += 0.1;
  104161. }
  104162. };
  104163. /**
  104164. * Teleports the users feet to the desired location
  104165. * @param location The location where the user's feet should be placed
  104166. */
  104167. VRExperienceHelper.prototype.teleportCamera = function (location) {
  104168. var _this = this;
  104169. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  104170. return;
  104171. }
  104172. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  104173. // offset of the headset from the anchor.
  104174. if (this.webVRCamera.leftCamera) {
  104175. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  104176. this._workingVector.subtractInPlace(this.webVRCamera.position);
  104177. location.subtractToRef(this._workingVector, this._workingVector);
  104178. }
  104179. else {
  104180. this._workingVector.copyFrom(location);
  104181. }
  104182. // Add height to account for user's height offset
  104183. if (this.isInVRMode) {
  104184. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  104185. }
  104186. else {
  104187. this._workingVector.y += this._defaultHeight;
  104188. }
  104189. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  104190. // Create animation from the camera's position to the new location
  104191. this.currentVRCamera.animations = [];
  104192. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  104193. var animationCameraTeleportationKeys = [{
  104194. frame: 0,
  104195. value: this.currentVRCamera.position
  104196. },
  104197. {
  104198. frame: 11,
  104199. value: this._workingVector
  104200. }
  104201. ];
  104202. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  104203. animationCameraTeleportation.setEasingFunction(this._circleEase);
  104204. this.currentVRCamera.animations.push(animationCameraTeleportation);
  104205. this._postProcessMove.animations = [];
  104206. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  104207. var vignetteWeightKeys = [];
  104208. vignetteWeightKeys.push({
  104209. frame: 0,
  104210. value: 0
  104211. });
  104212. vignetteWeightKeys.push({
  104213. frame: 5,
  104214. value: 8
  104215. });
  104216. vignetteWeightKeys.push({
  104217. frame: 11,
  104218. value: 0
  104219. });
  104220. animationPP.setKeys(vignetteWeightKeys);
  104221. this._postProcessMove.animations.push(animationPP);
  104222. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  104223. var vignetteStretchKeys = [];
  104224. vignetteStretchKeys.push({
  104225. frame: 0,
  104226. value: 0
  104227. });
  104228. vignetteStretchKeys.push({
  104229. frame: 5,
  104230. value: 10
  104231. });
  104232. vignetteStretchKeys.push({
  104233. frame: 11,
  104234. value: 0
  104235. });
  104236. animationPP2.setKeys(vignetteStretchKeys);
  104237. this._postProcessMove.animations.push(animationPP2);
  104238. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  104239. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  104240. this._webVRCamera.attachPostProcess(this._postProcessMove);
  104241. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  104242. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  104243. });
  104244. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  104245. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  104246. });
  104247. this._hideTeleportationTarget();
  104248. };
  104249. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  104250. if (normal) {
  104251. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  104252. if (angle < Math.PI / 2) {
  104253. normal.scaleInPlace(-1);
  104254. }
  104255. }
  104256. return normal;
  104257. };
  104258. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  104259. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  104260. return;
  104261. }
  104262. var ray = gazer._getForwardRay(this._rayLength);
  104263. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  104264. if (hit) {
  104265. // Populate the contrllers mesh that can be used for drag/drop
  104266. if (gazer._laserPointer) {
  104267. hit.originMesh = gazer._laserPointer.parent;
  104268. }
  104269. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  104270. }
  104271. gazer._currentHit = hit;
  104272. // Moving the gazeTracker on the mesh face targetted
  104273. if (hit && hit.pickedPoint) {
  104274. if (this._displayGaze) {
  104275. var multiplier = 1;
  104276. gazer._gazeTracker.isVisible = true;
  104277. if (gazer._isActionableMesh) {
  104278. multiplier = 3;
  104279. }
  104280. if (this.updateGazeTrackerScale) {
  104281. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  104282. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  104283. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  104284. }
  104285. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  104286. // To avoid z-fighting
  104287. var deltaFighting = 0.002;
  104288. if (pickNormal) {
  104289. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  104290. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  104291. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  104292. }
  104293. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  104294. if (gazer._gazeTracker.position.x < 0) {
  104295. gazer._gazeTracker.position.x += deltaFighting;
  104296. }
  104297. else {
  104298. gazer._gazeTracker.position.x -= deltaFighting;
  104299. }
  104300. if (gazer._gazeTracker.position.y < 0) {
  104301. gazer._gazeTracker.position.y += deltaFighting;
  104302. }
  104303. else {
  104304. gazer._gazeTracker.position.y -= deltaFighting;
  104305. }
  104306. if (gazer._gazeTracker.position.z < 0) {
  104307. gazer._gazeTracker.position.z += deltaFighting;
  104308. }
  104309. else {
  104310. gazer._gazeTracker.position.z -= deltaFighting;
  104311. }
  104312. }
  104313. // Changing the size of the laser pointer based on the distance from the targetted point
  104314. gazer._updatePointerDistance(hit.distance);
  104315. }
  104316. else {
  104317. gazer._updatePointerDistance();
  104318. gazer._gazeTracker.isVisible = false;
  104319. }
  104320. if (hit && hit.pickedMesh) {
  104321. // The object selected is the floor, we're in a teleportation scenario
  104322. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  104323. // Moving the teleportation area to this targetted point
  104324. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  104325. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  104326. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  104327. }
  104328. gazer._currentMeshSelected = null;
  104329. if (gazer._teleportationRequestInitiated) {
  104330. this._moveTeleportationSelectorTo(hit, gazer, ray);
  104331. }
  104332. return;
  104333. }
  104334. // If not, we're in a selection scenario
  104335. //this._teleportationAllowed = false;
  104336. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  104337. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  104338. this.onNewMeshPicked.notifyObservers(hit);
  104339. gazer._currentMeshSelected = hit.pickedMesh;
  104340. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  104341. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  104342. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  104343. gazer._isActionableMesh = true;
  104344. }
  104345. else {
  104346. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  104347. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  104348. gazer._isActionableMesh = false;
  104349. }
  104350. try {
  104351. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  104352. }
  104353. catch (err) {
  104354. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  104355. }
  104356. }
  104357. else {
  104358. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  104359. gazer._currentMeshSelected = null;
  104360. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  104361. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  104362. }
  104363. }
  104364. }
  104365. else {
  104366. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  104367. gazer._currentMeshSelected = null;
  104368. //this._teleportationAllowed = false;
  104369. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  104370. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  104371. }
  104372. };
  104373. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  104374. if (mesh) {
  104375. this.onSelectedMeshUnselected.notifyObservers(mesh);
  104376. }
  104377. };
  104378. /**
  104379. * Sets the color of the laser ray from the vr controllers.
  104380. * @param color new color for the ray.
  104381. */
  104382. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  104383. if (this._leftController) {
  104384. this._leftController._setLaserPointerColor(color);
  104385. }
  104386. if (this._rightController) {
  104387. this._rightController._setLaserPointerColor(color);
  104388. }
  104389. };
  104390. /**
  104391. * Sets the color of the ray from the vr headsets gaze.
  104392. * @param color new color for the ray.
  104393. */
  104394. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  104395. if (!this._cameraGazer._gazeTracker.material) {
  104396. return;
  104397. }
  104398. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  104399. if (this._leftController) {
  104400. this._leftController._gazeTracker.material.emissiveColor = color;
  104401. }
  104402. if (this._rightController) {
  104403. this._rightController._gazeTracker.material.emissiveColor = color;
  104404. }
  104405. };
  104406. /**
  104407. * Exits VR and disposes of the vr experience helper
  104408. */
  104409. VRExperienceHelper.prototype.dispose = function () {
  104410. if (this.isInVRMode) {
  104411. this.exitVR();
  104412. }
  104413. if (this._postProcessMove) {
  104414. this._postProcessMove.dispose();
  104415. }
  104416. if (this._webVRCamera) {
  104417. this._webVRCamera.dispose();
  104418. }
  104419. if (this._vrDeviceOrientationCamera) {
  104420. this._vrDeviceOrientationCamera.dispose();
  104421. }
  104422. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  104423. document.body.removeChild(this._btnVR);
  104424. }
  104425. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  104426. this._deviceOrientationCamera.dispose();
  104427. }
  104428. if (this._cameraGazer) {
  104429. this._cameraGazer.dispose();
  104430. }
  104431. if (this._leftController) {
  104432. this._leftController.dispose();
  104433. }
  104434. if (this._rightController) {
  104435. this._rightController.dispose();
  104436. }
  104437. if (this._teleportationTarget) {
  104438. this._teleportationTarget.dispose();
  104439. }
  104440. this._floorMeshesCollection = [];
  104441. document.removeEventListener("keydown", this._onKeyDown);
  104442. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  104443. window.removeEventListener("resize", this._onResize);
  104444. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  104445. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  104446. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  104447. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  104448. document.onmsfullscreenchange = null;
  104449. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  104450. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  104451. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  104452. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  104453. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  104454. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  104455. this._scene.unregisterBeforeRender(this.beforeRender);
  104456. };
  104457. /**
  104458. * Gets the name of the VRExperienceHelper class
  104459. * @returns "VRExperienceHelper"
  104460. */
  104461. VRExperienceHelper.prototype.getClassName = function () {
  104462. return "VRExperienceHelper";
  104463. };
  104464. return VRExperienceHelper;
  104465. }());
  104466. BABYLON.VRExperienceHelper = VRExperienceHelper;
  104467. })(BABYLON || (BABYLON = {}));
  104468. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  104469. // Mainly based on these 2 articles :
  104470. // 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
  104471. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  104472. var BABYLON;
  104473. (function (BABYLON) {
  104474. /**
  104475. * Defines the potential axis of a Joystick
  104476. */
  104477. var JoystickAxis;
  104478. (function (JoystickAxis) {
  104479. /** X axis */
  104480. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  104481. /** Y axis */
  104482. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  104483. /** Z axis */
  104484. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  104485. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  104486. /**
  104487. * Class used to define virtual joystick (used in touch mode)
  104488. */
  104489. var VirtualJoystick = /** @class */ (function () {
  104490. /**
  104491. * Creates a new virtual joystick
  104492. * @param leftJoystick defines that the joystick is for left hand (false by default)
  104493. */
  104494. function VirtualJoystick(leftJoystick) {
  104495. var _this = this;
  104496. if (leftJoystick) {
  104497. this._leftJoystick = true;
  104498. }
  104499. else {
  104500. this._leftJoystick = false;
  104501. }
  104502. VirtualJoystick._globalJoystickIndex++;
  104503. // By default left & right arrow keys are moving the X
  104504. // and up & down keys are moving the Y
  104505. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  104506. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  104507. this.reverseLeftRight = false;
  104508. this.reverseUpDown = false;
  104509. // collections of pointers
  104510. this._touches = new BABYLON.StringDictionary();
  104511. this.deltaPosition = BABYLON.Vector3.Zero();
  104512. this._joystickSensibility = 25;
  104513. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  104514. this._onResize = function (evt) {
  104515. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  104516. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  104517. if (VirtualJoystick.vjCanvas) {
  104518. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  104519. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  104520. }
  104521. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  104522. };
  104523. // injecting a canvas element on top of the canvas 3D game
  104524. if (!VirtualJoystick.vjCanvas) {
  104525. window.addEventListener("resize", this._onResize, false);
  104526. VirtualJoystick.vjCanvas = document.createElement("canvas");
  104527. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  104528. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  104529. VirtualJoystick.vjCanvas.width = window.innerWidth;
  104530. VirtualJoystick.vjCanvas.height = window.innerHeight;
  104531. VirtualJoystick.vjCanvas.style.width = "100%";
  104532. VirtualJoystick.vjCanvas.style.height = "100%";
  104533. VirtualJoystick.vjCanvas.style.position = "absolute";
  104534. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  104535. VirtualJoystick.vjCanvas.style.top = "0px";
  104536. VirtualJoystick.vjCanvas.style.left = "0px";
  104537. VirtualJoystick.vjCanvas.style.zIndex = "5";
  104538. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  104539. // Support for jQuery PEP polyfill
  104540. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  104541. var context = VirtualJoystick.vjCanvas.getContext('2d');
  104542. if (!context) {
  104543. throw new Error("Unable to create canvas for virtual joystick");
  104544. }
  104545. VirtualJoystick.vjCanvasContext = context;
  104546. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  104547. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  104548. document.body.appendChild(VirtualJoystick.vjCanvas);
  104549. }
  104550. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  104551. this.pressed = false;
  104552. // default joystick color
  104553. this._joystickColor = "cyan";
  104554. this._joystickPointerID = -1;
  104555. // current joystick position
  104556. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  104557. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  104558. // origin joystick position
  104559. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  104560. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  104561. this._onPointerDownHandlerRef = function (evt) {
  104562. _this._onPointerDown(evt);
  104563. };
  104564. this._onPointerMoveHandlerRef = function (evt) {
  104565. _this._onPointerMove(evt);
  104566. };
  104567. this._onPointerUpHandlerRef = function (evt) {
  104568. _this._onPointerUp(evt);
  104569. };
  104570. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  104571. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  104572. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  104573. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  104574. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  104575. evt.preventDefault(); // Disables system menu
  104576. }, false);
  104577. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  104578. }
  104579. /**
  104580. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  104581. * @param newJoystickSensibility defines the new sensibility
  104582. */
  104583. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  104584. this._joystickSensibility = newJoystickSensibility;
  104585. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  104586. };
  104587. VirtualJoystick.prototype._onPointerDown = function (e) {
  104588. var positionOnScreenCondition;
  104589. e.preventDefault();
  104590. if (this._leftJoystick === true) {
  104591. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  104592. }
  104593. else {
  104594. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  104595. }
  104596. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  104597. // First contact will be dedicated to the virtual joystick
  104598. this._joystickPointerID = e.pointerId;
  104599. this._joystickPointerStartPos.x = e.clientX;
  104600. this._joystickPointerStartPos.y = e.clientY;
  104601. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  104602. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  104603. this._deltaJoystickVector.x = 0;
  104604. this._deltaJoystickVector.y = 0;
  104605. this.pressed = true;
  104606. this._touches.add(e.pointerId.toString(), e);
  104607. }
  104608. else {
  104609. // You can only trigger the action buttons with a joystick declared
  104610. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  104611. this._action();
  104612. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  104613. }
  104614. }
  104615. };
  104616. VirtualJoystick.prototype._onPointerMove = function (e) {
  104617. // If the current pointer is the one associated to the joystick (first touch contact)
  104618. if (this._joystickPointerID == e.pointerId) {
  104619. this._joystickPointerPos.x = e.clientX;
  104620. this._joystickPointerPos.y = e.clientY;
  104621. this._deltaJoystickVector = this._joystickPointerPos.clone();
  104622. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  104623. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  104624. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  104625. switch (this._axisTargetedByLeftAndRight) {
  104626. case JoystickAxis.X:
  104627. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  104628. break;
  104629. case JoystickAxis.Y:
  104630. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  104631. break;
  104632. case JoystickAxis.Z:
  104633. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  104634. break;
  104635. }
  104636. var directionUpDown = this.reverseUpDown ? 1 : -1;
  104637. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  104638. switch (this._axisTargetedByUpAndDown) {
  104639. case JoystickAxis.X:
  104640. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  104641. break;
  104642. case JoystickAxis.Y:
  104643. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  104644. break;
  104645. case JoystickAxis.Z:
  104646. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  104647. break;
  104648. }
  104649. }
  104650. else {
  104651. var data = this._touches.get(e.pointerId.toString());
  104652. if (data) {
  104653. data.x = e.clientX;
  104654. data.y = e.clientY;
  104655. }
  104656. }
  104657. };
  104658. VirtualJoystick.prototype._onPointerUp = function (e) {
  104659. if (this._joystickPointerID == e.pointerId) {
  104660. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  104661. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  104662. this._joystickPointerID = -1;
  104663. this.pressed = false;
  104664. }
  104665. else {
  104666. var touch = this._touches.get(e.pointerId.toString());
  104667. if (touch) {
  104668. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  104669. }
  104670. }
  104671. this._deltaJoystickVector.x = 0;
  104672. this._deltaJoystickVector.y = 0;
  104673. this._touches.remove(e.pointerId.toString());
  104674. };
  104675. /**
  104676. * Change the color of the virtual joystick
  104677. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  104678. */
  104679. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  104680. this._joystickColor = newColor;
  104681. };
  104682. /**
  104683. * Defines a callback to call when the joystick is touched
  104684. * @param action defines the callback
  104685. */
  104686. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  104687. this._action = action;
  104688. };
  104689. /**
  104690. * Defines which axis you'd like to control for left & right
  104691. * @param axis defines the axis to use
  104692. */
  104693. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  104694. switch (axis) {
  104695. case JoystickAxis.X:
  104696. case JoystickAxis.Y:
  104697. case JoystickAxis.Z:
  104698. this._axisTargetedByLeftAndRight = axis;
  104699. break;
  104700. default:
  104701. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  104702. break;
  104703. }
  104704. };
  104705. /**
  104706. * Defines which axis you'd like to control for up & down
  104707. * @param axis defines the axis to use
  104708. */
  104709. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  104710. switch (axis) {
  104711. case JoystickAxis.X:
  104712. case JoystickAxis.Y:
  104713. case JoystickAxis.Z:
  104714. this._axisTargetedByUpAndDown = axis;
  104715. break;
  104716. default:
  104717. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  104718. break;
  104719. }
  104720. };
  104721. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  104722. var _this = this;
  104723. if (this.pressed) {
  104724. this._touches.forEach(function (key, touch) {
  104725. if (touch.pointerId === _this._joystickPointerID) {
  104726. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  104727. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  104728. VirtualJoystick.vjCanvasContext.beginPath();
  104729. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  104730. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  104731. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  104732. VirtualJoystick.vjCanvasContext.stroke();
  104733. VirtualJoystick.vjCanvasContext.closePath();
  104734. VirtualJoystick.vjCanvasContext.beginPath();
  104735. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  104736. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  104737. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  104738. VirtualJoystick.vjCanvasContext.stroke();
  104739. VirtualJoystick.vjCanvasContext.closePath();
  104740. VirtualJoystick.vjCanvasContext.beginPath();
  104741. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  104742. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  104743. VirtualJoystick.vjCanvasContext.stroke();
  104744. VirtualJoystick.vjCanvasContext.closePath();
  104745. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  104746. }
  104747. else {
  104748. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  104749. VirtualJoystick.vjCanvasContext.beginPath();
  104750. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  104751. VirtualJoystick.vjCanvasContext.beginPath();
  104752. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  104753. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  104754. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  104755. VirtualJoystick.vjCanvasContext.stroke();
  104756. VirtualJoystick.vjCanvasContext.closePath();
  104757. touch.prevX = touch.x;
  104758. touch.prevY = touch.y;
  104759. }
  104760. ;
  104761. });
  104762. }
  104763. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  104764. };
  104765. /**
  104766. * Release internal HTML canvas
  104767. */
  104768. VirtualJoystick.prototype.releaseCanvas = function () {
  104769. if (VirtualJoystick.vjCanvas) {
  104770. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  104771. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  104772. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  104773. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  104774. window.removeEventListener("resize", this._onResize);
  104775. document.body.removeChild(VirtualJoystick.vjCanvas);
  104776. VirtualJoystick.vjCanvas = null;
  104777. }
  104778. };
  104779. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  104780. VirtualJoystick._globalJoystickIndex = 0;
  104781. return VirtualJoystick;
  104782. }());
  104783. BABYLON.VirtualJoystick = VirtualJoystick;
  104784. })(BABYLON || (BABYLON = {}));
  104785. //# sourceMappingURL=babylon.virtualJoystick.js.map
  104786. var BABYLON;
  104787. (function (BABYLON) {
  104788. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  104789. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  104790. });
  104791. /**
  104792. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  104793. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  104794. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  104795. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  104796. */
  104797. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  104798. __extends(VirtualJoysticksCamera, _super);
  104799. /**
  104800. * Intantiates a VirtualJoysticksCamera. It can be usefull in First Person Shooter game for instance.
  104801. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  104802. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  104803. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  104804. * @param name Define the name of the camera in the scene
  104805. * @param position Define the start position of the camera in the scene
  104806. * @param scene Define the scene the camera belongs to
  104807. */
  104808. function VirtualJoysticksCamera(name, position, scene) {
  104809. var _this = _super.call(this, name, position, scene) || this;
  104810. _this.inputs.addVirtualJoystick();
  104811. return _this;
  104812. }
  104813. /**
  104814. * Gets the current object class name.
  104815. * @return the class name
  104816. */
  104817. VirtualJoysticksCamera.prototype.getClassName = function () {
  104818. return "VirtualJoysticksCamera";
  104819. };
  104820. return VirtualJoysticksCamera;
  104821. }(BABYLON.FreeCamera));
  104822. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  104823. })(BABYLON || (BABYLON = {}));
  104824. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  104825. var BABYLON;
  104826. (function (BABYLON) {
  104827. /**
  104828. * Manage the Virtual Joystick inputs to control the movement of a free camera.
  104829. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  104830. */
  104831. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  104832. function FreeCameraVirtualJoystickInput() {
  104833. }
  104834. /**
  104835. * Gets the left stick of the virtual joystick.
  104836. * @returns The virtual Joystick
  104837. */
  104838. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  104839. return this._leftjoystick;
  104840. };
  104841. /**
  104842. * Gets the right stick of the virtual joystick.
  104843. * @returns The virtual Joystick
  104844. */
  104845. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  104846. return this._rightjoystick;
  104847. };
  104848. /**
  104849. * Update the current camera state depending on the inputs that have been used this frame.
  104850. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  104851. */
  104852. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  104853. if (this._leftjoystick) {
  104854. var camera = this.camera;
  104855. var speed = camera._computeLocalCameraSpeed() * 50;
  104856. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  104857. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  104858. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  104859. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  104860. if (!this._leftjoystick.pressed) {
  104861. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  104862. }
  104863. if (!this._rightjoystick.pressed) {
  104864. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  104865. }
  104866. }
  104867. };
  104868. /**
  104869. * Attach the input controls to a specific dom element to get the input from.
  104870. * @param element Defines the element the controls should be listened from
  104871. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  104872. */
  104873. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  104874. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  104875. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  104876. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  104877. this._leftjoystick.setJoystickSensibility(0.15);
  104878. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  104879. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  104880. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  104881. this._rightjoystick.reverseUpDown = true;
  104882. this._rightjoystick.setJoystickSensibility(0.05);
  104883. this._rightjoystick.setJoystickColor("yellow");
  104884. };
  104885. /**
  104886. * Detach the current controls from the specified dom element.
  104887. * @param element Defines the element to stop listening the inputs from
  104888. */
  104889. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  104890. this._leftjoystick.releaseCanvas();
  104891. this._rightjoystick.releaseCanvas();
  104892. };
  104893. /**
  104894. * Gets the class name of the current intput.
  104895. * @returns the class name
  104896. */
  104897. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  104898. return "FreeCameraVirtualJoystickInput";
  104899. };
  104900. /**
  104901. * Get the friendly name associated with the input class.
  104902. * @returns the input friendly name
  104903. */
  104904. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  104905. return "virtualJoystick";
  104906. };
  104907. return FreeCameraVirtualJoystickInput;
  104908. }());
  104909. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  104910. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  104911. })(BABYLON || (BABYLON = {}));
  104912. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  104913. var BABYLON;
  104914. (function (BABYLON) {
  104915. /**
  104916. * Class used to specify simplification options
  104917. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  104918. */
  104919. var SimplificationSettings = /** @class */ (function () {
  104920. /**
  104921. * Creates a SimplificationSettings
  104922. * @param quality expected quality
  104923. * @param distance distance when this optimized version should be used
  104924. * @param optimizeMesh already optimized mesh
  104925. */
  104926. function SimplificationSettings(
  104927. /** expected quality */
  104928. quality,
  104929. /** distance when this optimized version should be used */
  104930. distance,
  104931. /** already optimized mesh */
  104932. optimizeMesh) {
  104933. this.quality = quality;
  104934. this.distance = distance;
  104935. this.optimizeMesh = optimizeMesh;
  104936. }
  104937. return SimplificationSettings;
  104938. }());
  104939. BABYLON.SimplificationSettings = SimplificationSettings;
  104940. /**
  104941. * Queue used to order the simplification tasks
  104942. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  104943. */
  104944. var SimplificationQueue = /** @class */ (function () {
  104945. /**
  104946. * Creates a new queue
  104947. */
  104948. function SimplificationQueue() {
  104949. this.running = false;
  104950. this._simplificationArray = [];
  104951. }
  104952. /**
  104953. * Adds a new simplification task
  104954. * @param task defines a task to add
  104955. */
  104956. SimplificationQueue.prototype.addTask = function (task) {
  104957. this._simplificationArray.push(task);
  104958. };
  104959. /**
  104960. * Execute next task
  104961. */
  104962. SimplificationQueue.prototype.executeNext = function () {
  104963. var task = this._simplificationArray.pop();
  104964. if (task) {
  104965. this.running = true;
  104966. this.runSimplification(task);
  104967. }
  104968. else {
  104969. this.running = false;
  104970. }
  104971. };
  104972. /**
  104973. * Execute a simplification task
  104974. * @param task defines the task to run
  104975. */
  104976. SimplificationQueue.prototype.runSimplification = function (task) {
  104977. var _this = this;
  104978. if (task.parallelProcessing) {
  104979. //parallel simplifier
  104980. task.settings.forEach(function (setting) {
  104981. var simplifier = _this.getSimplifier(task);
  104982. simplifier.simplify(setting, function (newMesh) {
  104983. task.mesh.addLODLevel(setting.distance, newMesh);
  104984. newMesh.isVisible = true;
  104985. //check if it is the last
  104986. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  104987. //all done, run the success callback.
  104988. task.successCallback();
  104989. }
  104990. _this.executeNext();
  104991. });
  104992. });
  104993. }
  104994. else {
  104995. //single simplifier.
  104996. var simplifier = this.getSimplifier(task);
  104997. var runDecimation = function (setting, callback) {
  104998. simplifier.simplify(setting, function (newMesh) {
  104999. task.mesh.addLODLevel(setting.distance, newMesh);
  105000. newMesh.isVisible = true;
  105001. //run the next quality level
  105002. callback();
  105003. });
  105004. };
  105005. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  105006. runDecimation(task.settings[loop.index], function () {
  105007. loop.executeNext();
  105008. });
  105009. }, function () {
  105010. //execution ended, run the success callback.
  105011. if (task.successCallback) {
  105012. task.successCallback();
  105013. }
  105014. _this.executeNext();
  105015. });
  105016. }
  105017. };
  105018. SimplificationQueue.prototype.getSimplifier = function (task) {
  105019. switch (task.simplificationType) {
  105020. case SimplificationType.QUADRATIC:
  105021. default:
  105022. return new QuadraticErrorSimplification(task.mesh);
  105023. }
  105024. };
  105025. return SimplificationQueue;
  105026. }());
  105027. BABYLON.SimplificationQueue = SimplificationQueue;
  105028. /**
  105029. * The implemented types of simplification
  105030. * At the moment only Quadratic Error Decimation is implemented
  105031. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  105032. */
  105033. var SimplificationType;
  105034. (function (SimplificationType) {
  105035. /** Quadratic error decimation */
  105036. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  105037. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  105038. var DecimationTriangle = /** @class */ (function () {
  105039. function DecimationTriangle(vertices) {
  105040. this.vertices = vertices;
  105041. this.error = new Array(4);
  105042. this.deleted = false;
  105043. this.isDirty = false;
  105044. this.deletePending = false;
  105045. this.borderFactor = 0;
  105046. }
  105047. return DecimationTriangle;
  105048. }());
  105049. var DecimationVertex = /** @class */ (function () {
  105050. function DecimationVertex(position, id) {
  105051. this.position = position;
  105052. this.id = id;
  105053. this.isBorder = true;
  105054. this.q = new QuadraticMatrix();
  105055. this.triangleCount = 0;
  105056. this.triangleStart = 0;
  105057. this.originalOffsets = [];
  105058. }
  105059. DecimationVertex.prototype.updatePosition = function (newPosition) {
  105060. this.position.copyFrom(newPosition);
  105061. };
  105062. return DecimationVertex;
  105063. }());
  105064. var QuadraticMatrix = /** @class */ (function () {
  105065. function QuadraticMatrix(data) {
  105066. this.data = new Array(10);
  105067. for (var i = 0; i < 10; ++i) {
  105068. if (data && data[i]) {
  105069. this.data[i] = data[i];
  105070. }
  105071. else {
  105072. this.data[i] = 0;
  105073. }
  105074. }
  105075. }
  105076. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  105077. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  105078. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  105079. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  105080. return det;
  105081. };
  105082. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  105083. for (var i = 0; i < 10; ++i) {
  105084. this.data[i] += matrix.data[i];
  105085. }
  105086. };
  105087. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  105088. for (var i = 0; i < 10; ++i) {
  105089. this.data[i] += data[i];
  105090. }
  105091. };
  105092. QuadraticMatrix.prototype.add = function (matrix) {
  105093. var m = new QuadraticMatrix();
  105094. for (var i = 0; i < 10; ++i) {
  105095. m.data[i] = this.data[i] + matrix.data[i];
  105096. }
  105097. return m;
  105098. };
  105099. QuadraticMatrix.FromData = function (a, b, c, d) {
  105100. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  105101. };
  105102. //returning an array to avoid garbage collection
  105103. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  105104. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  105105. };
  105106. return QuadraticMatrix;
  105107. }());
  105108. var Reference = /** @class */ (function () {
  105109. function Reference(vertexId, triangleId) {
  105110. this.vertexId = vertexId;
  105111. this.triangleId = triangleId;
  105112. }
  105113. return Reference;
  105114. }());
  105115. /**
  105116. * An implementation of the Quadratic Error simplification algorithm.
  105117. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  105118. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  105119. * @author RaananW
  105120. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  105121. */
  105122. var QuadraticErrorSimplification = /** @class */ (function () {
  105123. function QuadraticErrorSimplification(_mesh) {
  105124. this._mesh = _mesh;
  105125. this.syncIterations = 5000;
  105126. this.aggressiveness = 7;
  105127. this.decimationIterations = 100;
  105128. this.boundingBoxEpsilon = BABYLON.Epsilon;
  105129. }
  105130. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  105131. var _this = this;
  105132. this.initDecimatedMesh();
  105133. //iterating through the submeshes array, one after the other.
  105134. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  105135. _this.initWithMesh(loop.index, function () {
  105136. _this.runDecimation(settings, loop.index, function () {
  105137. loop.executeNext();
  105138. });
  105139. }, settings.optimizeMesh);
  105140. }, function () {
  105141. setTimeout(function () {
  105142. successCallback(_this._reconstructedMesh);
  105143. }, 0);
  105144. });
  105145. };
  105146. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  105147. var _this = this;
  105148. var targetCount = ~~(this.triangles.length * settings.quality);
  105149. var deletedTriangles = 0;
  105150. var triangleCount = this.triangles.length;
  105151. var iterationFunction = function (iteration, callback) {
  105152. setTimeout(function () {
  105153. if (iteration % 5 === 0) {
  105154. _this.updateMesh(iteration === 0);
  105155. }
  105156. for (var i = 0; i < _this.triangles.length; ++i) {
  105157. _this.triangles[i].isDirty = false;
  105158. }
  105159. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  105160. var trianglesIterator = function (i) {
  105161. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  105162. var t = _this.triangles[tIdx];
  105163. if (!t)
  105164. return;
  105165. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  105166. return;
  105167. }
  105168. for (var j = 0; j < 3; ++j) {
  105169. if (t.error[j] < threshold) {
  105170. var deleted0 = [];
  105171. var deleted1 = [];
  105172. var v0 = t.vertices[j];
  105173. var v1 = t.vertices[(j + 1) % 3];
  105174. if (v0.isBorder || v1.isBorder)
  105175. continue;
  105176. var p = BABYLON.Vector3.Zero();
  105177. var n = BABYLON.Vector3.Zero();
  105178. var uv = BABYLON.Vector2.Zero();
  105179. var color = new BABYLON.Color4(0, 0, 0, 1);
  105180. _this.calculateError(v0, v1, p, n, uv, color);
  105181. var delTr = new Array();
  105182. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  105183. continue;
  105184. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  105185. continue;
  105186. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  105187. continue;
  105188. var uniqueArray = new Array();
  105189. delTr.forEach(function (deletedT) {
  105190. if (uniqueArray.indexOf(deletedT) === -1) {
  105191. deletedT.deletePending = true;
  105192. uniqueArray.push(deletedT);
  105193. }
  105194. });
  105195. if (uniqueArray.length % 2 !== 0) {
  105196. continue;
  105197. }
  105198. v0.q = v1.q.add(v0.q);
  105199. v0.updatePosition(p);
  105200. var tStart = _this.references.length;
  105201. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  105202. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  105203. var tCount = _this.references.length - tStart;
  105204. if (tCount <= v0.triangleCount) {
  105205. if (tCount) {
  105206. for (var c = 0; c < tCount; c++) {
  105207. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  105208. }
  105209. }
  105210. }
  105211. else {
  105212. v0.triangleStart = tStart;
  105213. }
  105214. v0.triangleCount = tCount;
  105215. break;
  105216. }
  105217. }
  105218. };
  105219. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  105220. }, 0);
  105221. };
  105222. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  105223. if (triangleCount - deletedTriangles <= targetCount)
  105224. loop.breakLoop();
  105225. else {
  105226. iterationFunction(loop.index, function () {
  105227. loop.executeNext();
  105228. });
  105229. }
  105230. }, function () {
  105231. setTimeout(function () {
  105232. //reconstruct this part of the mesh
  105233. _this.reconstructMesh(submeshIndex);
  105234. successCallback();
  105235. }, 0);
  105236. });
  105237. };
  105238. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  105239. var _this = this;
  105240. this.vertices = [];
  105241. this.triangles = [];
  105242. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  105243. var indices = this._mesh.getIndices();
  105244. var submesh = this._mesh.subMeshes[submeshIndex];
  105245. var findInVertices = function (positionToSearch) {
  105246. if (optimizeMesh) {
  105247. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  105248. if (_this.vertices[ii].position.equals(positionToSearch)) {
  105249. return _this.vertices[ii];
  105250. }
  105251. }
  105252. }
  105253. return null;
  105254. };
  105255. var vertexReferences = [];
  105256. var vertexInit = function (i) {
  105257. if (!positionData) {
  105258. return;
  105259. }
  105260. var offset = i + submesh.verticesStart;
  105261. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  105262. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  105263. vertex.originalOffsets.push(offset);
  105264. if (vertex.id === _this.vertices.length) {
  105265. _this.vertices.push(vertex);
  105266. }
  105267. vertexReferences.push(vertex.id);
  105268. };
  105269. //var totalVertices = mesh.getTotalVertices();
  105270. var totalVertices = submesh.verticesCount;
  105271. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  105272. var indicesInit = function (i) {
  105273. if (!indices) {
  105274. return;
  105275. }
  105276. var offset = (submesh.indexStart / 3) + i;
  105277. var pos = (offset * 3);
  105278. var i0 = indices[pos + 0];
  105279. var i1 = indices[pos + 1];
  105280. var i2 = indices[pos + 2];
  105281. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  105282. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  105283. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  105284. var triangle = new DecimationTriangle([v0, v1, v2]);
  105285. triangle.originalOffset = pos;
  105286. _this.triangles.push(triangle);
  105287. };
  105288. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  105289. _this.init(callback);
  105290. });
  105291. });
  105292. };
  105293. QuadraticErrorSimplification.prototype.init = function (callback) {
  105294. var _this = this;
  105295. var triangleInit1 = function (i) {
  105296. var t = _this.triangles[i];
  105297. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  105298. for (var j = 0; j < 3; j++) {
  105299. 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))));
  105300. }
  105301. };
  105302. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  105303. var triangleInit2 = function (i) {
  105304. var t = _this.triangles[i];
  105305. for (var j = 0; j < 3; ++j) {
  105306. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  105307. }
  105308. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  105309. };
  105310. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  105311. callback();
  105312. });
  105313. });
  105314. };
  105315. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  105316. var newTriangles = [];
  105317. var i;
  105318. for (i = 0; i < this.vertices.length; ++i) {
  105319. this.vertices[i].triangleCount = 0;
  105320. }
  105321. var t;
  105322. var j;
  105323. for (i = 0; i < this.triangles.length; ++i) {
  105324. if (!this.triangles[i].deleted) {
  105325. t = this.triangles[i];
  105326. for (j = 0; j < 3; ++j) {
  105327. t.vertices[j].triangleCount = 1;
  105328. }
  105329. newTriangles.push(t);
  105330. }
  105331. }
  105332. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  105333. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  105334. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  105335. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  105336. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  105337. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  105338. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  105339. var vertexCount = 0;
  105340. for (i = 0; i < this.vertices.length; ++i) {
  105341. var vertex = this.vertices[i];
  105342. vertex.id = vertexCount;
  105343. if (vertex.triangleCount) {
  105344. vertex.originalOffsets.forEach(function (originalOffset) {
  105345. if (!normalData) {
  105346. return;
  105347. }
  105348. newPositionData.push(vertex.position.x);
  105349. newPositionData.push(vertex.position.y);
  105350. newPositionData.push(vertex.position.z);
  105351. newNormalData.push(normalData[originalOffset * 3]);
  105352. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  105353. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  105354. if (uvs && uvs.length) {
  105355. newUVsData.push(uvs[(originalOffset * 2)]);
  105356. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  105357. }
  105358. else if (colorsData && colorsData.length) {
  105359. newColorsData.push(colorsData[(originalOffset * 4)]);
  105360. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  105361. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  105362. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  105363. }
  105364. ++vertexCount;
  105365. });
  105366. }
  105367. }
  105368. var startingIndex = this._reconstructedMesh.getTotalIndices();
  105369. var startingVertex = this._reconstructedMesh.getTotalVertices();
  105370. var submeshesArray = this._reconstructedMesh.subMeshes;
  105371. this._reconstructedMesh.subMeshes = [];
  105372. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  105373. var originalIndices = this._mesh.getIndices();
  105374. for (i = 0; i < newTriangles.length; ++i) {
  105375. t = newTriangles[i]; //now get the new referencing point for each vertex
  105376. [0, 1, 2].forEach(function (idx) {
  105377. var id = originalIndices[t.originalOffset + idx];
  105378. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  105379. if (offset < 0)
  105380. offset = 0;
  105381. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  105382. });
  105383. }
  105384. //overwriting the old vertex buffers and indices.
  105385. this._reconstructedMesh.setIndices(newIndicesArray);
  105386. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  105387. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  105388. if (newUVsData.length > 0)
  105389. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  105390. if (newColorsData.length > 0)
  105391. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  105392. //create submesh
  105393. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  105394. if (submeshIndex > 0) {
  105395. this._reconstructedMesh.subMeshes = [];
  105396. submeshesArray.forEach(function (submesh) {
  105397. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  105398. });
  105399. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  105400. }
  105401. };
  105402. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  105403. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  105404. this._reconstructedMesh.material = this._mesh.material;
  105405. this._reconstructedMesh.parent = this._mesh.parent;
  105406. this._reconstructedMesh.isVisible = false;
  105407. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  105408. };
  105409. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  105410. for (var i = 0; i < vertex1.triangleCount; ++i) {
  105411. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  105412. if (t.deleted)
  105413. continue;
  105414. var s = this.references[vertex1.triangleStart + i].vertexId;
  105415. var v1 = t.vertices[(s + 1) % 3];
  105416. var v2 = t.vertices[(s + 2) % 3];
  105417. if ((v1 === vertex2 || v2 === vertex2)) {
  105418. deletedArray[i] = true;
  105419. delTr.push(t);
  105420. continue;
  105421. }
  105422. var d1 = v1.position.subtract(point);
  105423. d1 = d1.normalize();
  105424. var d2 = v2.position.subtract(point);
  105425. d2 = d2.normalize();
  105426. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  105427. return true;
  105428. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  105429. deletedArray[i] = false;
  105430. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  105431. return true;
  105432. }
  105433. return false;
  105434. };
  105435. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  105436. var newDeleted = deletedTriangles;
  105437. for (var i = 0; i < vertex.triangleCount; ++i) {
  105438. var ref = this.references[vertex.triangleStart + i];
  105439. var t = this.triangles[ref.triangleId];
  105440. if (t.deleted)
  105441. continue;
  105442. if (deletedArray[i] && t.deletePending) {
  105443. t.deleted = true;
  105444. newDeleted++;
  105445. continue;
  105446. }
  105447. t.vertices[ref.vertexId] = origVertex;
  105448. t.isDirty = true;
  105449. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  105450. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  105451. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  105452. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  105453. this.references.push(ref);
  105454. }
  105455. return newDeleted;
  105456. };
  105457. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  105458. for (var i = 0; i < this.vertices.length; ++i) {
  105459. var vCount = [];
  105460. var vId = [];
  105461. var v = this.vertices[i];
  105462. var j;
  105463. for (j = 0; j < v.triangleCount; ++j) {
  105464. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  105465. for (var ii = 0; ii < 3; ii++) {
  105466. var ofs = 0;
  105467. var vv = triangle.vertices[ii];
  105468. while (ofs < vCount.length) {
  105469. if (vId[ofs] === vv.id)
  105470. break;
  105471. ++ofs;
  105472. }
  105473. if (ofs === vCount.length) {
  105474. vCount.push(1);
  105475. vId.push(vv.id);
  105476. }
  105477. else {
  105478. vCount[ofs]++;
  105479. }
  105480. }
  105481. }
  105482. for (j = 0; j < vCount.length; ++j) {
  105483. if (vCount[j] === 1) {
  105484. this.vertices[vId[j]].isBorder = true;
  105485. }
  105486. else {
  105487. this.vertices[vId[j]].isBorder = false;
  105488. }
  105489. }
  105490. }
  105491. };
  105492. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  105493. if (identifyBorders === void 0) { identifyBorders = false; }
  105494. var i;
  105495. if (!identifyBorders) {
  105496. var newTrianglesVector = [];
  105497. for (i = 0; i < this.triangles.length; ++i) {
  105498. if (!this.triangles[i].deleted) {
  105499. newTrianglesVector.push(this.triangles[i]);
  105500. }
  105501. }
  105502. this.triangles = newTrianglesVector;
  105503. }
  105504. for (i = 0; i < this.vertices.length; ++i) {
  105505. this.vertices[i].triangleCount = 0;
  105506. this.vertices[i].triangleStart = 0;
  105507. }
  105508. var t;
  105509. var j;
  105510. var v;
  105511. for (i = 0; i < this.triangles.length; ++i) {
  105512. t = this.triangles[i];
  105513. for (j = 0; j < 3; ++j) {
  105514. v = t.vertices[j];
  105515. v.triangleCount++;
  105516. }
  105517. }
  105518. var tStart = 0;
  105519. for (i = 0; i < this.vertices.length; ++i) {
  105520. this.vertices[i].triangleStart = tStart;
  105521. tStart += this.vertices[i].triangleCount;
  105522. this.vertices[i].triangleCount = 0;
  105523. }
  105524. var newReferences = new Array(this.triangles.length * 3);
  105525. for (i = 0; i < this.triangles.length; ++i) {
  105526. t = this.triangles[i];
  105527. for (j = 0; j < 3; ++j) {
  105528. v = t.vertices[j];
  105529. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  105530. v.triangleCount++;
  105531. }
  105532. }
  105533. this.references = newReferences;
  105534. if (identifyBorders) {
  105535. this.identifyBorder();
  105536. }
  105537. };
  105538. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  105539. var x = point.x;
  105540. var y = point.y;
  105541. var z = point.z;
  105542. 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
  105543. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  105544. };
  105545. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  105546. var q = vertex1.q.add(vertex2.q);
  105547. var border = vertex1.isBorder && vertex2.isBorder;
  105548. var error = 0;
  105549. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  105550. if (qDet !== 0 && !border) {
  105551. if (!pointResult) {
  105552. pointResult = BABYLON.Vector3.Zero();
  105553. }
  105554. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  105555. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  105556. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  105557. error = this.vertexError(q, pointResult);
  105558. }
  105559. else {
  105560. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  105561. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  105562. var error1 = this.vertexError(q, vertex1.position);
  105563. var error2 = this.vertexError(q, vertex2.position);
  105564. var error3 = this.vertexError(q, p3);
  105565. error = Math.min(error1, error2, error3);
  105566. if (error === error1) {
  105567. if (pointResult) {
  105568. pointResult.copyFrom(vertex1.position);
  105569. }
  105570. }
  105571. else if (error === error2) {
  105572. if (pointResult) {
  105573. pointResult.copyFrom(vertex2.position);
  105574. }
  105575. }
  105576. else {
  105577. if (pointResult) {
  105578. pointResult.copyFrom(p3);
  105579. }
  105580. }
  105581. }
  105582. return error;
  105583. };
  105584. return QuadraticErrorSimplification;
  105585. }());
  105586. })(BABYLON || (BABYLON = {}));
  105587. //# sourceMappingURL=babylon.meshSimplification.js.map
  105588. var BABYLON;
  105589. (function (BABYLON) {
  105590. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  105591. get: function () {
  105592. if (!this._simplificationQueue) {
  105593. this._simplificationQueue = new BABYLON.SimplificationQueue();
  105594. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  105595. if (!component) {
  105596. component = new SimplicationQueueSceneComponent(this);
  105597. this._addComponent(component);
  105598. }
  105599. }
  105600. return this._simplificationQueue;
  105601. },
  105602. set: function (value) {
  105603. this._simplificationQueue = value;
  105604. },
  105605. enumerable: true,
  105606. configurable: true
  105607. });
  105608. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  105609. if (parallelProcessing === void 0) { parallelProcessing = true; }
  105610. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  105611. this.getScene().simplificationQueue.addTask({
  105612. settings: settings,
  105613. parallelProcessing: parallelProcessing,
  105614. mesh: this,
  105615. simplificationType: simplificationType,
  105616. successCallback: successCallback
  105617. });
  105618. return this;
  105619. };
  105620. /**
  105621. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  105622. * created in a scene
  105623. */
  105624. var SimplicationQueueSceneComponent = /** @class */ (function () {
  105625. /**
  105626. * Creates a new instance of the component for the given scene
  105627. * @param scene Defines the scene to register the component in
  105628. */
  105629. function SimplicationQueueSceneComponent(scene) {
  105630. /**
  105631. * The component name helpfull to identify the component in the list of scene components.
  105632. */
  105633. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  105634. this.scene = scene;
  105635. }
  105636. /**
  105637. * Registers the component in a given scene
  105638. */
  105639. SimplicationQueueSceneComponent.prototype.register = function () {
  105640. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  105641. };
  105642. /**
  105643. * Rebuilds the elements related to this component in case of
  105644. * context lost for instance.
  105645. */
  105646. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  105647. // Nothing to do for this component
  105648. };
  105649. /**
  105650. * Disposes the component and the associated ressources
  105651. */
  105652. SimplicationQueueSceneComponent.prototype.dispose = function () {
  105653. // Nothing to do for this component
  105654. };
  105655. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  105656. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  105657. this.scene._simplificationQueue.executeNext();
  105658. }
  105659. };
  105660. return SimplicationQueueSceneComponent;
  105661. }());
  105662. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  105663. })(BABYLON || (BABYLON = {}));
  105664. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  105665. var BABYLON;
  105666. (function (BABYLON) {
  105667. /**
  105668. * Class used to represent a specific level of detail of a mesh
  105669. * @see http://doc.babylonjs.com/how_to/how_to_use_lod
  105670. */
  105671. var MeshLODLevel = /** @class */ (function () {
  105672. /**
  105673. * Creates a new LOD level
  105674. * @param distance defines the distance where this level should star being displayed
  105675. * @param mesh defines the mesh to use to render this level
  105676. */
  105677. function MeshLODLevel(
  105678. /** Defines the distance where this level should star being displayed */
  105679. distance,
  105680. /** Defines the mesh to use to render this level */
  105681. mesh) {
  105682. this.distance = distance;
  105683. this.mesh = mesh;
  105684. }
  105685. return MeshLODLevel;
  105686. }());
  105687. BABYLON.MeshLODLevel = MeshLODLevel;
  105688. })(BABYLON || (BABYLON = {}));
  105689. //# sourceMappingURL=babylon.meshLODLevel.js.map
  105690. var BABYLON;
  105691. (function (BABYLON) {
  105692. /**
  105693. * Defines the root class used to create scene optimization to use with SceneOptimizer
  105694. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105695. */
  105696. var SceneOptimization = /** @class */ (function () {
  105697. /**
  105698. * Creates the SceneOptimization object
  105699. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  105700. * @param desc defines the description associated with the optimization
  105701. */
  105702. function SceneOptimization(
  105703. /**
  105704. * Defines the priority of this optimization (0 by default which means first in the list)
  105705. */
  105706. priority) {
  105707. if (priority === void 0) { priority = 0; }
  105708. this.priority = priority;
  105709. }
  105710. /**
  105711. * Gets a string describing the action executed by the current optimization
  105712. * @returns description string
  105713. */
  105714. SceneOptimization.prototype.getDescription = function () {
  105715. return "";
  105716. };
  105717. /**
  105718. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105719. * @param scene defines the current scene where to apply this optimization
  105720. * @param optimizer defines the current optimizer
  105721. * @returns true if everything that can be done was applied
  105722. */
  105723. SceneOptimization.prototype.apply = function (scene, optimizer) {
  105724. return true;
  105725. };
  105726. ;
  105727. return SceneOptimization;
  105728. }());
  105729. BABYLON.SceneOptimization = SceneOptimization;
  105730. /**
  105731. * Defines an optimization used to reduce the size of render target textures
  105732. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105733. */
  105734. var TextureOptimization = /** @class */ (function (_super) {
  105735. __extends(TextureOptimization, _super);
  105736. /**
  105737. * Creates the TextureOptimization object
  105738. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  105739. * @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
  105740. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  105741. */
  105742. function TextureOptimization(
  105743. /**
  105744. * Defines the priority of this optimization (0 by default which means first in the list)
  105745. */
  105746. priority,
  105747. /**
  105748. * 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
  105749. */
  105750. maximumSize,
  105751. /**
  105752. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  105753. */
  105754. step) {
  105755. if (priority === void 0) { priority = 0; }
  105756. if (maximumSize === void 0) { maximumSize = 1024; }
  105757. if (step === void 0) { step = 0.5; }
  105758. var _this = _super.call(this, priority) || this;
  105759. _this.priority = priority;
  105760. _this.maximumSize = maximumSize;
  105761. _this.step = step;
  105762. return _this;
  105763. }
  105764. /**
  105765. * Gets a string describing the action executed by the current optimization
  105766. * @returns description string
  105767. */
  105768. TextureOptimization.prototype.getDescription = function () {
  105769. return "Reducing render target texture size to " + this.maximumSize;
  105770. };
  105771. /**
  105772. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105773. * @param scene defines the current scene where to apply this optimization
  105774. * @param optimizer defines the current optimizer
  105775. * @returns true if everything that can be done was applied
  105776. */
  105777. TextureOptimization.prototype.apply = function (scene, optimizer) {
  105778. var allDone = true;
  105779. for (var index = 0; index < scene.textures.length; index++) {
  105780. var texture = scene.textures[index];
  105781. if (!texture.canRescale || texture.getContext) {
  105782. continue;
  105783. }
  105784. var currentSize = texture.getSize();
  105785. var maxDimension = Math.max(currentSize.width, currentSize.height);
  105786. if (maxDimension > this.maximumSize) {
  105787. texture.scale(this.step);
  105788. allDone = false;
  105789. }
  105790. }
  105791. return allDone;
  105792. };
  105793. return TextureOptimization;
  105794. }(SceneOptimization));
  105795. BABYLON.TextureOptimization = TextureOptimization;
  105796. /**
  105797. * Defines an optimization used to increase or decrease the rendering resolution
  105798. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105799. */
  105800. var HardwareScalingOptimization = /** @class */ (function (_super) {
  105801. __extends(HardwareScalingOptimization, _super);
  105802. /**
  105803. * Creates the HardwareScalingOptimization object
  105804. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  105805. * @param maximumScale defines the maximum scale to use (2 by default)
  105806. * @param step defines the step to use between two passes (0.5 by default)
  105807. */
  105808. function HardwareScalingOptimization(
  105809. /**
  105810. * Defines the priority of this optimization (0 by default which means first in the list)
  105811. */
  105812. priority,
  105813. /**
  105814. * Defines the maximum scale to use (2 by default)
  105815. */
  105816. maximumScale,
  105817. /**
  105818. * Defines the step to use between two passes (0.5 by default)
  105819. */
  105820. step) {
  105821. if (priority === void 0) { priority = 0; }
  105822. if (maximumScale === void 0) { maximumScale = 2; }
  105823. if (step === void 0) { step = 0.25; }
  105824. var _this = _super.call(this, priority) || this;
  105825. _this.priority = priority;
  105826. _this.maximumScale = maximumScale;
  105827. _this.step = step;
  105828. _this._currentScale = -1;
  105829. _this._directionOffset = 1;
  105830. return _this;
  105831. }
  105832. /**
  105833. * Gets a string describing the action executed by the current optimization
  105834. * @return description string
  105835. */
  105836. HardwareScalingOptimization.prototype.getDescription = function () {
  105837. return "Setting hardware scaling level to " + this._currentScale;
  105838. };
  105839. /**
  105840. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105841. * @param scene defines the current scene where to apply this optimization
  105842. * @param optimizer defines the current optimizer
  105843. * @returns true if everything that can be done was applied
  105844. */
  105845. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  105846. if (this._currentScale === -1) {
  105847. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  105848. if (this._currentScale > this.maximumScale) {
  105849. this._directionOffset = -1;
  105850. }
  105851. }
  105852. this._currentScale += this._directionOffset * this.step;
  105853. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  105854. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  105855. };
  105856. ;
  105857. return HardwareScalingOptimization;
  105858. }(SceneOptimization));
  105859. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  105860. /**
  105861. * Defines an optimization used to remove shadows
  105862. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105863. */
  105864. var ShadowsOptimization = /** @class */ (function (_super) {
  105865. __extends(ShadowsOptimization, _super);
  105866. function ShadowsOptimization() {
  105867. return _super !== null && _super.apply(this, arguments) || this;
  105868. }
  105869. /**
  105870. * Gets a string describing the action executed by the current optimization
  105871. * @return description string
  105872. */
  105873. ShadowsOptimization.prototype.getDescription = function () {
  105874. return "Turning shadows on/off";
  105875. };
  105876. /**
  105877. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105878. * @param scene defines the current scene where to apply this optimization
  105879. * @param optimizer defines the current optimizer
  105880. * @returns true if everything that can be done was applied
  105881. */
  105882. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  105883. scene.shadowsEnabled = optimizer.isInImprovementMode;
  105884. return true;
  105885. };
  105886. ;
  105887. return ShadowsOptimization;
  105888. }(SceneOptimization));
  105889. BABYLON.ShadowsOptimization = ShadowsOptimization;
  105890. /**
  105891. * Defines an optimization used to turn post-processes off
  105892. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105893. */
  105894. var PostProcessesOptimization = /** @class */ (function (_super) {
  105895. __extends(PostProcessesOptimization, _super);
  105896. function PostProcessesOptimization() {
  105897. return _super !== null && _super.apply(this, arguments) || this;
  105898. }
  105899. /**
  105900. * Gets a string describing the action executed by the current optimization
  105901. * @return description string
  105902. */
  105903. PostProcessesOptimization.prototype.getDescription = function () {
  105904. return "Turning post-processes on/off";
  105905. };
  105906. /**
  105907. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105908. * @param scene defines the current scene where to apply this optimization
  105909. * @param optimizer defines the current optimizer
  105910. * @returns true if everything that can be done was applied
  105911. */
  105912. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  105913. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  105914. return true;
  105915. };
  105916. ;
  105917. return PostProcessesOptimization;
  105918. }(SceneOptimization));
  105919. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  105920. /**
  105921. * Defines an optimization used to turn lens flares off
  105922. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105923. */
  105924. var LensFlaresOptimization = /** @class */ (function (_super) {
  105925. __extends(LensFlaresOptimization, _super);
  105926. function LensFlaresOptimization() {
  105927. return _super !== null && _super.apply(this, arguments) || this;
  105928. }
  105929. /**
  105930. * Gets a string describing the action executed by the current optimization
  105931. * @return description string
  105932. */
  105933. LensFlaresOptimization.prototype.getDescription = function () {
  105934. return "Turning lens flares on/off";
  105935. };
  105936. /**
  105937. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105938. * @param scene defines the current scene where to apply this optimization
  105939. * @param optimizer defines the current optimizer
  105940. * @returns true if everything that can be done was applied
  105941. */
  105942. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  105943. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  105944. return true;
  105945. };
  105946. ;
  105947. return LensFlaresOptimization;
  105948. }(SceneOptimization));
  105949. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  105950. /**
  105951. * Defines an optimization based on user defined callback.
  105952. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105953. */
  105954. var CustomOptimization = /** @class */ (function (_super) {
  105955. __extends(CustomOptimization, _super);
  105956. function CustomOptimization() {
  105957. return _super !== null && _super.apply(this, arguments) || this;
  105958. }
  105959. /**
  105960. * Gets a string describing the action executed by the current optimization
  105961. * @returns description string
  105962. */
  105963. CustomOptimization.prototype.getDescription = function () {
  105964. if (this.onGetDescription) {
  105965. return this.onGetDescription();
  105966. }
  105967. return "Running user defined callback";
  105968. };
  105969. /**
  105970. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105971. * @param scene defines the current scene where to apply this optimization
  105972. * @param optimizer defines the current optimizer
  105973. * @returns true if everything that can be done was applied
  105974. */
  105975. CustomOptimization.prototype.apply = function (scene, optimizer) {
  105976. if (this.onApply) {
  105977. return this.onApply(scene, optimizer);
  105978. }
  105979. return true;
  105980. };
  105981. ;
  105982. return CustomOptimization;
  105983. }(SceneOptimization));
  105984. BABYLON.CustomOptimization = CustomOptimization;
  105985. /**
  105986. * Defines an optimization used to turn particles off
  105987. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105988. */
  105989. var ParticlesOptimization = /** @class */ (function (_super) {
  105990. __extends(ParticlesOptimization, _super);
  105991. function ParticlesOptimization() {
  105992. return _super !== null && _super.apply(this, arguments) || this;
  105993. }
  105994. /**
  105995. * Gets a string describing the action executed by the current optimization
  105996. * @return description string
  105997. */
  105998. ParticlesOptimization.prototype.getDescription = function () {
  105999. return "Turning particles on/off";
  106000. };
  106001. /**
  106002. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  106003. * @param scene defines the current scene where to apply this optimization
  106004. * @param optimizer defines the current optimizer
  106005. * @returns true if everything that can be done was applied
  106006. */
  106007. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  106008. scene.particlesEnabled = optimizer.isInImprovementMode;
  106009. return true;
  106010. };
  106011. ;
  106012. return ParticlesOptimization;
  106013. }(SceneOptimization));
  106014. BABYLON.ParticlesOptimization = ParticlesOptimization;
  106015. /**
  106016. * Defines an optimization used to turn render targets off
  106017. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  106018. */
  106019. var RenderTargetsOptimization = /** @class */ (function (_super) {
  106020. __extends(RenderTargetsOptimization, _super);
  106021. function RenderTargetsOptimization() {
  106022. return _super !== null && _super.apply(this, arguments) || this;
  106023. }
  106024. /**
  106025. * Gets a string describing the action executed by the current optimization
  106026. * @return description string
  106027. */
  106028. RenderTargetsOptimization.prototype.getDescription = function () {
  106029. return "Turning render targets off";
  106030. };
  106031. /**
  106032. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  106033. * @param scene defines the current scene where to apply this optimization
  106034. * @param optimizer defines the current optimizer
  106035. * @returns true if everything that can be done was applied
  106036. */
  106037. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  106038. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  106039. return true;
  106040. };
  106041. ;
  106042. return RenderTargetsOptimization;
  106043. }(SceneOptimization));
  106044. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  106045. /**
  106046. * Defines an optimization used to merge meshes with compatible materials
  106047. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  106048. */
  106049. var MergeMeshesOptimization = /** @class */ (function (_super) {
  106050. __extends(MergeMeshesOptimization, _super);
  106051. function MergeMeshesOptimization() {
  106052. var _this = _super !== null && _super.apply(this, arguments) || this;
  106053. _this._canBeMerged = function (abstractMesh) {
  106054. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  106055. return false;
  106056. }
  106057. var mesh = abstractMesh;
  106058. if (mesh.isDisposed()) {
  106059. return false;
  106060. }
  106061. if (!mesh.isVisible || !mesh.isEnabled()) {
  106062. return false;
  106063. }
  106064. if (mesh.instances.length > 0) {
  106065. return false;
  106066. }
  106067. if (mesh.skeleton || mesh.hasLODLevels) {
  106068. return false;
  106069. }
  106070. return true;
  106071. };
  106072. return _this;
  106073. }
  106074. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  106075. /**
  106076. * Gets or sets a boolean which defines if optimization octree has to be updated
  106077. */
  106078. get: function () {
  106079. return MergeMeshesOptimization._UpdateSelectionTree;
  106080. },
  106081. /**
  106082. * Gets or sets a boolean which defines if optimization octree has to be updated
  106083. */
  106084. set: function (value) {
  106085. MergeMeshesOptimization._UpdateSelectionTree = value;
  106086. },
  106087. enumerable: true,
  106088. configurable: true
  106089. });
  106090. /**
  106091. * Gets a string describing the action executed by the current optimization
  106092. * @return description string
  106093. */
  106094. MergeMeshesOptimization.prototype.getDescription = function () {
  106095. return "Merging similar meshes together";
  106096. };
  106097. /**
  106098. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  106099. * @param scene defines the current scene where to apply this optimization
  106100. * @param optimizer defines the current optimizer
  106101. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  106102. * @returns true if everything that can be done was applied
  106103. */
  106104. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  106105. var globalPool = scene.meshes.slice(0);
  106106. var globalLength = globalPool.length;
  106107. for (var index = 0; index < globalLength; index++) {
  106108. var currentPool = new Array();
  106109. var current = globalPool[index];
  106110. // Checks
  106111. if (!this._canBeMerged(current)) {
  106112. continue;
  106113. }
  106114. currentPool.push(current);
  106115. // Find compatible meshes
  106116. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  106117. var otherMesh = globalPool[subIndex];
  106118. if (!this._canBeMerged(otherMesh)) {
  106119. continue;
  106120. }
  106121. if (otherMesh.material !== current.material) {
  106122. continue;
  106123. }
  106124. if (otherMesh.checkCollisions !== current.checkCollisions) {
  106125. continue;
  106126. }
  106127. currentPool.push(otherMesh);
  106128. globalLength--;
  106129. globalPool.splice(subIndex, 1);
  106130. subIndex--;
  106131. }
  106132. if (currentPool.length < 2) {
  106133. continue;
  106134. }
  106135. // Merge meshes
  106136. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  106137. }
  106138. // Call the octree system optimization if it is defined.
  106139. var sceneAsAny = scene;
  106140. if (sceneAsAny.createOrUpdateSelectionOctree) {
  106141. if (updateSelectionTree != undefined) {
  106142. if (updateSelectionTree) {
  106143. sceneAsAny.createOrUpdateSelectionOctree();
  106144. }
  106145. }
  106146. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  106147. sceneAsAny.createOrUpdateSelectionOctree();
  106148. }
  106149. }
  106150. return true;
  106151. };
  106152. ;
  106153. MergeMeshesOptimization._UpdateSelectionTree = false;
  106154. return MergeMeshesOptimization;
  106155. }(SceneOptimization));
  106156. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  106157. /**
  106158. * Defines a list of options used by SceneOptimizer
  106159. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  106160. */
  106161. var SceneOptimizerOptions = /** @class */ (function () {
  106162. /**
  106163. * Creates a new list of options used by SceneOptimizer
  106164. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  106165. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  106166. */
  106167. function SceneOptimizerOptions(
  106168. /**
  106169. * Defines the target frame rate to reach (60 by default)
  106170. */
  106171. targetFrameRate,
  106172. /**
  106173. * Defines the interval between two checkes (2000ms by default)
  106174. */
  106175. trackerDuration) {
  106176. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  106177. if (trackerDuration === void 0) { trackerDuration = 2000; }
  106178. this.targetFrameRate = targetFrameRate;
  106179. this.trackerDuration = trackerDuration;
  106180. /**
  106181. * Gets the list of optimizations to apply
  106182. */
  106183. this.optimizations = new Array();
  106184. }
  106185. /**
  106186. * Add a new optimization
  106187. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  106188. * @returns the current SceneOptimizerOptions
  106189. */
  106190. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  106191. this.optimizations.push(optimization);
  106192. return this;
  106193. };
  106194. /**
  106195. * Add a new custom optimization
  106196. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  106197. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  106198. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  106199. * @returns the current SceneOptimizerOptions
  106200. */
  106201. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  106202. if (priority === void 0) { priority = 0; }
  106203. var optimization = new CustomOptimization(priority);
  106204. optimization.onApply = onApply;
  106205. optimization.onGetDescription = onGetDescription;
  106206. this.optimizations.push(optimization);
  106207. return this;
  106208. };
  106209. /**
  106210. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  106211. * @param targetFrameRate defines the target frame rate (60 by default)
  106212. * @returns a SceneOptimizerOptions object
  106213. */
  106214. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  106215. var result = new SceneOptimizerOptions(targetFrameRate);
  106216. var priority = 0;
  106217. result.addOptimization(new MergeMeshesOptimization(priority));
  106218. result.addOptimization(new ShadowsOptimization(priority));
  106219. result.addOptimization(new LensFlaresOptimization(priority));
  106220. // Next priority
  106221. priority++;
  106222. result.addOptimization(new PostProcessesOptimization(priority));
  106223. result.addOptimization(new ParticlesOptimization(priority));
  106224. // Next priority
  106225. priority++;
  106226. result.addOptimization(new TextureOptimization(priority, 1024));
  106227. return result;
  106228. };
  106229. /**
  106230. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  106231. * @param targetFrameRate defines the target frame rate (60 by default)
  106232. * @returns a SceneOptimizerOptions object
  106233. */
  106234. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  106235. var result = new SceneOptimizerOptions(targetFrameRate);
  106236. var priority = 0;
  106237. result.addOptimization(new MergeMeshesOptimization(priority));
  106238. result.addOptimization(new ShadowsOptimization(priority));
  106239. result.addOptimization(new LensFlaresOptimization(priority));
  106240. // Next priority
  106241. priority++;
  106242. result.addOptimization(new PostProcessesOptimization(priority));
  106243. result.addOptimization(new ParticlesOptimization(priority));
  106244. // Next priority
  106245. priority++;
  106246. result.addOptimization(new TextureOptimization(priority, 512));
  106247. // Next priority
  106248. priority++;
  106249. result.addOptimization(new RenderTargetsOptimization(priority));
  106250. // Next priority
  106251. priority++;
  106252. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  106253. return result;
  106254. };
  106255. /**
  106256. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  106257. * @param targetFrameRate defines the target frame rate (60 by default)
  106258. * @returns a SceneOptimizerOptions object
  106259. */
  106260. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  106261. var result = new SceneOptimizerOptions(targetFrameRate);
  106262. var priority = 0;
  106263. result.addOptimization(new MergeMeshesOptimization(priority));
  106264. result.addOptimization(new ShadowsOptimization(priority));
  106265. result.addOptimization(new LensFlaresOptimization(priority));
  106266. // Next priority
  106267. priority++;
  106268. result.addOptimization(new PostProcessesOptimization(priority));
  106269. result.addOptimization(new ParticlesOptimization(priority));
  106270. // Next priority
  106271. priority++;
  106272. result.addOptimization(new TextureOptimization(priority, 256));
  106273. // Next priority
  106274. priority++;
  106275. result.addOptimization(new RenderTargetsOptimization(priority));
  106276. // Next priority
  106277. priority++;
  106278. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  106279. return result;
  106280. };
  106281. return SceneOptimizerOptions;
  106282. }());
  106283. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  106284. /**
  106285. * Class used to run optimizations in order to reach a target frame rate
  106286. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  106287. */
  106288. var SceneOptimizer = /** @class */ (function () {
  106289. /**
  106290. * Creates a new SceneOptimizer
  106291. * @param scene defines the scene to work on
  106292. * @param options defines the options to use with the SceneOptimizer
  106293. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  106294. * @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)
  106295. */
  106296. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  106297. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  106298. if (improvementMode === void 0) { improvementMode = false; }
  106299. var _this = this;
  106300. this._isRunning = false;
  106301. this._currentPriorityLevel = 0;
  106302. this._targetFrameRate = 60;
  106303. this._trackerDuration = 2000;
  106304. this._currentFrameRate = 0;
  106305. this._improvementMode = false;
  106306. /**
  106307. * Defines an observable called when the optimizer reaches the target frame rate
  106308. */
  106309. this.onSuccessObservable = new BABYLON.Observable();
  106310. /**
  106311. * Defines an observable called when the optimizer enables an optimization
  106312. */
  106313. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  106314. /**
  106315. * Defines an observable called when the optimizer is not able to reach the target frame rate
  106316. */
  106317. this.onFailureObservable = new BABYLON.Observable();
  106318. if (!options) {
  106319. this._options = new SceneOptimizerOptions();
  106320. }
  106321. else {
  106322. this._options = options;
  106323. }
  106324. if (this._options.targetFrameRate) {
  106325. this._targetFrameRate = this._options.targetFrameRate;
  106326. }
  106327. if (this._options.trackerDuration) {
  106328. this._trackerDuration = this._options.trackerDuration;
  106329. }
  106330. if (autoGeneratePriorities) {
  106331. var priority = 0;
  106332. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  106333. var optim = _a[_i];
  106334. optim.priority = priority++;
  106335. }
  106336. }
  106337. this._improvementMode = improvementMode;
  106338. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  106339. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  106340. _this._sceneDisposeObserver = null;
  106341. _this.dispose();
  106342. });
  106343. }
  106344. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  106345. /**
  106346. * Gets a boolean indicating if the optimizer is in improvement mode
  106347. */
  106348. get: function () {
  106349. return this._improvementMode;
  106350. },
  106351. enumerable: true,
  106352. configurable: true
  106353. });
  106354. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  106355. /**
  106356. * Gets the current priority level (0 at start)
  106357. */
  106358. get: function () {
  106359. return this._currentPriorityLevel;
  106360. },
  106361. enumerable: true,
  106362. configurable: true
  106363. });
  106364. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  106365. /**
  106366. * Gets the current frame rate checked by the SceneOptimizer
  106367. */
  106368. get: function () {
  106369. return this._currentFrameRate;
  106370. },
  106371. enumerable: true,
  106372. configurable: true
  106373. });
  106374. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  106375. /**
  106376. * Gets or sets the current target frame rate (60 by default)
  106377. */
  106378. get: function () {
  106379. return this._targetFrameRate;
  106380. },
  106381. /**
  106382. * Gets or sets the current target frame rate (60 by default)
  106383. */
  106384. set: function (value) {
  106385. this._targetFrameRate = value;
  106386. },
  106387. enumerable: true,
  106388. configurable: true
  106389. });
  106390. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  106391. /**
  106392. * Gets or sets the current interval between two checks (every 2000ms by default)
  106393. */
  106394. get: function () {
  106395. return this._trackerDuration;
  106396. },
  106397. /**
  106398. * Gets or sets the current interval between two checks (every 2000ms by default)
  106399. */
  106400. set: function (value) {
  106401. this._trackerDuration = value;
  106402. },
  106403. enumerable: true,
  106404. configurable: true
  106405. });
  106406. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  106407. /**
  106408. * Gets the list of active optimizations
  106409. */
  106410. get: function () {
  106411. return this._options.optimizations;
  106412. },
  106413. enumerable: true,
  106414. configurable: true
  106415. });
  106416. /**
  106417. * Stops the current optimizer
  106418. */
  106419. SceneOptimizer.prototype.stop = function () {
  106420. this._isRunning = false;
  106421. };
  106422. /**
  106423. * Reset the optimizer to initial step (current priority level = 0)
  106424. */
  106425. SceneOptimizer.prototype.reset = function () {
  106426. this._currentPriorityLevel = 0;
  106427. };
  106428. /**
  106429. * Start the optimizer. By default it will try to reach a specific framerate
  106430. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  106431. */
  106432. SceneOptimizer.prototype.start = function () {
  106433. var _this = this;
  106434. if (this._isRunning) {
  106435. return;
  106436. }
  106437. this._isRunning = true;
  106438. // Let's wait for the scene to be ready before running our check
  106439. this._scene.executeWhenReady(function () {
  106440. setTimeout(function () {
  106441. _this._checkCurrentState();
  106442. }, _this._trackerDuration);
  106443. });
  106444. };
  106445. SceneOptimizer.prototype._checkCurrentState = function () {
  106446. var _this = this;
  106447. if (!this._isRunning) {
  106448. return;
  106449. }
  106450. var scene = this._scene;
  106451. var options = this._options;
  106452. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  106453. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  106454. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  106455. this._isRunning = false;
  106456. this.onSuccessObservable.notifyObservers(this);
  106457. return;
  106458. }
  106459. // Apply current level of optimizations
  106460. var allDone = true;
  106461. var noOptimizationApplied = true;
  106462. for (var index = 0; index < options.optimizations.length; index++) {
  106463. var optimization = options.optimizations[index];
  106464. if (optimization.priority === this._currentPriorityLevel) {
  106465. noOptimizationApplied = false;
  106466. allDone = allDone && optimization.apply(scene, this);
  106467. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  106468. }
  106469. }
  106470. // If no optimization was applied, this is a failure :(
  106471. if (noOptimizationApplied) {
  106472. this._isRunning = false;
  106473. this.onFailureObservable.notifyObservers(this);
  106474. return;
  106475. }
  106476. // If all optimizations were done, move to next level
  106477. if (allDone) {
  106478. this._currentPriorityLevel++;
  106479. }
  106480. // Let's the system running for a specific amount of time before checking FPS
  106481. scene.executeWhenReady(function () {
  106482. setTimeout(function () {
  106483. _this._checkCurrentState();
  106484. }, _this._trackerDuration);
  106485. });
  106486. };
  106487. /**
  106488. * Release all resources
  106489. */
  106490. SceneOptimizer.prototype.dispose = function () {
  106491. this.stop();
  106492. this.onSuccessObservable.clear();
  106493. this.onFailureObservable.clear();
  106494. this.onNewOptimizationAppliedObservable.clear();
  106495. if (this._sceneDisposeObserver) {
  106496. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  106497. }
  106498. };
  106499. /**
  106500. * Helper function to create a SceneOptimizer with one single line of code
  106501. * @param scene defines the scene to work on
  106502. * @param options defines the options to use with the SceneOptimizer
  106503. * @param onSuccess defines a callback to call on success
  106504. * @param onFailure defines a callback to call on failure
  106505. * @returns the new SceneOptimizer object
  106506. */
  106507. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  106508. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  106509. if (onSuccess) {
  106510. optimizer.onSuccessObservable.add(function () {
  106511. onSuccess();
  106512. });
  106513. }
  106514. if (onFailure) {
  106515. optimizer.onFailureObservable.add(function () {
  106516. onFailure();
  106517. });
  106518. }
  106519. optimizer.start();
  106520. return optimizer;
  106521. };
  106522. return SceneOptimizer;
  106523. }());
  106524. BABYLON.SceneOptimizer = SceneOptimizer;
  106525. })(BABYLON || (BABYLON = {}));
  106526. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  106527. var BABYLON;
  106528. (function (BABYLON) {
  106529. /**
  106530. * Gets the outline renderer associated with the scene
  106531. * @returns a OutlineRenderer
  106532. */
  106533. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  106534. if (!this._outlineRenderer) {
  106535. this._outlineRenderer = new OutlineRenderer(this);
  106536. }
  106537. return this._outlineRenderer;
  106538. };
  106539. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  106540. get: function () {
  106541. return this._renderOutline;
  106542. },
  106543. set: function (value) {
  106544. if (value) {
  106545. // Lazy Load the component.
  106546. this.getScene().getOutlineRenderer();
  106547. }
  106548. this._renderOutline = value;
  106549. },
  106550. enumerable: true,
  106551. configurable: true
  106552. });
  106553. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  106554. get: function () {
  106555. return this._renderOverlay;
  106556. },
  106557. set: function (value) {
  106558. if (value) {
  106559. // Lazy Load the component.
  106560. this.getScene().getOutlineRenderer();
  106561. }
  106562. this._renderOverlay = value;
  106563. },
  106564. enumerable: true,
  106565. configurable: true
  106566. });
  106567. /**
  106568. * This class is responsible to draw bothe outline/overlay of meshes.
  106569. * It should not be used directly but through the available method on mesh.
  106570. */
  106571. var OutlineRenderer = /** @class */ (function () {
  106572. /**
  106573. * Instantiates a new outline renderer. (There could be only one per scene).
  106574. * @param scene Defines the scene it belongs to
  106575. */
  106576. function OutlineRenderer(scene) {
  106577. /**
  106578. * The name of the component. Each component must have a unique name.
  106579. */
  106580. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  106581. /**
  106582. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  106583. */
  106584. this.zOffset = 1;
  106585. this.scene = scene;
  106586. this._engine = scene.getEngine();
  106587. this.scene._addComponent(this);
  106588. }
  106589. /**
  106590. * Register the component to one instance of a scene.
  106591. */
  106592. OutlineRenderer.prototype.register = function () {
  106593. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  106594. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  106595. };
  106596. /**
  106597. * Rebuilds the elements related to this component in case of
  106598. * context lost for instance.
  106599. */
  106600. OutlineRenderer.prototype.rebuild = function () {
  106601. // Nothing to do here.
  106602. };
  106603. /**
  106604. * Disposes the component and the associated ressources.
  106605. */
  106606. OutlineRenderer.prototype.dispose = function () {
  106607. // Nothing to do here.
  106608. };
  106609. /**
  106610. * Renders the outline in the canvas.
  106611. * @param subMesh Defines the sumesh to render
  106612. * @param batch Defines the batch of meshes in case of instances
  106613. * @param useOverlay Defines if the rendering is for the overlay or the outline
  106614. */
  106615. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  106616. var _this = this;
  106617. if (useOverlay === void 0) { useOverlay = false; }
  106618. var scene = this.scene;
  106619. var engine = scene.getEngine();
  106620. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  106621. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  106622. return;
  106623. }
  106624. var mesh = subMesh.getRenderingMesh();
  106625. var material = subMesh.getMaterial();
  106626. if (!material || !scene.activeCamera) {
  106627. return;
  106628. }
  106629. engine.enableEffect(this._effect);
  106630. // Logarithmic depth
  106631. if (material.useLogarithmicDepth) {
  106632. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  106633. }
  106634. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  106635. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  106636. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  106637. // Bones
  106638. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  106639. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  106640. }
  106641. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  106642. // Alpha test
  106643. if (material && material.needAlphaTesting()) {
  106644. var alphaTexture = material.getAlphaTestTexture();
  106645. if (alphaTexture) {
  106646. this._effect.setTexture("diffuseSampler", alphaTexture);
  106647. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  106648. }
  106649. }
  106650. engine.setZOffset(-this.zOffset);
  106651. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  106652. engine.setZOffset(0);
  106653. };
  106654. /**
  106655. * Returns whether or not the outline renderer is ready for a given submesh.
  106656. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  106657. * @param subMesh Defines the submesh to check readyness for
  106658. * @param useInstances Defines wheter wee are trying to render instances or not
  106659. * @returns true if ready otherwise false
  106660. */
  106661. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  106662. var defines = [];
  106663. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  106664. var mesh = subMesh.getMesh();
  106665. var material = subMesh.getMaterial();
  106666. if (material) {
  106667. // Alpha test
  106668. if (material.needAlphaTesting()) {
  106669. defines.push("#define ALPHATEST");
  106670. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  106671. attribs.push(BABYLON.VertexBuffer.UVKind);
  106672. defines.push("#define UV1");
  106673. }
  106674. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  106675. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  106676. defines.push("#define UV2");
  106677. }
  106678. }
  106679. //Logarithmic depth
  106680. if (material.useLogarithmicDepth) {
  106681. defines.push("#define LOGARITHMICDEPTH");
  106682. }
  106683. }
  106684. // Bones
  106685. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  106686. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  106687. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  106688. if (mesh.numBoneInfluencers > 4) {
  106689. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  106690. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  106691. }
  106692. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  106693. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  106694. }
  106695. else {
  106696. defines.push("#define NUM_BONE_INFLUENCERS 0");
  106697. }
  106698. // Instances
  106699. if (useInstances) {
  106700. defines.push("#define INSTANCES");
  106701. attribs.push("world0");
  106702. attribs.push("world1");
  106703. attribs.push("world2");
  106704. attribs.push("world3");
  106705. }
  106706. // Get correct effect
  106707. var join = defines.join("\n");
  106708. if (this._cachedDefines !== join) {
  106709. this._cachedDefines = join;
  106710. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  106711. }
  106712. return this._effect.isReady();
  106713. };
  106714. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  106715. // Outline - step 1
  106716. this._savedDepthWrite = this._engine.getDepthWrite();
  106717. if (mesh.renderOutline) {
  106718. this._engine.setDepthWrite(false);
  106719. this.render(subMesh, batch);
  106720. this._engine.setDepthWrite(this._savedDepthWrite);
  106721. }
  106722. };
  106723. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  106724. // Outline - step 2
  106725. if (mesh.renderOutline && this._savedDepthWrite) {
  106726. this._engine.setDepthWrite(true);
  106727. this._engine.setColorWrite(false);
  106728. this.render(subMesh, batch);
  106729. this._engine.setColorWrite(true);
  106730. }
  106731. // Overlay
  106732. if (mesh.renderOverlay) {
  106733. var currentMode = this._engine.getAlphaMode();
  106734. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  106735. this.render(subMesh, batch, true);
  106736. this._engine.setAlphaMode(currentMode);
  106737. }
  106738. };
  106739. return OutlineRenderer;
  106740. }());
  106741. BABYLON.OutlineRenderer = OutlineRenderer;
  106742. })(BABYLON || (BABYLON = {}));
  106743. //# sourceMappingURL=babylon.outlineRenderer.js.map
  106744. var BABYLON;
  106745. (function (BABYLON) {
  106746. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  106747. if (this._edgesRenderer) {
  106748. this._edgesRenderer.dispose();
  106749. this._edgesRenderer = null;
  106750. }
  106751. return this;
  106752. };
  106753. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  106754. if (epsilon === void 0) { epsilon = 0.95; }
  106755. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  106756. this.disableEdgesRendering();
  106757. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  106758. return this;
  106759. };
  106760. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  106761. get: function () {
  106762. return this._edgesRenderer;
  106763. },
  106764. enumerable: true,
  106765. configurable: true
  106766. });
  106767. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  106768. if (epsilon === void 0) { epsilon = 0.95; }
  106769. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  106770. this.disableEdgesRendering();
  106771. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  106772. return this;
  106773. };
  106774. /**
  106775. * FaceAdjacencies Helper class to generate edges
  106776. */
  106777. var FaceAdjacencies = /** @class */ (function () {
  106778. function FaceAdjacencies() {
  106779. this.edges = new Array();
  106780. this.edgesConnectedCount = 0;
  106781. }
  106782. return FaceAdjacencies;
  106783. }());
  106784. /**
  106785. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  106786. */
  106787. var EdgesRenderer = /** @class */ (function () {
  106788. /**
  106789. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  106790. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  106791. * @param source Mesh used to create edges
  106792. * @param epsilon sum of angles in adjacency to check for edge
  106793. * @param checkVerticesInsteadOfIndices
  106794. * @param generateEdgesLines - should generate Lines or only prepare resources.
  106795. */
  106796. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  106797. if (epsilon === void 0) { epsilon = 0.95; }
  106798. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  106799. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  106800. var _this = this;
  106801. /**
  106802. * Define the size of the edges with an orthographic camera
  106803. */
  106804. this.edgesWidthScalerForOrthographic = 1000.0;
  106805. /**
  106806. * Define the size of the edges with a perspective camera
  106807. */
  106808. this.edgesWidthScalerForPerspective = 50.0;
  106809. this._linesPositions = new Array();
  106810. this._linesNormals = new Array();
  106811. this._linesIndices = new Array();
  106812. this._buffers = {};
  106813. this._checkVerticesInsteadOfIndices = false;
  106814. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  106815. this.isEnabled = true;
  106816. this._source = source;
  106817. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  106818. this._epsilon = epsilon;
  106819. this._prepareRessources();
  106820. if (generateEdgesLines) {
  106821. this._generateEdgesLines();
  106822. }
  106823. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  106824. _this._rebuild();
  106825. });
  106826. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  106827. _this.dispose();
  106828. });
  106829. }
  106830. EdgesRenderer.prototype._prepareRessources = function () {
  106831. if (this._lineShader) {
  106832. return;
  106833. }
  106834. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  106835. attributes: ["position", "normal"],
  106836. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  106837. });
  106838. this._lineShader.disableDepthWrite = true;
  106839. this._lineShader.backFaceCulling = false;
  106840. };
  106841. /** @hidden */
  106842. EdgesRenderer.prototype._rebuild = function () {
  106843. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  106844. if (buffer) {
  106845. buffer._rebuild();
  106846. }
  106847. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  106848. if (buffer) {
  106849. buffer._rebuild();
  106850. }
  106851. var scene = this._source.getScene();
  106852. var engine = scene.getEngine();
  106853. this._ib = engine.createIndexBuffer(this._linesIndices);
  106854. };
  106855. /**
  106856. * Releases the required resources for the edges renderer
  106857. */
  106858. EdgesRenderer.prototype.dispose = function () {
  106859. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  106860. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  106861. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  106862. if (buffer) {
  106863. buffer.dispose();
  106864. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  106865. }
  106866. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  106867. if (buffer) {
  106868. buffer.dispose();
  106869. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  106870. }
  106871. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  106872. this._lineShader.dispose();
  106873. };
  106874. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  106875. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  106876. return 0;
  106877. }
  106878. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  106879. return 1;
  106880. }
  106881. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  106882. return 2;
  106883. }
  106884. return -1;
  106885. };
  106886. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  106887. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  106888. return 0;
  106889. }
  106890. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  106891. return 1;
  106892. }
  106893. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  106894. return 2;
  106895. }
  106896. return -1;
  106897. };
  106898. /**
  106899. * Checks if the pair of p0 and p1 is en edge
  106900. * @param faceIndex
  106901. * @param edge
  106902. * @param faceNormals
  106903. * @param p0
  106904. * @param p1
  106905. * @private
  106906. */
  106907. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  106908. var needToCreateLine;
  106909. if (edge === undefined) {
  106910. needToCreateLine = true;
  106911. }
  106912. else {
  106913. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  106914. needToCreateLine = dotProduct < this._epsilon;
  106915. }
  106916. if (needToCreateLine) {
  106917. var offset = this._linesPositions.length / 3;
  106918. var normal = p0.subtract(p1);
  106919. normal.normalize();
  106920. // Positions
  106921. this._linesPositions.push(p0.x);
  106922. this._linesPositions.push(p0.y);
  106923. this._linesPositions.push(p0.z);
  106924. this._linesPositions.push(p0.x);
  106925. this._linesPositions.push(p0.y);
  106926. this._linesPositions.push(p0.z);
  106927. this._linesPositions.push(p1.x);
  106928. this._linesPositions.push(p1.y);
  106929. this._linesPositions.push(p1.z);
  106930. this._linesPositions.push(p1.x);
  106931. this._linesPositions.push(p1.y);
  106932. this._linesPositions.push(p1.z);
  106933. // Normals
  106934. this._linesNormals.push(p1.x);
  106935. this._linesNormals.push(p1.y);
  106936. this._linesNormals.push(p1.z);
  106937. this._linesNormals.push(-1);
  106938. this._linesNormals.push(p1.x);
  106939. this._linesNormals.push(p1.y);
  106940. this._linesNormals.push(p1.z);
  106941. this._linesNormals.push(1);
  106942. this._linesNormals.push(p0.x);
  106943. this._linesNormals.push(p0.y);
  106944. this._linesNormals.push(p0.z);
  106945. this._linesNormals.push(-1);
  106946. this._linesNormals.push(p0.x);
  106947. this._linesNormals.push(p0.y);
  106948. this._linesNormals.push(p0.z);
  106949. this._linesNormals.push(1);
  106950. // Indices
  106951. this._linesIndices.push(offset);
  106952. this._linesIndices.push(offset + 1);
  106953. this._linesIndices.push(offset + 2);
  106954. this._linesIndices.push(offset);
  106955. this._linesIndices.push(offset + 2);
  106956. this._linesIndices.push(offset + 3);
  106957. }
  106958. };
  106959. /**
  106960. * Generates lines edges from adjacencjes
  106961. * @private
  106962. */
  106963. EdgesRenderer.prototype._generateEdgesLines = function () {
  106964. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  106965. var indices = this._source.getIndices();
  106966. if (!indices || !positions) {
  106967. return;
  106968. }
  106969. // First let's find adjacencies
  106970. var adjacencies = new Array();
  106971. var faceNormals = new Array();
  106972. var index;
  106973. var faceAdjacencies;
  106974. // Prepare faces
  106975. for (index = 0; index < indices.length; index += 3) {
  106976. faceAdjacencies = new FaceAdjacencies();
  106977. var p0Index = indices[index];
  106978. var p1Index = indices[index + 1];
  106979. var p2Index = indices[index + 2];
  106980. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  106981. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  106982. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  106983. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  106984. faceNormal.normalize();
  106985. faceNormals.push(faceNormal);
  106986. adjacencies.push(faceAdjacencies);
  106987. }
  106988. // Scan
  106989. for (index = 0; index < adjacencies.length; index++) {
  106990. faceAdjacencies = adjacencies[index];
  106991. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  106992. var otherFaceAdjacencies = adjacencies[otherIndex];
  106993. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  106994. break;
  106995. }
  106996. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  106997. continue;
  106998. }
  106999. var otherP0 = indices[otherIndex * 3];
  107000. var otherP1 = indices[otherIndex * 3 + 1];
  107001. var otherP2 = indices[otherIndex * 3 + 2];
  107002. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  107003. var otherEdgeIndex = 0;
  107004. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  107005. continue;
  107006. }
  107007. switch (edgeIndex) {
  107008. case 0:
  107009. if (this._checkVerticesInsteadOfIndices) {
  107010. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  107011. }
  107012. else {
  107013. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  107014. }
  107015. break;
  107016. case 1:
  107017. if (this._checkVerticesInsteadOfIndices) {
  107018. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  107019. }
  107020. else {
  107021. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  107022. }
  107023. break;
  107024. case 2:
  107025. if (this._checkVerticesInsteadOfIndices) {
  107026. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  107027. }
  107028. else {
  107029. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  107030. }
  107031. break;
  107032. }
  107033. if (otherEdgeIndex === -1) {
  107034. continue;
  107035. }
  107036. faceAdjacencies.edges[edgeIndex] = otherIndex;
  107037. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  107038. faceAdjacencies.edgesConnectedCount++;
  107039. otherFaceAdjacencies.edgesConnectedCount++;
  107040. if (faceAdjacencies.edgesConnectedCount === 3) {
  107041. break;
  107042. }
  107043. }
  107044. }
  107045. }
  107046. // Create lines
  107047. for (index = 0; index < adjacencies.length; index++) {
  107048. // 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
  107049. var current = adjacencies[index];
  107050. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  107051. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  107052. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  107053. }
  107054. // Merge into a single mesh
  107055. var engine = this._source.getScene().getEngine();
  107056. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  107057. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  107058. this._ib = engine.createIndexBuffer(this._linesIndices);
  107059. this._indicesCount = this._linesIndices.length;
  107060. };
  107061. /**
  107062. * Checks wether or not the edges renderer is ready to render.
  107063. * @return true if ready, otherwise false.
  107064. */
  107065. EdgesRenderer.prototype.isReady = function () {
  107066. return this._lineShader.isReady();
  107067. };
  107068. /**
  107069. * Renders the edges of the attached mesh,
  107070. */
  107071. EdgesRenderer.prototype.render = function () {
  107072. var scene = this._source.getScene();
  107073. if (!this.isReady() || !scene.activeCamera) {
  107074. return;
  107075. }
  107076. var engine = scene.getEngine();
  107077. this._lineShader._preBind();
  107078. if (this._source.edgesColor.a !== 1) {
  107079. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  107080. }
  107081. else {
  107082. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  107083. }
  107084. // VBOs
  107085. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  107086. scene.resetCachedMaterial();
  107087. this._lineShader.setColor4("color", this._source.edgesColor);
  107088. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  107089. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  107090. }
  107091. else {
  107092. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  107093. }
  107094. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  107095. this._lineShader.bind(this._source.getWorldMatrix());
  107096. // Draw order
  107097. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  107098. this._lineShader.unbind();
  107099. };
  107100. return EdgesRenderer;
  107101. }());
  107102. BABYLON.EdgesRenderer = EdgesRenderer;
  107103. })(BABYLON || (BABYLON = {}));
  107104. //# sourceMappingURL=babylon.edgesRenderer.js.map
  107105. var BABYLON;
  107106. (function (BABYLON) {
  107107. /**
  107108. * FaceAdjacencies Helper class to generate edges
  107109. */
  107110. var FaceAdjacencies = /** @class */ (function () {
  107111. function FaceAdjacencies() {
  107112. this.edges = new Array();
  107113. this.edgesConnectedCount = 0;
  107114. }
  107115. return FaceAdjacencies;
  107116. }());
  107117. /**
  107118. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  107119. */
  107120. var LineEdgesRenderer = /** @class */ (function (_super) {
  107121. __extends(LineEdgesRenderer, _super);
  107122. /**
  107123. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  107124. * @param source LineMesh used to generate edges
  107125. * @param epsilon not important (specified angle for edge detection)
  107126. * @param checkVerticesInsteadOfIndices not important for LineMesh
  107127. */
  107128. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  107129. if (epsilon === void 0) { epsilon = 0.95; }
  107130. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  107131. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  107132. _this._generateEdgesLines();
  107133. return _this;
  107134. }
  107135. /**
  107136. * Always create the edge since its a line so only important things are p0 and p1
  107137. * @param faceIndex not important for LineMesh
  107138. * @param edge not important for LineMesh
  107139. * @param faceNormals not important for LineMesh
  107140. * @param p0 beginnig of line
  107141. * @param p1 end of line
  107142. */
  107143. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  107144. var offset = this._linesPositions.length / 3;
  107145. var normal = p0.subtract(p1);
  107146. normal.normalize();
  107147. // Positions
  107148. this._linesPositions.push(p0.x);
  107149. this._linesPositions.push(p0.y);
  107150. this._linesPositions.push(p0.z);
  107151. this._linesPositions.push(p0.x);
  107152. this._linesPositions.push(p0.y);
  107153. this._linesPositions.push(p0.z);
  107154. this._linesPositions.push(p1.x);
  107155. this._linesPositions.push(p1.y);
  107156. this._linesPositions.push(p1.z);
  107157. this._linesPositions.push(p1.x);
  107158. this._linesPositions.push(p1.y);
  107159. this._linesPositions.push(p1.z);
  107160. // Normals
  107161. this._linesNormals.push(p1.x);
  107162. this._linesNormals.push(p1.y);
  107163. this._linesNormals.push(p1.z);
  107164. this._linesNormals.push(-1);
  107165. this._linesNormals.push(p1.x);
  107166. this._linesNormals.push(p1.y);
  107167. this._linesNormals.push(p1.z);
  107168. this._linesNormals.push(1);
  107169. this._linesNormals.push(p0.x);
  107170. this._linesNormals.push(p0.y);
  107171. this._linesNormals.push(p0.z);
  107172. this._linesNormals.push(-1);
  107173. this._linesNormals.push(p0.x);
  107174. this._linesNormals.push(p0.y);
  107175. this._linesNormals.push(p0.z);
  107176. this._linesNormals.push(1);
  107177. // Indices
  107178. this._linesIndices.push(offset);
  107179. this._linesIndices.push(offset + 1);
  107180. this._linesIndices.push(offset + 2);
  107181. this._linesIndices.push(offset);
  107182. this._linesIndices.push(offset + 2);
  107183. this._linesIndices.push(offset + 3);
  107184. };
  107185. /**
  107186. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  107187. */
  107188. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  107189. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  107190. var indices = this._source.getIndices();
  107191. if (!indices || !positions) {
  107192. return;
  107193. }
  107194. // First let's find adjacencies
  107195. var adjacencies = new Array();
  107196. var faceNormals = new Array();
  107197. var index;
  107198. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  107199. var currentAdjecancy = new FaceAdjacencies();
  107200. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  107201. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  107202. adjacencies.push(currentAdjecancy);
  107203. }
  107204. // Create lines
  107205. for (index = 0; index < adjacencies.length; index++) {
  107206. // 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
  107207. var current = adjacencies[index];
  107208. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  107209. }
  107210. // Merge into a single mesh
  107211. var engine = this._source.getScene().getEngine();
  107212. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  107213. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  107214. this._ib = engine.createIndexBuffer(this._linesIndices);
  107215. this._indicesCount = this._linesIndices.length;
  107216. };
  107217. return LineEdgesRenderer;
  107218. }(BABYLON.EdgesRenderer));
  107219. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  107220. })(BABYLON || (BABYLON = {}));
  107221. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  107222. var BABYLON;
  107223. (function (BABYLON) {
  107224. // Adds the parser to the scene parsers.
  107225. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  107226. if (parsedData.effectLayers) {
  107227. if (!container.effectLayers) {
  107228. container.effectLayers = new Array();
  107229. }
  107230. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  107231. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  107232. container.effectLayers.push(effectLayer);
  107233. }
  107234. }
  107235. });
  107236. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  107237. var index = this.effectLayers.indexOf(toRemove);
  107238. if (index !== -1) {
  107239. this.effectLayers.splice(index, 1);
  107240. }
  107241. return index;
  107242. };
  107243. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  107244. this.effectLayers.push(newEffectLayer);
  107245. };
  107246. /**
  107247. * Defines the layer scene component responsible to manage any effect layers
  107248. * in a given scene.
  107249. */
  107250. var EffectLayerSceneComponent = /** @class */ (function () {
  107251. /**
  107252. * Creates a new instance of the component for the given scene
  107253. * @param scene Defines the scene to register the component in
  107254. */
  107255. function EffectLayerSceneComponent(scene) {
  107256. /**
  107257. * The component name helpfull to identify the component in the list of scene components.
  107258. */
  107259. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  107260. this._renderEffects = false;
  107261. this._needStencil = false;
  107262. this._previousStencilState = false;
  107263. this.scene = scene;
  107264. this._engine = scene.getEngine();
  107265. scene.effectLayers = new Array();
  107266. }
  107267. /**
  107268. * Registers the component in a given scene
  107269. */
  107270. EffectLayerSceneComponent.prototype.register = function () {
  107271. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  107272. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  107273. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  107274. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  107275. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  107276. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  107277. };
  107278. /**
  107279. * Rebuilds the elements related to this component in case of
  107280. * context lost for instance.
  107281. */
  107282. EffectLayerSceneComponent.prototype.rebuild = function () {
  107283. var layers = this.scene.effectLayers;
  107284. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  107285. var effectLayer = layers_1[_i];
  107286. effectLayer._rebuild();
  107287. }
  107288. };
  107289. /**
  107290. * Serializes the component data to the specified json object
  107291. * @param serializationObject The object to serialize to
  107292. */
  107293. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  107294. // Effect layers
  107295. serializationObject.effectLayers = [];
  107296. var layers = this.scene.effectLayers;
  107297. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  107298. var effectLayer = layers_2[_i];
  107299. if (effectLayer.serialize) {
  107300. serializationObject.effectLayers.push(effectLayer.serialize());
  107301. }
  107302. }
  107303. };
  107304. /**
  107305. * Adds all the element from the container to the scene
  107306. * @param container the container holding the elements
  107307. */
  107308. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  107309. var _this = this;
  107310. if (!container.effectLayers) {
  107311. return;
  107312. }
  107313. container.effectLayers.forEach(function (o) {
  107314. _this.scene.addEffectLayer(o);
  107315. });
  107316. };
  107317. /**
  107318. * Removes all the elements in the container from the scene
  107319. * @param container contains the elements to remove
  107320. */
  107321. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  107322. var _this = this;
  107323. if (!container.effectLayers) {
  107324. return;
  107325. }
  107326. container.effectLayers.forEach(function (o) {
  107327. _this.scene.removeEffectLayer(o);
  107328. });
  107329. };
  107330. /**
  107331. * Disposes the component and the associated ressources.
  107332. */
  107333. EffectLayerSceneComponent.prototype.dispose = function () {
  107334. var layers = this.scene.effectLayers;
  107335. while (layers.length) {
  107336. layers[0].dispose();
  107337. }
  107338. };
  107339. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  107340. var layers = this.scene.effectLayers;
  107341. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  107342. var layer = layers_3[_i];
  107343. if (!layer.hasMesh(mesh)) {
  107344. continue;
  107345. }
  107346. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  107347. var subMesh = _b[_a];
  107348. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  107349. return false;
  107350. }
  107351. }
  107352. }
  107353. return true;
  107354. };
  107355. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  107356. this._renderEffects = false;
  107357. this._needStencil = false;
  107358. var layers = this.scene.effectLayers;
  107359. if (layers && layers.length > 0) {
  107360. this._previousStencilState = this._engine.getStencilBuffer();
  107361. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  107362. var effectLayer = layers_4[_i];
  107363. if (effectLayer.shouldRender() &&
  107364. (!effectLayer.camera ||
  107365. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  107366. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  107367. this._renderEffects = true;
  107368. this._needStencil = this._needStencil || effectLayer.needStencil();
  107369. var renderTarget = effectLayer._mainTexture;
  107370. if (renderTarget._shouldRender()) {
  107371. this.scene.incrementRenderId();
  107372. renderTarget.render(false, false);
  107373. }
  107374. }
  107375. }
  107376. this.scene.incrementRenderId();
  107377. }
  107378. };
  107379. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  107380. // Activate effect Layer stencil
  107381. if (this._needStencil) {
  107382. this._engine.setStencilBuffer(true);
  107383. }
  107384. };
  107385. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  107386. // Restore effect Layer stencil
  107387. if (this._needStencil) {
  107388. this._engine.setStencilBuffer(this._previousStencilState);
  107389. }
  107390. };
  107391. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  107392. if (this._renderEffects) {
  107393. this._engine.setDepthBuffer(false);
  107394. var layers = this.scene.effectLayers;
  107395. for (var i = 0; i < layers.length; i++) {
  107396. var effectLayer = layers[i];
  107397. if (effectLayer.renderingGroupId === renderingGroupId) {
  107398. if (effectLayer.shouldRender()) {
  107399. effectLayer.render();
  107400. }
  107401. }
  107402. }
  107403. this._engine.setDepthBuffer(true);
  107404. }
  107405. };
  107406. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  107407. if (this._renderEffects) {
  107408. this._draw(-1);
  107409. }
  107410. };
  107411. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  107412. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  107413. this._draw(index);
  107414. }
  107415. };
  107416. return EffectLayerSceneComponent;
  107417. }());
  107418. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  107419. })(BABYLON || (BABYLON = {}));
  107420. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  107421. var __assign = (this && this.__assign) || function () {
  107422. __assign = Object.assign || function(t) {
  107423. for (var s, i = 1, n = arguments.length; i < n; i++) {
  107424. s = arguments[i];
  107425. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  107426. t[p] = s[p];
  107427. }
  107428. return t;
  107429. };
  107430. return __assign.apply(this, arguments);
  107431. };
  107432. var BABYLON;
  107433. (function (BABYLON) {
  107434. /**
  107435. * The effect layer Helps adding post process effect blended with the main pass.
  107436. *
  107437. * This can be for instance use to generate glow or higlight effects on the scene.
  107438. *
  107439. * The effect layer class can not be used directly and is intented to inherited from to be
  107440. * customized per effects.
  107441. */
  107442. var EffectLayer = /** @class */ (function () {
  107443. /**
  107444. * Instantiates a new effect Layer and references it in the scene.
  107445. * @param name The name of the layer
  107446. * @param scene The scene to use the layer in
  107447. */
  107448. function EffectLayer(
  107449. /** The Friendly of the effect in the scene */
  107450. name, scene) {
  107451. this._vertexBuffers = {};
  107452. this._maxSize = 0;
  107453. this._mainTextureDesiredSize = { width: 0, height: 0 };
  107454. this._shouldRender = true;
  107455. this._postProcesses = [];
  107456. this._textures = [];
  107457. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  107458. /**
  107459. * The clear color of the texture used to generate the glow map.
  107460. */
  107461. this.neutralColor = new BABYLON.Color4();
  107462. /**
  107463. * Specifies wether the highlight layer is enabled or not.
  107464. */
  107465. this.isEnabled = true;
  107466. /**
  107467. * An event triggered when the effect layer has been disposed.
  107468. */
  107469. this.onDisposeObservable = new BABYLON.Observable();
  107470. /**
  107471. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  107472. */
  107473. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  107474. /**
  107475. * An event triggered when the generated texture is being merged in the scene.
  107476. */
  107477. this.onBeforeComposeObservable = new BABYLON.Observable();
  107478. /**
  107479. * An event triggered when the generated texture has been merged in the scene.
  107480. */
  107481. this.onAfterComposeObservable = new BABYLON.Observable();
  107482. /**
  107483. * An event triggered when the efffect layer changes its size.
  107484. */
  107485. this.onSizeChangedObservable = new BABYLON.Observable();
  107486. this.name = name;
  107487. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  107488. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  107489. if (!component) {
  107490. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  107491. this._scene._addComponent(component);
  107492. }
  107493. this._engine = this._scene.getEngine();
  107494. this._maxSize = this._engine.getCaps().maxTextureSize;
  107495. this._scene.effectLayers.push(this);
  107496. // Generate Buffers
  107497. this._generateIndexBuffer();
  107498. this._genrateVertexBuffer();
  107499. }
  107500. Object.defineProperty(EffectLayer.prototype, "camera", {
  107501. /**
  107502. * Gets the camera attached to the layer.
  107503. */
  107504. get: function () {
  107505. return this._effectLayerOptions.camera;
  107506. },
  107507. enumerable: true,
  107508. configurable: true
  107509. });
  107510. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  107511. /**
  107512. * Gets the rendering group id the layer should render in.
  107513. */
  107514. get: function () {
  107515. return this._effectLayerOptions.renderingGroupId;
  107516. },
  107517. enumerable: true,
  107518. configurable: true
  107519. });
  107520. /**
  107521. * Initializes the effect layer with the required options.
  107522. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  107523. */
  107524. EffectLayer.prototype._init = function (options) {
  107525. // Adapt options
  107526. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  107527. this._setMainTextureSize();
  107528. this._createMainTexture();
  107529. this._createTextureAndPostProcesses();
  107530. this._mergeEffect = this._createMergeEffect();
  107531. };
  107532. /**
  107533. * Generates the index buffer of the full screen quad blending to the main canvas.
  107534. */
  107535. EffectLayer.prototype._generateIndexBuffer = function () {
  107536. // Indices
  107537. var indices = [];
  107538. indices.push(0);
  107539. indices.push(1);
  107540. indices.push(2);
  107541. indices.push(0);
  107542. indices.push(2);
  107543. indices.push(3);
  107544. this._indexBuffer = this._engine.createIndexBuffer(indices);
  107545. };
  107546. /**
  107547. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  107548. */
  107549. EffectLayer.prototype._genrateVertexBuffer = function () {
  107550. // VBO
  107551. var vertices = [];
  107552. vertices.push(1, 1);
  107553. vertices.push(-1, 1);
  107554. vertices.push(-1, -1);
  107555. vertices.push(1, -1);
  107556. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  107557. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  107558. };
  107559. /**
  107560. * Sets the main texture desired size which is the closest power of two
  107561. * of the engine canvas size.
  107562. */
  107563. EffectLayer.prototype._setMainTextureSize = function () {
  107564. if (this._effectLayerOptions.mainTextureFixedSize) {
  107565. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  107566. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  107567. }
  107568. else {
  107569. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  107570. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  107571. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  107572. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  107573. }
  107574. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  107575. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  107576. };
  107577. /**
  107578. * Creates the main texture for the effect layer.
  107579. */
  107580. EffectLayer.prototype._createMainTexture = function () {
  107581. var _this = this;
  107582. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  107583. width: this._mainTextureDesiredSize.width,
  107584. height: this._mainTextureDesiredSize.height
  107585. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  107586. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  107587. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107588. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107589. this._mainTexture.anisotropicFilteringLevel = 1;
  107590. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  107591. this._mainTexture.renderParticles = false;
  107592. this._mainTexture.renderList = null;
  107593. this._mainTexture.ignoreCameraViewport = true;
  107594. // Custom render function
  107595. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  107596. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  107597. var index;
  107598. var engine = _this._scene.getEngine();
  107599. if (depthOnlySubMeshes.length) {
  107600. engine.setColorWrite(false);
  107601. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  107602. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  107603. }
  107604. engine.setColorWrite(true);
  107605. }
  107606. for (index = 0; index < opaqueSubMeshes.length; index++) {
  107607. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  107608. }
  107609. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  107610. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  107611. }
  107612. for (index = 0; index < transparentSubMeshes.length; index++) {
  107613. _this._renderSubMesh(transparentSubMeshes.data[index]);
  107614. }
  107615. };
  107616. this._mainTexture.onClearObservable.add(function (engine) {
  107617. engine.clear(_this.neutralColor, true, true, true);
  107618. });
  107619. };
  107620. /**
  107621. * Checks for the readiness of the element composing the layer.
  107622. * @param subMesh the mesh to check for
  107623. * @param useInstances specify wether or not to use instances to render the mesh
  107624. * @param emissiveTexture the associated emissive texture used to generate the glow
  107625. * @return true if ready otherwise, false
  107626. */
  107627. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  107628. var material = subMesh.getMaterial();
  107629. if (!material) {
  107630. return false;
  107631. }
  107632. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  107633. return false;
  107634. }
  107635. var defines = [];
  107636. var attribs = [BABYLON.VertexBuffer.PositionKind];
  107637. var mesh = subMesh.getMesh();
  107638. var uv1 = false;
  107639. var uv2 = false;
  107640. // Alpha test
  107641. if (material && material.needAlphaTesting()) {
  107642. var alphaTexture = material.getAlphaTestTexture();
  107643. if (alphaTexture) {
  107644. defines.push("#define ALPHATEST");
  107645. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  107646. alphaTexture.coordinatesIndex === 1) {
  107647. defines.push("#define DIFFUSEUV2");
  107648. uv2 = true;
  107649. }
  107650. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  107651. defines.push("#define DIFFUSEUV1");
  107652. uv1 = true;
  107653. }
  107654. }
  107655. }
  107656. // Emissive
  107657. if (emissiveTexture) {
  107658. defines.push("#define EMISSIVE");
  107659. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  107660. emissiveTexture.coordinatesIndex === 1) {
  107661. defines.push("#define EMISSIVEUV2");
  107662. uv2 = true;
  107663. }
  107664. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  107665. defines.push("#define EMISSIVEUV1");
  107666. uv1 = true;
  107667. }
  107668. }
  107669. if (uv1) {
  107670. attribs.push(BABYLON.VertexBuffer.UVKind);
  107671. defines.push("#define UV1");
  107672. }
  107673. if (uv2) {
  107674. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  107675. defines.push("#define UV2");
  107676. }
  107677. // Bones
  107678. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  107679. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  107680. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  107681. if (mesh.numBoneInfluencers > 4) {
  107682. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  107683. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  107684. }
  107685. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  107686. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  107687. }
  107688. else {
  107689. defines.push("#define NUM_BONE_INFLUENCERS 0");
  107690. }
  107691. // Morph targets
  107692. var manager = mesh.morphTargetManager;
  107693. var morphInfluencers = 0;
  107694. if (manager) {
  107695. if (manager.numInfluencers > 0) {
  107696. defines.push("#define MORPHTARGETS");
  107697. morphInfluencers = manager.numInfluencers;
  107698. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  107699. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  107700. }
  107701. }
  107702. // Instances
  107703. if (useInstances) {
  107704. defines.push("#define INSTANCES");
  107705. attribs.push("world0");
  107706. attribs.push("world1");
  107707. attribs.push("world2");
  107708. attribs.push("world3");
  107709. }
  107710. // Get correct effect
  107711. var join = defines.join("\n");
  107712. if (this._cachedDefines !== join) {
  107713. this._cachedDefines = join;
  107714. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  107715. }
  107716. return this._effectLayerMapGenerationEffect.isReady();
  107717. };
  107718. /**
  107719. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  107720. */
  107721. EffectLayer.prototype.render = function () {
  107722. var currentEffect = this._mergeEffect;
  107723. // Check
  107724. if (!currentEffect.isReady())
  107725. return;
  107726. for (var i = 0; i < this._postProcesses.length; i++) {
  107727. if (!this._postProcesses[i].isReady()) {
  107728. return;
  107729. }
  107730. }
  107731. var engine = this._scene.getEngine();
  107732. this.onBeforeComposeObservable.notifyObservers(this);
  107733. // Render
  107734. engine.enableEffect(currentEffect);
  107735. engine.setState(false);
  107736. // VBOs
  107737. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  107738. // Cache
  107739. var previousAlphaMode = engine.getAlphaMode();
  107740. // Go Blend.
  107741. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  107742. // Blends the map on the main canvas.
  107743. this._internalRender(currentEffect);
  107744. // Restore Alpha
  107745. engine.setAlphaMode(previousAlphaMode);
  107746. this.onAfterComposeObservable.notifyObservers(this);
  107747. // Handle size changes.
  107748. var size = this._mainTexture.getSize();
  107749. this._setMainTextureSize();
  107750. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  107751. // Recreate RTT and post processes on size change.
  107752. this.onSizeChangedObservable.notifyObservers(this);
  107753. this._disposeTextureAndPostProcesses();
  107754. this._createMainTexture();
  107755. this._createTextureAndPostProcesses();
  107756. }
  107757. };
  107758. /**
  107759. * Determine if a given mesh will be used in the current effect.
  107760. * @param mesh mesh to test
  107761. * @returns true if the mesh will be used
  107762. */
  107763. EffectLayer.prototype.hasMesh = function (mesh) {
  107764. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  107765. return true;
  107766. }
  107767. return false;
  107768. };
  107769. /**
  107770. * Returns true if the layer contains information to display, otherwise false.
  107771. * @returns true if the glow layer should be rendered
  107772. */
  107773. EffectLayer.prototype.shouldRender = function () {
  107774. return this.isEnabled && this._shouldRender;
  107775. };
  107776. /**
  107777. * Returns true if the mesh should render, otherwise false.
  107778. * @param mesh The mesh to render
  107779. * @returns true if it should render otherwise false
  107780. */
  107781. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  107782. return true;
  107783. };
  107784. /**
  107785. * Returns true if the mesh should render, otherwise false.
  107786. * @param mesh The mesh to render
  107787. * @returns true if it should render otherwise false
  107788. */
  107789. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  107790. return true;
  107791. };
  107792. /**
  107793. * Renders the submesh passed in parameter to the generation map.
  107794. */
  107795. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  107796. var _this = this;
  107797. if (!this.shouldRender()) {
  107798. return;
  107799. }
  107800. var material = subMesh.getMaterial();
  107801. var mesh = subMesh.getRenderingMesh();
  107802. var scene = this._scene;
  107803. var engine = scene.getEngine();
  107804. if (!material) {
  107805. return;
  107806. }
  107807. // Do not block in blend mode.
  107808. if (material.needAlphaBlendingForMesh(mesh)) {
  107809. return;
  107810. }
  107811. // Culling
  107812. engine.setState(material.backFaceCulling);
  107813. // Managing instances
  107814. var batch = mesh._getInstancesRenderList(subMesh._id);
  107815. if (batch.mustReturn) {
  107816. return;
  107817. }
  107818. // Early Exit per mesh
  107819. if (!this._shouldRenderMesh(mesh)) {
  107820. return;
  107821. }
  107822. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  107823. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  107824. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  107825. engine.enableEffect(this._effectLayerMapGenerationEffect);
  107826. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  107827. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  107828. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  107829. // Alpha test
  107830. if (material && material.needAlphaTesting()) {
  107831. var alphaTexture = material.getAlphaTestTexture();
  107832. if (alphaTexture) {
  107833. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  107834. var textureMatrix = alphaTexture.getTextureMatrix();
  107835. if (textureMatrix) {
  107836. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  107837. }
  107838. }
  107839. }
  107840. // Glow emissive only
  107841. if (this._emissiveTextureAndColor.texture) {
  107842. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  107843. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  107844. }
  107845. // Bones
  107846. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  107847. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  107848. }
  107849. // Morph targets
  107850. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  107851. // Draw
  107852. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  107853. }
  107854. else {
  107855. // Need to reset refresh rate of the main map
  107856. this._mainTexture.resetRefreshCounter();
  107857. }
  107858. };
  107859. /**
  107860. * Rebuild the required buffers.
  107861. * @hidden Internal use only.
  107862. */
  107863. EffectLayer.prototype._rebuild = function () {
  107864. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  107865. if (vb) {
  107866. vb._rebuild();
  107867. }
  107868. this._generateIndexBuffer();
  107869. };
  107870. /**
  107871. * Dispose only the render target textures and post process.
  107872. */
  107873. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  107874. this._mainTexture.dispose();
  107875. for (var i = 0; i < this._postProcesses.length; i++) {
  107876. if (this._postProcesses[i]) {
  107877. this._postProcesses[i].dispose();
  107878. }
  107879. }
  107880. this._postProcesses = [];
  107881. for (var i = 0; i < this._textures.length; i++) {
  107882. if (this._textures[i]) {
  107883. this._textures[i].dispose();
  107884. }
  107885. }
  107886. this._textures = [];
  107887. };
  107888. /**
  107889. * Dispose the highlight layer and free resources.
  107890. */
  107891. EffectLayer.prototype.dispose = function () {
  107892. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  107893. if (vertexBuffer) {
  107894. vertexBuffer.dispose();
  107895. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  107896. }
  107897. if (this._indexBuffer) {
  107898. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  107899. this._indexBuffer = null;
  107900. }
  107901. // Clean textures and post processes
  107902. this._disposeTextureAndPostProcesses();
  107903. // Remove from scene
  107904. var index = this._scene.effectLayers.indexOf(this, 0);
  107905. if (index > -1) {
  107906. this._scene.effectLayers.splice(index, 1);
  107907. }
  107908. // Callback
  107909. this.onDisposeObservable.notifyObservers(this);
  107910. this.onDisposeObservable.clear();
  107911. this.onBeforeRenderMainTextureObservable.clear();
  107912. this.onBeforeComposeObservable.clear();
  107913. this.onAfterComposeObservable.clear();
  107914. this.onSizeChangedObservable.clear();
  107915. };
  107916. /**
  107917. * Gets the class name of the effect layer
  107918. * @returns the string with the class name of the effect layer
  107919. */
  107920. EffectLayer.prototype.getClassName = function () {
  107921. return "EffectLayer";
  107922. };
  107923. /**
  107924. * Creates an effect layer from parsed effect layer data
  107925. * @param parsedEffectLayer defines effect layer data
  107926. * @param scene defines the current scene
  107927. * @param rootUrl defines the root URL containing the effect layer information
  107928. * @returns a parsed effect Layer
  107929. */
  107930. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  107931. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  107932. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  107933. };
  107934. __decorate([
  107935. BABYLON.serialize()
  107936. ], EffectLayer.prototype, "name", void 0);
  107937. __decorate([
  107938. BABYLON.serializeAsColor4()
  107939. ], EffectLayer.prototype, "neutralColor", void 0);
  107940. __decorate([
  107941. BABYLON.serialize()
  107942. ], EffectLayer.prototype, "isEnabled", void 0);
  107943. __decorate([
  107944. BABYLON.serializeAsCameraReference()
  107945. ], EffectLayer.prototype, "camera", null);
  107946. __decorate([
  107947. BABYLON.serialize()
  107948. ], EffectLayer.prototype, "renderingGroupId", null);
  107949. return EffectLayer;
  107950. }());
  107951. BABYLON.EffectLayer = EffectLayer;
  107952. })(BABYLON || (BABYLON = {}));
  107953. //# sourceMappingURL=babylon.effectLayer.js.map
  107954. var BABYLON;
  107955. (function (BABYLON) {
  107956. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  107957. for (var index = 0; index < this.effectLayers.length; index++) {
  107958. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  107959. return this.effectLayers[index];
  107960. }
  107961. }
  107962. return null;
  107963. };
  107964. /**
  107965. * Special Glow Blur post process only blurring the alpha channel
  107966. * It enforces keeping the most luminous color in the color channel.
  107967. */
  107968. var GlowBlurPostProcess = /** @class */ (function (_super) {
  107969. __extends(GlowBlurPostProcess, _super);
  107970. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  107971. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  107972. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  107973. _this.direction = direction;
  107974. _this.kernel = kernel;
  107975. _this.onApplyObservable.add(function (effect) {
  107976. effect.setFloat2("screenSize", _this.width, _this.height);
  107977. effect.setVector2("direction", _this.direction);
  107978. effect.setFloat("blurWidth", _this.kernel);
  107979. });
  107980. return _this;
  107981. }
  107982. return GlowBlurPostProcess;
  107983. }(BABYLON.PostProcess));
  107984. /**
  107985. * The highlight layer Helps adding a glow effect around a mesh.
  107986. *
  107987. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  107988. * glowy meshes to your scene.
  107989. *
  107990. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  107991. */
  107992. var HighlightLayer = /** @class */ (function (_super) {
  107993. __extends(HighlightLayer, _super);
  107994. /**
  107995. * Instantiates a new highlight Layer and references it to the scene..
  107996. * @param name The name of the layer
  107997. * @param scene The scene to use the layer in
  107998. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  107999. */
  108000. function HighlightLayer(name, scene, options) {
  108001. var _this = _super.call(this, name, scene) || this;
  108002. _this.name = name;
  108003. /**
  108004. * Specifies whether or not the inner glow is ACTIVE in the layer.
  108005. */
  108006. _this.innerGlow = true;
  108007. /**
  108008. * Specifies whether or not the outer glow is ACTIVE in the layer.
  108009. */
  108010. _this.outerGlow = true;
  108011. /**
  108012. * An event triggered when the highlight layer is being blurred.
  108013. */
  108014. _this.onBeforeBlurObservable = new BABYLON.Observable();
  108015. /**
  108016. * An event triggered when the highlight layer has been blurred.
  108017. */
  108018. _this.onAfterBlurObservable = new BABYLON.Observable();
  108019. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  108020. _this._meshes = {};
  108021. _this._excludedMeshes = {};
  108022. _this.neutralColor = HighlightLayer.NeutralColor;
  108023. // Warn on stencil
  108024. if (!_this._engine.isStencilEnable) {
  108025. 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 }");
  108026. }
  108027. // Adapt options
  108028. _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);
  108029. // Initialize the layer
  108030. _this._init({
  108031. alphaBlendingMode: _this._options.alphaBlendingMode,
  108032. camera: _this._options.camera,
  108033. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  108034. mainTextureRatio: _this._options.mainTextureRatio,
  108035. renderingGroupId: _this._options.renderingGroupId
  108036. });
  108037. // Do not render as long as no meshes have been added
  108038. _this._shouldRender = false;
  108039. return _this;
  108040. }
  108041. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  108042. /**
  108043. * Gets the horizontal size of the blur.
  108044. */
  108045. get: function () {
  108046. return this._horizontalBlurPostprocess.kernel;
  108047. },
  108048. /**
  108049. * Specifies the horizontal size of the blur.
  108050. */
  108051. set: function (value) {
  108052. this._horizontalBlurPostprocess.kernel = value;
  108053. },
  108054. enumerable: true,
  108055. configurable: true
  108056. });
  108057. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  108058. /**
  108059. * Gets the vertical size of the blur.
  108060. */
  108061. get: function () {
  108062. return this._verticalBlurPostprocess.kernel;
  108063. },
  108064. /**
  108065. * Specifies the vertical size of the blur.
  108066. */
  108067. set: function (value) {
  108068. this._verticalBlurPostprocess.kernel = value;
  108069. },
  108070. enumerable: true,
  108071. configurable: true
  108072. });
  108073. /**
  108074. * Get the effect name of the layer.
  108075. * @return The effect name
  108076. */
  108077. HighlightLayer.prototype.getEffectName = function () {
  108078. return HighlightLayer.EffectName;
  108079. };
  108080. /**
  108081. * Create the merge effect. This is the shader use to blit the information back
  108082. * to the main canvas at the end of the scene rendering.
  108083. */
  108084. HighlightLayer.prototype._createMergeEffect = function () {
  108085. // Effect
  108086. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  108087. };
  108088. /**
  108089. * Creates the render target textures and post processes used in the highlight layer.
  108090. */
  108091. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  108092. var _this = this;
  108093. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  108094. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  108095. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  108096. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  108097. var textureType = 0;
  108098. if (this._engine.getCaps().textureHalfFloatRender) {
  108099. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  108100. }
  108101. else {
  108102. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  108103. }
  108104. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  108105. width: blurTextureWidth,
  108106. height: blurTextureHeight
  108107. }, this._scene, false, true, textureType);
  108108. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108109. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108110. this._blurTexture.anisotropicFilteringLevel = 16;
  108111. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  108112. this._blurTexture.renderParticles = false;
  108113. this._blurTexture.ignoreCameraViewport = true;
  108114. this._textures = [this._blurTexture];
  108115. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  108116. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  108117. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  108118. effect.setTexture("textureSampler", _this._mainTexture);
  108119. });
  108120. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  108121. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  108122. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  108123. });
  108124. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  108125. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  108126. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  108127. });
  108128. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  108129. }
  108130. else {
  108131. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  108132. width: blurTextureWidth,
  108133. height: blurTextureHeight
  108134. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  108135. this._horizontalBlurPostprocess.width = blurTextureWidth;
  108136. this._horizontalBlurPostprocess.height = blurTextureHeight;
  108137. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  108138. effect.setTexture("textureSampler", _this._mainTexture);
  108139. });
  108140. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  108141. width: blurTextureWidth,
  108142. height: blurTextureHeight
  108143. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  108144. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  108145. }
  108146. this._mainTexture.onAfterUnbindObservable.add(function () {
  108147. _this.onBeforeBlurObservable.notifyObservers(_this);
  108148. var internalTexture = _this._blurTexture.getInternalTexture();
  108149. if (internalTexture) {
  108150. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  108151. }
  108152. _this.onAfterBlurObservable.notifyObservers(_this);
  108153. });
  108154. // Prevent autoClear.
  108155. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  108156. };
  108157. /**
  108158. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  108159. */
  108160. HighlightLayer.prototype.needStencil = function () {
  108161. return true;
  108162. };
  108163. /**
  108164. * Checks for the readiness of the element composing the layer.
  108165. * @param subMesh the mesh to check for
  108166. * @param useInstances specify wether or not to use instances to render the mesh
  108167. * @param emissiveTexture the associated emissive texture used to generate the glow
  108168. * @return true if ready otherwise, false
  108169. */
  108170. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  108171. var material = subMesh.getMaterial();
  108172. var mesh = subMesh.getRenderingMesh();
  108173. if (!material || !mesh || !this._meshes) {
  108174. return false;
  108175. }
  108176. var emissiveTexture = null;
  108177. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  108178. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  108179. emissiveTexture = material.emissiveTexture;
  108180. }
  108181. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  108182. };
  108183. /**
  108184. * Implementation specific of rendering the generating effect on the main canvas.
  108185. * @param effect The effect used to render through
  108186. */
  108187. HighlightLayer.prototype._internalRender = function (effect) {
  108188. // Texture
  108189. effect.setTexture("textureSampler", this._blurTexture);
  108190. // Cache
  108191. var engine = this._engine;
  108192. var previousStencilBuffer = engine.getStencilBuffer();
  108193. var previousStencilFunction = engine.getStencilFunction();
  108194. var previousStencilMask = engine.getStencilMask();
  108195. var previousStencilOperationPass = engine.getStencilOperationPass();
  108196. var previousStencilOperationFail = engine.getStencilOperationFail();
  108197. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  108198. var previousStencilReference = engine.getStencilFunctionReference();
  108199. // Stencil operations
  108200. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  108201. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  108202. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  108203. // Draw order
  108204. engine.setStencilMask(0x00);
  108205. engine.setStencilBuffer(true);
  108206. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  108207. // 2 passes inner outer
  108208. if (this.outerGlow) {
  108209. effect.setFloat("offset", 0);
  108210. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  108211. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  108212. }
  108213. if (this.innerGlow) {
  108214. effect.setFloat("offset", 1);
  108215. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  108216. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  108217. }
  108218. // Restore Cache
  108219. engine.setStencilFunction(previousStencilFunction);
  108220. engine.setStencilMask(previousStencilMask);
  108221. engine.setStencilBuffer(previousStencilBuffer);
  108222. engine.setStencilOperationPass(previousStencilOperationPass);
  108223. engine.setStencilOperationFail(previousStencilOperationFail);
  108224. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  108225. engine.setStencilFunctionReference(previousStencilReference);
  108226. };
  108227. /**
  108228. * Returns true if the layer contains information to display, otherwise false.
  108229. */
  108230. HighlightLayer.prototype.shouldRender = function () {
  108231. if (_super.prototype.shouldRender.call(this)) {
  108232. return this._meshes ? true : false;
  108233. }
  108234. return false;
  108235. };
  108236. /**
  108237. * Returns true if the mesh should render, otherwise false.
  108238. * @param mesh The mesh to render
  108239. * @returns true if it should render otherwise false
  108240. */
  108241. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  108242. // Excluded Mesh
  108243. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  108244. return false;
  108245. }
  108246. ;
  108247. if (!_super.prototype.hasMesh.call(this, mesh)) {
  108248. return false;
  108249. }
  108250. return true;
  108251. };
  108252. /**
  108253. * Sets the required values for both the emissive texture and and the main color.
  108254. */
  108255. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  108256. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  108257. if (highlightLayerMesh) {
  108258. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  108259. }
  108260. else {
  108261. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  108262. }
  108263. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  108264. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  108265. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  108266. }
  108267. else {
  108268. this._emissiveTextureAndColor.texture = null;
  108269. }
  108270. };
  108271. /**
  108272. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  108273. * @param mesh The mesh to exclude from the highlight layer
  108274. */
  108275. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  108276. if (!this._excludedMeshes) {
  108277. return;
  108278. }
  108279. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  108280. if (!meshExcluded) {
  108281. this._excludedMeshes[mesh.uniqueId] = {
  108282. mesh: mesh,
  108283. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  108284. mesh.getEngine().setStencilBuffer(false);
  108285. }),
  108286. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  108287. mesh.getEngine().setStencilBuffer(true);
  108288. }),
  108289. };
  108290. }
  108291. };
  108292. /**
  108293. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  108294. * @param mesh The mesh to highlight
  108295. */
  108296. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  108297. if (!this._excludedMeshes) {
  108298. return;
  108299. }
  108300. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  108301. if (meshExcluded) {
  108302. if (meshExcluded.beforeRender) {
  108303. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  108304. }
  108305. if (meshExcluded.afterRender) {
  108306. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  108307. }
  108308. }
  108309. this._excludedMeshes[mesh.uniqueId] = null;
  108310. };
  108311. /**
  108312. * Determine if a given mesh will be highlighted by the current HighlightLayer
  108313. * @param mesh mesh to test
  108314. * @returns true if the mesh will be highlighted by the current HighlightLayer
  108315. */
  108316. HighlightLayer.prototype.hasMesh = function (mesh) {
  108317. if (!this._meshes) {
  108318. return false;
  108319. }
  108320. if (!_super.prototype.hasMesh.call(this, mesh)) {
  108321. return false;
  108322. }
  108323. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  108324. };
  108325. /**
  108326. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  108327. * @param mesh The mesh to highlight
  108328. * @param color The color of the highlight
  108329. * @param glowEmissiveOnly Extract the glow from the emissive texture
  108330. */
  108331. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  108332. var _this = this;
  108333. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  108334. if (!this._meshes) {
  108335. return;
  108336. }
  108337. var meshHighlight = this._meshes[mesh.uniqueId];
  108338. if (meshHighlight) {
  108339. meshHighlight.color = color;
  108340. }
  108341. else {
  108342. this._meshes[mesh.uniqueId] = {
  108343. mesh: mesh,
  108344. color: color,
  108345. // Lambda required for capture due to Observable this context
  108346. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  108347. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  108348. _this._defaultStencilReference(mesh);
  108349. }
  108350. else {
  108351. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  108352. }
  108353. }),
  108354. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  108355. glowEmissiveOnly: glowEmissiveOnly
  108356. };
  108357. mesh.onDisposeObservable.add(function () {
  108358. _this._disposeMesh(mesh);
  108359. });
  108360. }
  108361. this._shouldRender = true;
  108362. };
  108363. /**
  108364. * Remove a mesh from the highlight layer in order to make it stop glowing.
  108365. * @param mesh The mesh to highlight
  108366. */
  108367. HighlightLayer.prototype.removeMesh = function (mesh) {
  108368. if (!this._meshes) {
  108369. return;
  108370. }
  108371. var meshHighlight = this._meshes[mesh.uniqueId];
  108372. if (meshHighlight) {
  108373. if (meshHighlight.observerHighlight) {
  108374. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  108375. }
  108376. if (meshHighlight.observerDefault) {
  108377. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  108378. }
  108379. delete this._meshes[mesh.uniqueId];
  108380. }
  108381. this._shouldRender = false;
  108382. for (var meshHighlightToCheck in this._meshes) {
  108383. if (this._meshes[meshHighlightToCheck]) {
  108384. this._shouldRender = true;
  108385. break;
  108386. }
  108387. }
  108388. };
  108389. /**
  108390. * Force the stencil to the normal expected value for none glowing parts
  108391. */
  108392. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  108393. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  108394. };
  108395. /**
  108396. * Free any resources and references associated to a mesh.
  108397. * Internal use
  108398. * @param mesh The mesh to free.
  108399. * @hidden
  108400. */
  108401. HighlightLayer.prototype._disposeMesh = function (mesh) {
  108402. this.removeMesh(mesh);
  108403. this.removeExcludedMesh(mesh);
  108404. };
  108405. /**
  108406. * Dispose the highlight layer and free resources.
  108407. */
  108408. HighlightLayer.prototype.dispose = function () {
  108409. if (this._meshes) {
  108410. // Clean mesh references
  108411. for (var id in this._meshes) {
  108412. var meshHighlight = this._meshes[id];
  108413. if (meshHighlight && meshHighlight.mesh) {
  108414. if (meshHighlight.observerHighlight) {
  108415. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  108416. }
  108417. if (meshHighlight.observerDefault) {
  108418. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  108419. }
  108420. }
  108421. }
  108422. this._meshes = null;
  108423. }
  108424. if (this._excludedMeshes) {
  108425. for (var id in this._excludedMeshes) {
  108426. var meshHighlight = this._excludedMeshes[id];
  108427. if (meshHighlight) {
  108428. if (meshHighlight.beforeRender) {
  108429. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  108430. }
  108431. if (meshHighlight.afterRender) {
  108432. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  108433. }
  108434. }
  108435. }
  108436. this._excludedMeshes = null;
  108437. }
  108438. _super.prototype.dispose.call(this);
  108439. };
  108440. /**
  108441. * Gets the class name of the effect layer
  108442. * @returns the string with the class name of the effect layer
  108443. */
  108444. HighlightLayer.prototype.getClassName = function () {
  108445. return "HighlightLayer";
  108446. };
  108447. /**
  108448. * Serializes this Highlight layer
  108449. * @returns a serialized Highlight layer object
  108450. */
  108451. HighlightLayer.prototype.serialize = function () {
  108452. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  108453. serializationObject.customType = "BABYLON.HighlightLayer";
  108454. // Highlighted meshes
  108455. serializationObject.meshes = [];
  108456. if (this._meshes) {
  108457. for (var m in this._meshes) {
  108458. var mesh = this._meshes[m];
  108459. if (mesh) {
  108460. serializationObject.meshes.push({
  108461. glowEmissiveOnly: mesh.glowEmissiveOnly,
  108462. color: mesh.color.asArray(),
  108463. meshId: mesh.mesh.id
  108464. });
  108465. }
  108466. }
  108467. }
  108468. // Excluded meshes
  108469. serializationObject.excludedMeshes = [];
  108470. if (this._excludedMeshes) {
  108471. for (var e in this._excludedMeshes) {
  108472. var excludedMesh = this._excludedMeshes[e];
  108473. if (excludedMesh) {
  108474. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  108475. }
  108476. }
  108477. }
  108478. return serializationObject;
  108479. };
  108480. /**
  108481. * Creates a Highlight layer from parsed Highlight layer data
  108482. * @param parsedHightlightLayer defines the Highlight layer data
  108483. * @param scene defines the current scene
  108484. * @param rootUrl defines the root URL containing the Highlight layer information
  108485. * @returns a parsed Highlight layer
  108486. */
  108487. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  108488. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  108489. var index;
  108490. // Excluded meshes
  108491. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  108492. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  108493. if (mesh) {
  108494. hl.addExcludedMesh(mesh);
  108495. }
  108496. }
  108497. // Included meshes
  108498. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  108499. var highlightedMesh = parsedHightlightLayer.meshes[index];
  108500. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  108501. if (mesh) {
  108502. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  108503. }
  108504. }
  108505. return hl;
  108506. };
  108507. /**
  108508. * Effect Name of the highlight layer.
  108509. */
  108510. HighlightLayer.EffectName = "HighlightLayer";
  108511. /**
  108512. * The neutral color used during the preparation of the glow effect.
  108513. * This is black by default as the blend operation is a blend operation.
  108514. */
  108515. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  108516. /**
  108517. * Stencil value used for glowing meshes.
  108518. */
  108519. HighlightLayer.GlowingMeshStencilReference = 0x02;
  108520. /**
  108521. * Stencil value used for the other meshes in the scene.
  108522. */
  108523. HighlightLayer.NormalMeshStencilReference = 0x01;
  108524. __decorate([
  108525. BABYLON.serialize()
  108526. ], HighlightLayer.prototype, "innerGlow", void 0);
  108527. __decorate([
  108528. BABYLON.serialize()
  108529. ], HighlightLayer.prototype, "outerGlow", void 0);
  108530. __decorate([
  108531. BABYLON.serialize()
  108532. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  108533. __decorate([
  108534. BABYLON.serialize()
  108535. ], HighlightLayer.prototype, "blurVerticalSize", null);
  108536. __decorate([
  108537. BABYLON.serialize("options")
  108538. ], HighlightLayer.prototype, "_options", void 0);
  108539. return HighlightLayer;
  108540. }(BABYLON.EffectLayer));
  108541. BABYLON.HighlightLayer = HighlightLayer;
  108542. })(BABYLON || (BABYLON = {}));
  108543. //# sourceMappingURL=babylon.highlightLayer.js.map
  108544. var BABYLON;
  108545. (function (BABYLON) {
  108546. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  108547. for (var index = 0; index < this.effectLayers.length; index++) {
  108548. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  108549. return this.effectLayers[index];
  108550. }
  108551. }
  108552. return null;
  108553. };
  108554. /**
  108555. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  108556. *
  108557. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  108558. * glowy meshes to your scene.
  108559. *
  108560. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  108561. */
  108562. var GlowLayer = /** @class */ (function (_super) {
  108563. __extends(GlowLayer, _super);
  108564. /**
  108565. * Instantiates a new glow Layer and references it to the scene.
  108566. * @param name The name of the layer
  108567. * @param scene The scene to use the layer in
  108568. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  108569. */
  108570. function GlowLayer(name, scene, options) {
  108571. var _this = _super.call(this, name, scene) || this;
  108572. _this._intensity = 1.0;
  108573. _this._includedOnlyMeshes = [];
  108574. _this._excludedMeshes = [];
  108575. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  108576. // Adapt options
  108577. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  108578. // Initialize the layer
  108579. _this._init({
  108580. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  108581. camera: _this._options.camera,
  108582. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  108583. mainTextureRatio: _this._options.mainTextureRatio,
  108584. renderingGroupId: _this._options.renderingGroupId
  108585. });
  108586. return _this;
  108587. }
  108588. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  108589. /**
  108590. * Gets the kernel size of the blur.
  108591. */
  108592. get: function () {
  108593. return this._horizontalBlurPostprocess1.kernel;
  108594. },
  108595. /**
  108596. * Sets the kernel size of the blur.
  108597. */
  108598. set: function (value) {
  108599. this._horizontalBlurPostprocess1.kernel = value;
  108600. this._verticalBlurPostprocess1.kernel = value;
  108601. this._horizontalBlurPostprocess2.kernel = value;
  108602. this._verticalBlurPostprocess2.kernel = value;
  108603. },
  108604. enumerable: true,
  108605. configurable: true
  108606. });
  108607. Object.defineProperty(GlowLayer.prototype, "intensity", {
  108608. /**
  108609. * Gets the glow intensity.
  108610. */
  108611. get: function () {
  108612. return this._intensity;
  108613. },
  108614. /**
  108615. * Sets the glow intensity.
  108616. */
  108617. set: function (value) {
  108618. this._intensity = value;
  108619. },
  108620. enumerable: true,
  108621. configurable: true
  108622. });
  108623. /**
  108624. * Get the effect name of the layer.
  108625. * @return The effect name
  108626. */
  108627. GlowLayer.prototype.getEffectName = function () {
  108628. return GlowLayer.EffectName;
  108629. };
  108630. /**
  108631. * Create the merge effect. This is the shader use to blit the information back
  108632. * to the main canvas at the end of the scene rendering.
  108633. */
  108634. GlowLayer.prototype._createMergeEffect = function () {
  108635. // Effect
  108636. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  108637. };
  108638. /**
  108639. * Creates the render target textures and post processes used in the glow layer.
  108640. */
  108641. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  108642. var _this = this;
  108643. var blurTextureWidth = this._mainTextureDesiredSize.width;
  108644. var blurTextureHeight = this._mainTextureDesiredSize.height;
  108645. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  108646. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  108647. var textureType = 0;
  108648. if (this._engine.getCaps().textureHalfFloatRender) {
  108649. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  108650. }
  108651. else {
  108652. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  108653. }
  108654. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  108655. width: blurTextureWidth,
  108656. height: blurTextureHeight
  108657. }, this._scene, false, true, textureType);
  108658. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108659. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108660. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  108661. this._blurTexture1.renderParticles = false;
  108662. this._blurTexture1.ignoreCameraViewport = true;
  108663. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  108664. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  108665. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  108666. width: blurTextureWidth2,
  108667. height: blurTextureHeight2
  108668. }, this._scene, false, true, textureType);
  108669. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108670. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108671. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  108672. this._blurTexture2.renderParticles = false;
  108673. this._blurTexture2.ignoreCameraViewport = true;
  108674. this._textures = [this._blurTexture1, this._blurTexture2];
  108675. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  108676. width: blurTextureWidth,
  108677. height: blurTextureHeight
  108678. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  108679. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  108680. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  108681. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  108682. effect.setTexture("textureSampler", _this._mainTexture);
  108683. });
  108684. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  108685. width: blurTextureWidth,
  108686. height: blurTextureHeight
  108687. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  108688. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  108689. width: blurTextureWidth2,
  108690. height: blurTextureHeight2
  108691. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  108692. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  108693. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  108694. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  108695. effect.setTexture("textureSampler", _this._blurTexture1);
  108696. });
  108697. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  108698. width: blurTextureWidth2,
  108699. height: blurTextureHeight2
  108700. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  108701. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  108702. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  108703. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  108704. this._mainTexture.samples = this._options.mainTextureSamples;
  108705. this._mainTexture.onAfterUnbindObservable.add(function () {
  108706. var internalTexture = _this._blurTexture1.getInternalTexture();
  108707. if (internalTexture) {
  108708. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  108709. internalTexture = _this._blurTexture2.getInternalTexture();
  108710. if (internalTexture) {
  108711. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  108712. }
  108713. }
  108714. });
  108715. // Prevent autoClear.
  108716. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  108717. };
  108718. /**
  108719. * Checks for the readiness of the element composing the layer.
  108720. * @param subMesh the mesh to check for
  108721. * @param useInstances specify wether or not to use instances to render the mesh
  108722. * @param emissiveTexture the associated emissive texture used to generate the glow
  108723. * @return true if ready otherwise, false
  108724. */
  108725. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  108726. var material = subMesh.getMaterial();
  108727. var mesh = subMesh.getRenderingMesh();
  108728. if (!material || !mesh) {
  108729. return false;
  108730. }
  108731. var emissiveTexture = material.emissiveTexture;
  108732. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  108733. };
  108734. /**
  108735. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  108736. */
  108737. GlowLayer.prototype.needStencil = function () {
  108738. return false;
  108739. };
  108740. /**
  108741. * Implementation specific of rendering the generating effect on the main canvas.
  108742. * @param effect The effect used to render through
  108743. */
  108744. GlowLayer.prototype._internalRender = function (effect) {
  108745. // Texture
  108746. effect.setTexture("textureSampler", this._blurTexture1);
  108747. effect.setTexture("textureSampler2", this._blurTexture2);
  108748. effect.setFloat("offset", this._intensity);
  108749. // Cache
  108750. var engine = this._engine;
  108751. var previousStencilBuffer = engine.getStencilBuffer();
  108752. // Draw order
  108753. engine.setStencilBuffer(false);
  108754. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  108755. // Draw order
  108756. engine.setStencilBuffer(previousStencilBuffer);
  108757. };
  108758. /**
  108759. * Sets the required values for both the emissive texture and and the main color.
  108760. */
  108761. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  108762. var textureLevel = 1.0;
  108763. if (this.customEmissiveTextureSelector) {
  108764. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  108765. }
  108766. else {
  108767. if (material) {
  108768. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  108769. if (this._emissiveTextureAndColor.texture) {
  108770. textureLevel = this._emissiveTextureAndColor.texture.level;
  108771. }
  108772. }
  108773. else {
  108774. this._emissiveTextureAndColor.texture = null;
  108775. }
  108776. }
  108777. if (this.customEmissiveColorSelector) {
  108778. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  108779. }
  108780. else {
  108781. if (material.emissiveColor) {
  108782. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  108783. }
  108784. else {
  108785. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  108786. }
  108787. }
  108788. };
  108789. /**
  108790. * Returns true if the mesh should render, otherwise false.
  108791. * @param mesh The mesh to render
  108792. * @returns true if it should render otherwise false
  108793. */
  108794. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  108795. return this.hasMesh(mesh);
  108796. };
  108797. /**
  108798. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  108799. * @param mesh The mesh to exclude from the glow layer
  108800. */
  108801. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  108802. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  108803. this._excludedMeshes.push(mesh.uniqueId);
  108804. }
  108805. };
  108806. /**
  108807. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  108808. * @param mesh The mesh to remove
  108809. */
  108810. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  108811. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  108812. if (index !== -1) {
  108813. this._excludedMeshes.splice(index, 1);
  108814. }
  108815. };
  108816. /**
  108817. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  108818. * @param mesh The mesh to include in the glow layer
  108819. */
  108820. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  108821. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  108822. this._includedOnlyMeshes.push(mesh.uniqueId);
  108823. }
  108824. };
  108825. /**
  108826. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  108827. * @param mesh The mesh to remove
  108828. */
  108829. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  108830. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  108831. if (index !== -1) {
  108832. this._includedOnlyMeshes.splice(index, 1);
  108833. }
  108834. };
  108835. /**
  108836. * Determine if a given mesh will be used in the glow layer
  108837. * @param mesh The mesh to test
  108838. * @returns true if the mesh will be highlighted by the current glow layer
  108839. */
  108840. GlowLayer.prototype.hasMesh = function (mesh) {
  108841. if (!_super.prototype.hasMesh.call(this, mesh)) {
  108842. return false;
  108843. }
  108844. // Included Mesh
  108845. if (this._includedOnlyMeshes.length) {
  108846. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  108847. }
  108848. ;
  108849. // Excluded Mesh
  108850. if (this._excludedMeshes.length) {
  108851. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  108852. }
  108853. ;
  108854. return true;
  108855. };
  108856. /**
  108857. * Free any resources and references associated to a mesh.
  108858. * Internal use
  108859. * @param mesh The mesh to free.
  108860. * @hidden
  108861. */
  108862. GlowLayer.prototype._disposeMesh = function (mesh) {
  108863. this.removeIncludedOnlyMesh(mesh);
  108864. this.removeExcludedMesh(mesh);
  108865. };
  108866. /**
  108867. * Gets the class name of the effect layer
  108868. * @returns the string with the class name of the effect layer
  108869. */
  108870. GlowLayer.prototype.getClassName = function () {
  108871. return "GlowLayer";
  108872. };
  108873. /**
  108874. * Serializes this glow layer
  108875. * @returns a serialized glow layer object
  108876. */
  108877. GlowLayer.prototype.serialize = function () {
  108878. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  108879. serializationObject.customType = "BABYLON.GlowLayer";
  108880. var index;
  108881. // Included meshes
  108882. serializationObject.includedMeshes = [];
  108883. if (this._includedOnlyMeshes.length) {
  108884. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  108885. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  108886. if (mesh) {
  108887. serializationObject.includedMeshes.push(mesh.id);
  108888. }
  108889. }
  108890. }
  108891. // Excluded meshes
  108892. serializationObject.excludedMeshes = [];
  108893. if (this._excludedMeshes.length) {
  108894. for (index = 0; index < this._excludedMeshes.length; index++) {
  108895. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  108896. if (mesh) {
  108897. serializationObject.excludedMeshes.push(mesh.id);
  108898. }
  108899. }
  108900. }
  108901. return serializationObject;
  108902. };
  108903. /**
  108904. * Creates a Glow Layer from parsed glow layer data
  108905. * @param parsedGlowLayer defines glow layer data
  108906. * @param scene defines the current scene
  108907. * @param rootUrl defines the root URL containing the glow layer information
  108908. * @returns a parsed Glow Layer
  108909. */
  108910. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  108911. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  108912. var index;
  108913. // Excluded meshes
  108914. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  108915. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  108916. if (mesh) {
  108917. gl.addExcludedMesh(mesh);
  108918. }
  108919. }
  108920. // Included meshes
  108921. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  108922. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  108923. if (mesh) {
  108924. gl.addIncludedOnlyMesh(mesh);
  108925. }
  108926. }
  108927. return gl;
  108928. };
  108929. /**
  108930. * Effect Name of the layer.
  108931. */
  108932. GlowLayer.EffectName = "GlowLayer";
  108933. /**
  108934. * The default blur kernel size used for the glow.
  108935. */
  108936. GlowLayer.DefaultBlurKernelSize = 32;
  108937. /**
  108938. * The default texture size ratio used for the glow.
  108939. */
  108940. GlowLayer.DefaultTextureRatio = 0.5;
  108941. __decorate([
  108942. BABYLON.serialize()
  108943. ], GlowLayer.prototype, "blurKernelSize", null);
  108944. __decorate([
  108945. BABYLON.serialize()
  108946. ], GlowLayer.prototype, "intensity", null);
  108947. __decorate([
  108948. BABYLON.serialize("options")
  108949. ], GlowLayer.prototype, "_options", void 0);
  108950. return GlowLayer;
  108951. }(BABYLON.EffectLayer));
  108952. BABYLON.GlowLayer = GlowLayer;
  108953. })(BABYLON || (BABYLON = {}));
  108954. //# sourceMappingURL=babylon.glowLayer.js.map
  108955. var BABYLON;
  108956. (function (BABYLON) {
  108957. /**
  108958. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  108959. */
  108960. var AssetTaskState;
  108961. (function (AssetTaskState) {
  108962. /**
  108963. * Initialization
  108964. */
  108965. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  108966. /**
  108967. * Running
  108968. */
  108969. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  108970. /**
  108971. * Done
  108972. */
  108973. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  108974. /**
  108975. * Error
  108976. */
  108977. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  108978. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  108979. /**
  108980. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  108981. */
  108982. var AbstractAssetTask = /** @class */ (function () {
  108983. /**
  108984. * Creates a new {BABYLON.AssetsManager}
  108985. * @param name defines the name of the task
  108986. */
  108987. function AbstractAssetTask(
  108988. /**
  108989. * Task name
  108990. */ name) {
  108991. this.name = name;
  108992. this._isCompleted = false;
  108993. this._taskState = AssetTaskState.INIT;
  108994. }
  108995. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  108996. /**
  108997. * Get if the task is completed
  108998. */
  108999. get: function () {
  109000. return this._isCompleted;
  109001. },
  109002. enumerable: true,
  109003. configurable: true
  109004. });
  109005. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  109006. /**
  109007. * Gets the current state of the task
  109008. */
  109009. get: function () {
  109010. return this._taskState;
  109011. },
  109012. enumerable: true,
  109013. configurable: true
  109014. });
  109015. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  109016. /**
  109017. * Gets the current error object (if task is in error)
  109018. */
  109019. get: function () {
  109020. return this._errorObject;
  109021. },
  109022. enumerable: true,
  109023. configurable: true
  109024. });
  109025. /**
  109026. * Internal only
  109027. * @hidden
  109028. */
  109029. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  109030. if (this._errorObject) {
  109031. return;
  109032. }
  109033. this._errorObject = {
  109034. message: message,
  109035. exception: exception
  109036. };
  109037. };
  109038. /**
  109039. * Execute the current task
  109040. * @param scene defines the scene where you want your assets to be loaded
  109041. * @param onSuccess is a callback called when the task is successfully executed
  109042. * @param onError is a callback called if an error occurs
  109043. */
  109044. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  109045. var _this = this;
  109046. this._taskState = AssetTaskState.RUNNING;
  109047. this.runTask(scene, function () {
  109048. _this.onDoneCallback(onSuccess, onError);
  109049. }, function (msg, exception) {
  109050. _this.onErrorCallback(onError, msg, exception);
  109051. });
  109052. };
  109053. /**
  109054. * Execute the current task
  109055. * @param scene defines the scene where you want your assets to be loaded
  109056. * @param onSuccess is a callback called when the task is successfully executed
  109057. * @param onError is a callback called if an error occurs
  109058. */
  109059. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  109060. throw new Error("runTask is not implemented");
  109061. };
  109062. /**
  109063. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  109064. * This can be used with failed tasks that have the reason for failure fixed.
  109065. */
  109066. AbstractAssetTask.prototype.reset = function () {
  109067. this._taskState = AssetTaskState.INIT;
  109068. };
  109069. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  109070. this._taskState = AssetTaskState.ERROR;
  109071. this._errorObject = {
  109072. message: message,
  109073. exception: exception
  109074. };
  109075. if (this.onError) {
  109076. this.onError(this, message, exception);
  109077. }
  109078. onError();
  109079. };
  109080. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  109081. try {
  109082. this._taskState = AssetTaskState.DONE;
  109083. this._isCompleted = true;
  109084. if (this.onSuccess) {
  109085. this.onSuccess(this);
  109086. }
  109087. onSuccess();
  109088. }
  109089. catch (e) {
  109090. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  109091. }
  109092. };
  109093. return AbstractAssetTask;
  109094. }());
  109095. BABYLON.AbstractAssetTask = AbstractAssetTask;
  109096. /**
  109097. * Class used to share progress information about assets loading
  109098. */
  109099. var AssetsProgressEvent = /** @class */ (function () {
  109100. /**
  109101. * Creates a {BABYLON.AssetsProgressEvent}
  109102. * @param remainingCount defines the number of remaining tasks to process
  109103. * @param totalCount defines the total number of tasks
  109104. * @param task defines the task that was just processed
  109105. */
  109106. function AssetsProgressEvent(remainingCount, totalCount, task) {
  109107. this.remainingCount = remainingCount;
  109108. this.totalCount = totalCount;
  109109. this.task = task;
  109110. }
  109111. return AssetsProgressEvent;
  109112. }());
  109113. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  109114. /**
  109115. * Define a task used by {BABYLON.AssetsManager} to load meshes
  109116. */
  109117. var MeshAssetTask = /** @class */ (function (_super) {
  109118. __extends(MeshAssetTask, _super);
  109119. /**
  109120. * Creates a new {BABYLON.MeshAssetTask}
  109121. * @param name defines the name of the task
  109122. * @param meshesNames defines the list of mesh's names you want to load
  109123. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  109124. * @param sceneFilename defines the filename of the scene to load from
  109125. */
  109126. function MeshAssetTask(
  109127. /**
  109128. * Defines the name of the task
  109129. */
  109130. name,
  109131. /**
  109132. * Defines the list of mesh's names you want to load
  109133. */
  109134. meshesNames,
  109135. /**
  109136. * Defines the root url to use as a base to load your meshes and associated resources
  109137. */
  109138. rootUrl,
  109139. /**
  109140. * Defines the filename of the scene to load from
  109141. */
  109142. sceneFilename) {
  109143. var _this = _super.call(this, name) || this;
  109144. _this.name = name;
  109145. _this.meshesNames = meshesNames;
  109146. _this.rootUrl = rootUrl;
  109147. _this.sceneFilename = sceneFilename;
  109148. return _this;
  109149. }
  109150. /**
  109151. * Execute the current task
  109152. * @param scene defines the scene where you want your assets to be loaded
  109153. * @param onSuccess is a callback called when the task is successfully executed
  109154. * @param onError is a callback called if an error occurs
  109155. */
  109156. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  109157. var _this = this;
  109158. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  109159. _this.loadedMeshes = meshes;
  109160. _this.loadedParticleSystems = particleSystems;
  109161. _this.loadedSkeletons = skeletons;
  109162. onSuccess();
  109163. }, null, function (scene, message, exception) {
  109164. onError(message, exception);
  109165. });
  109166. };
  109167. return MeshAssetTask;
  109168. }(AbstractAssetTask));
  109169. BABYLON.MeshAssetTask = MeshAssetTask;
  109170. /**
  109171. * Define a task used by {BABYLON.AssetsManager} to load text content
  109172. */
  109173. var TextFileAssetTask = /** @class */ (function (_super) {
  109174. __extends(TextFileAssetTask, _super);
  109175. /**
  109176. * Creates a new TextFileAssetTask object
  109177. * @param name defines the name of the task
  109178. * @param url defines the location of the file to load
  109179. */
  109180. function TextFileAssetTask(
  109181. /**
  109182. * Defines the name of the task
  109183. */
  109184. name,
  109185. /**
  109186. * Defines the location of the file to load
  109187. */
  109188. url) {
  109189. var _this = _super.call(this, name) || this;
  109190. _this.name = name;
  109191. _this.url = url;
  109192. return _this;
  109193. }
  109194. /**
  109195. * Execute the current task
  109196. * @param scene defines the scene where you want your assets to be loaded
  109197. * @param onSuccess is a callback called when the task is successfully executed
  109198. * @param onError is a callback called if an error occurs
  109199. */
  109200. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  109201. var _this = this;
  109202. scene._loadFile(this.url, function (data) {
  109203. _this.text = data;
  109204. onSuccess();
  109205. }, undefined, false, false, function (request, exception) {
  109206. if (request) {
  109207. onError(request.status + " " + request.statusText, exception);
  109208. }
  109209. });
  109210. };
  109211. return TextFileAssetTask;
  109212. }(AbstractAssetTask));
  109213. BABYLON.TextFileAssetTask = TextFileAssetTask;
  109214. /**
  109215. * Define a task used by {BABYLON.AssetsManager} to load binary data
  109216. */
  109217. var BinaryFileAssetTask = /** @class */ (function (_super) {
  109218. __extends(BinaryFileAssetTask, _super);
  109219. /**
  109220. * Creates a new BinaryFileAssetTask object
  109221. * @param name defines the name of the new task
  109222. * @param url defines the location of the file to load
  109223. */
  109224. function BinaryFileAssetTask(
  109225. /**
  109226. * Defines the name of the task
  109227. */
  109228. name,
  109229. /**
  109230. * Defines the location of the file to load
  109231. */
  109232. url) {
  109233. var _this = _super.call(this, name) || this;
  109234. _this.name = name;
  109235. _this.url = url;
  109236. return _this;
  109237. }
  109238. /**
  109239. * Execute the current task
  109240. * @param scene defines the scene where you want your assets to be loaded
  109241. * @param onSuccess is a callback called when the task is successfully executed
  109242. * @param onError is a callback called if an error occurs
  109243. */
  109244. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  109245. var _this = this;
  109246. scene._loadFile(this.url, function (data) {
  109247. _this.data = data;
  109248. onSuccess();
  109249. }, undefined, true, true, function (request, exception) {
  109250. if (request) {
  109251. onError(request.status + " " + request.statusText, exception);
  109252. }
  109253. });
  109254. };
  109255. return BinaryFileAssetTask;
  109256. }(AbstractAssetTask));
  109257. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  109258. /**
  109259. * Define a task used by {BABYLON.AssetsManager} to load images
  109260. */
  109261. var ImageAssetTask = /** @class */ (function (_super) {
  109262. __extends(ImageAssetTask, _super);
  109263. /**
  109264. * Creates a new ImageAssetTask
  109265. * @param name defines the name of the task
  109266. * @param url defines the location of the image to load
  109267. */
  109268. function ImageAssetTask(
  109269. /**
  109270. * Defines the name of the task
  109271. */
  109272. name,
  109273. /**
  109274. * Defines the location of the image to load
  109275. */
  109276. url) {
  109277. var _this = _super.call(this, name) || this;
  109278. _this.name = name;
  109279. _this.url = url;
  109280. return _this;
  109281. }
  109282. /**
  109283. * Execute the current task
  109284. * @param scene defines the scene where you want your assets to be loaded
  109285. * @param onSuccess is a callback called when the task is successfully executed
  109286. * @param onError is a callback called if an error occurs
  109287. */
  109288. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  109289. var _this = this;
  109290. var img = new Image();
  109291. BABYLON.Tools.SetCorsBehavior(this.url, img);
  109292. img.onload = function () {
  109293. _this.image = img;
  109294. onSuccess();
  109295. };
  109296. img.onerror = function (err) {
  109297. onError("Error loading image", err);
  109298. };
  109299. img.src = this.url;
  109300. };
  109301. return ImageAssetTask;
  109302. }(AbstractAssetTask));
  109303. BABYLON.ImageAssetTask = ImageAssetTask;
  109304. /**
  109305. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  109306. */
  109307. var TextureAssetTask = /** @class */ (function (_super) {
  109308. __extends(TextureAssetTask, _super);
  109309. /**
  109310. * Creates a new TextureAssetTask object
  109311. * @param name defines the name of the task
  109312. * @param url defines the location of the file to load
  109313. * @param noMipmap defines if mipmap should not be generated (default is false)
  109314. * @param invertY defines if texture must be inverted on Y axis (default is false)
  109315. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  109316. */
  109317. function TextureAssetTask(
  109318. /**
  109319. * Defines the name of the task
  109320. */
  109321. name,
  109322. /**
  109323. * Defines the location of the file to load
  109324. */
  109325. url,
  109326. /**
  109327. * Defines if mipmap should not be generated (default is false)
  109328. */
  109329. noMipmap,
  109330. /**
  109331. * Defines if texture must be inverted on Y axis (default is false)
  109332. */
  109333. invertY,
  109334. /**
  109335. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  109336. */
  109337. samplingMode) {
  109338. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  109339. var _this = _super.call(this, name) || this;
  109340. _this.name = name;
  109341. _this.url = url;
  109342. _this.noMipmap = noMipmap;
  109343. _this.invertY = invertY;
  109344. _this.samplingMode = samplingMode;
  109345. return _this;
  109346. }
  109347. /**
  109348. * Execute the current task
  109349. * @param scene defines the scene where you want your assets to be loaded
  109350. * @param onSuccess is a callback called when the task is successfully executed
  109351. * @param onError is a callback called if an error occurs
  109352. */
  109353. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  109354. var onload = function () {
  109355. onSuccess();
  109356. };
  109357. var onerror = function (message, exception) {
  109358. onError(message, exception);
  109359. };
  109360. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  109361. };
  109362. return TextureAssetTask;
  109363. }(AbstractAssetTask));
  109364. BABYLON.TextureAssetTask = TextureAssetTask;
  109365. /**
  109366. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  109367. */
  109368. var CubeTextureAssetTask = /** @class */ (function (_super) {
  109369. __extends(CubeTextureAssetTask, _super);
  109370. /**
  109371. * Creates a new CubeTextureAssetTask
  109372. * @param name defines the name of the task
  109373. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  109374. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  109375. * @param noMipmap defines if mipmaps should not be generated (default is false)
  109376. * @param files defines the explicit list of files (undefined by default)
  109377. */
  109378. function CubeTextureAssetTask(
  109379. /**
  109380. * Defines the name of the task
  109381. */
  109382. name,
  109383. /**
  109384. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  109385. */
  109386. url,
  109387. /**
  109388. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  109389. */
  109390. extensions,
  109391. /**
  109392. * Defines if mipmaps should not be generated (default is false)
  109393. */
  109394. noMipmap,
  109395. /**
  109396. * Defines the explicit list of files (undefined by default)
  109397. */
  109398. files) {
  109399. var _this = _super.call(this, name) || this;
  109400. _this.name = name;
  109401. _this.url = url;
  109402. _this.extensions = extensions;
  109403. _this.noMipmap = noMipmap;
  109404. _this.files = files;
  109405. return _this;
  109406. }
  109407. /**
  109408. * Execute the current task
  109409. * @param scene defines the scene where you want your assets to be loaded
  109410. * @param onSuccess is a callback called when the task is successfully executed
  109411. * @param onError is a callback called if an error occurs
  109412. */
  109413. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  109414. var onload = function () {
  109415. onSuccess();
  109416. };
  109417. var onerror = function (message, exception) {
  109418. onError(message, exception);
  109419. };
  109420. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  109421. };
  109422. return CubeTextureAssetTask;
  109423. }(AbstractAssetTask));
  109424. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  109425. /**
  109426. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  109427. */
  109428. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  109429. __extends(HDRCubeTextureAssetTask, _super);
  109430. /**
  109431. * Creates a new HDRCubeTextureAssetTask object
  109432. * @param name defines the name of the task
  109433. * @param url defines the location of the file to load
  109434. * @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.
  109435. * @param noMipmap defines if mipmaps should not be generated (default is false)
  109436. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  109437. * @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)
  109438. * @param reserved Internal use only
  109439. */
  109440. function HDRCubeTextureAssetTask(
  109441. /**
  109442. * Defines the name of the task
  109443. */
  109444. name,
  109445. /**
  109446. * Defines the location of the file to load
  109447. */
  109448. url,
  109449. /**
  109450. * Defines the desired size (the more it increases the longer the generation will be)
  109451. */
  109452. size,
  109453. /**
  109454. * Defines if mipmaps should not be generated (default is false)
  109455. */
  109456. noMipmap,
  109457. /**
  109458. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  109459. */
  109460. generateHarmonics,
  109461. /**
  109462. * 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)
  109463. */
  109464. gammaSpace,
  109465. /**
  109466. * Internal Use Only
  109467. */
  109468. reserved) {
  109469. if (noMipmap === void 0) { noMipmap = false; }
  109470. if (generateHarmonics === void 0) { generateHarmonics = true; }
  109471. if (gammaSpace === void 0) { gammaSpace = false; }
  109472. if (reserved === void 0) { reserved = false; }
  109473. var _this = _super.call(this, name) || this;
  109474. _this.name = name;
  109475. _this.url = url;
  109476. _this.size = size;
  109477. _this.noMipmap = noMipmap;
  109478. _this.generateHarmonics = generateHarmonics;
  109479. _this.gammaSpace = gammaSpace;
  109480. _this.reserved = reserved;
  109481. return _this;
  109482. }
  109483. /**
  109484. * Execute the current task
  109485. * @param scene defines the scene where you want your assets to be loaded
  109486. * @param onSuccess is a callback called when the task is successfully executed
  109487. * @param onError is a callback called if an error occurs
  109488. */
  109489. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  109490. var onload = function () {
  109491. onSuccess();
  109492. };
  109493. var onerror = function (message, exception) {
  109494. onError(message, exception);
  109495. };
  109496. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  109497. };
  109498. return HDRCubeTextureAssetTask;
  109499. }(AbstractAssetTask));
  109500. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  109501. /**
  109502. * This class can be used to easily import assets into a scene
  109503. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  109504. */
  109505. var AssetsManager = /** @class */ (function () {
  109506. /**
  109507. * Creates a new AssetsManager
  109508. * @param scene defines the scene to work on
  109509. */
  109510. function AssetsManager(scene) {
  109511. this._isLoading = false;
  109512. this._tasks = new Array();
  109513. this._waitingTasksCount = 0;
  109514. this._totalTasksCount = 0;
  109515. /**
  109516. * Observable called when all tasks are processed
  109517. */
  109518. this.onTaskSuccessObservable = new BABYLON.Observable();
  109519. /**
  109520. * Observable called when a task had an error
  109521. */
  109522. this.onTaskErrorObservable = new BABYLON.Observable();
  109523. /**
  109524. * Observable called when a task is successful
  109525. */
  109526. this.onTasksDoneObservable = new BABYLON.Observable();
  109527. /**
  109528. * Observable called when a task is done (whatever the result is)
  109529. */
  109530. this.onProgressObservable = new BABYLON.Observable();
  109531. /**
  109532. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  109533. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  109534. */
  109535. this.useDefaultLoadingScreen = true;
  109536. this._scene = scene;
  109537. }
  109538. /**
  109539. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  109540. * @param taskName defines the name of the new task
  109541. * @param meshesNames defines the name of meshes to load
  109542. * @param rootUrl defines the root url to use to locate files
  109543. * @param sceneFilename defines the filename of the scene file
  109544. * @returns a new {BABYLON.MeshAssetTask} object
  109545. */
  109546. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  109547. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  109548. this._tasks.push(task);
  109549. return task;
  109550. };
  109551. /**
  109552. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  109553. * @param taskName defines the name of the new task
  109554. * @param url defines the url of the file to load
  109555. * @returns a new {BABYLON.TextFileAssetTask} object
  109556. */
  109557. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  109558. var task = new TextFileAssetTask(taskName, url);
  109559. this._tasks.push(task);
  109560. return task;
  109561. };
  109562. /**
  109563. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  109564. * @param taskName defines the name of the new task
  109565. * @param url defines the url of the file to load
  109566. * @returns a new {BABYLON.BinaryFileAssetTask} object
  109567. */
  109568. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  109569. var task = new BinaryFileAssetTask(taskName, url);
  109570. this._tasks.push(task);
  109571. return task;
  109572. };
  109573. /**
  109574. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  109575. * @param taskName defines the name of the new task
  109576. * @param url defines the url of the file to load
  109577. * @returns a new {BABYLON.ImageAssetTask} object
  109578. */
  109579. AssetsManager.prototype.addImageTask = function (taskName, url) {
  109580. var task = new ImageAssetTask(taskName, url);
  109581. this._tasks.push(task);
  109582. return task;
  109583. };
  109584. /**
  109585. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  109586. * @param taskName defines the name of the new task
  109587. * @param url defines the url of the file to load
  109588. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  109589. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  109590. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  109591. * @returns a new {BABYLON.TextureAssetTask} object
  109592. */
  109593. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  109594. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  109595. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  109596. this._tasks.push(task);
  109597. return task;
  109598. };
  109599. /**
  109600. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  109601. * @param taskName defines the name of the new task
  109602. * @param url defines the url of the file to load
  109603. * @param extensions defines the extension to use to load the cube map (can be null)
  109604. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  109605. * @param files defines the list of files to load (can be null)
  109606. * @returns a new {BABYLON.CubeTextureAssetTask} object
  109607. */
  109608. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  109609. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  109610. this._tasks.push(task);
  109611. return task;
  109612. };
  109613. /**
  109614. *
  109615. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  109616. * @param taskName defines the name of the new task
  109617. * @param url defines the url of the file to load
  109618. * @param size defines the size you want for the cubemap (can be null)
  109619. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  109620. * @param generateHarmonics defines if you want to automatically generate (true by default)
  109621. * @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)
  109622. * @param reserved Internal use only
  109623. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  109624. */
  109625. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  109626. if (noMipmap === void 0) { noMipmap = false; }
  109627. if (generateHarmonics === void 0) { generateHarmonics = true; }
  109628. if (gammaSpace === void 0) { gammaSpace = false; }
  109629. if (reserved === void 0) { reserved = false; }
  109630. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  109631. this._tasks.push(task);
  109632. return task;
  109633. };
  109634. /**
  109635. * Remove a task from the assets manager.
  109636. * @param task the task to remove
  109637. */
  109638. AssetsManager.prototype.removeTask = function (task) {
  109639. var index = this._tasks.indexOf(task);
  109640. if (index > -1) {
  109641. this._tasks.splice(index, 1);
  109642. }
  109643. };
  109644. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  109645. this._waitingTasksCount--;
  109646. try {
  109647. if (this.onProgress) {
  109648. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  109649. }
  109650. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  109651. }
  109652. catch (e) {
  109653. BABYLON.Tools.Error("Error running progress callbacks.");
  109654. console.log(e);
  109655. }
  109656. if (this._waitingTasksCount === 0) {
  109657. try {
  109658. if (this.onFinish) {
  109659. this.onFinish(this._tasks);
  109660. }
  109661. // Let's remove successfull tasks
  109662. var currentTasks = this._tasks.slice();
  109663. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  109664. var task = currentTasks_1[_i];
  109665. if (task.taskState === AssetTaskState.DONE) {
  109666. var index = this._tasks.indexOf(task);
  109667. if (index > -1) {
  109668. this._tasks.splice(index, 1);
  109669. }
  109670. }
  109671. }
  109672. this.onTasksDoneObservable.notifyObservers(this._tasks);
  109673. }
  109674. catch (e) {
  109675. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  109676. console.log(e);
  109677. }
  109678. this._isLoading = false;
  109679. this._scene.getEngine().hideLoadingUI();
  109680. }
  109681. };
  109682. AssetsManager.prototype._runTask = function (task) {
  109683. var _this = this;
  109684. var done = function () {
  109685. try {
  109686. if (_this.onTaskSuccess) {
  109687. _this.onTaskSuccess(task);
  109688. }
  109689. _this.onTaskSuccessObservable.notifyObservers(task);
  109690. _this._decreaseWaitingTasksCount(task);
  109691. }
  109692. catch (e) {
  109693. error("Error executing task success callbacks", e);
  109694. }
  109695. };
  109696. var error = function (message, exception) {
  109697. task._setErrorObject(message, exception);
  109698. if (_this.onTaskError) {
  109699. _this.onTaskError(task);
  109700. }
  109701. _this.onTaskErrorObservable.notifyObservers(task);
  109702. _this._decreaseWaitingTasksCount(task);
  109703. };
  109704. task.run(this._scene, done, error);
  109705. };
  109706. /**
  109707. * Reset the {BABYLON.AssetsManager} and remove all tasks
  109708. * @return the current instance of the {BABYLON.AssetsManager}
  109709. */
  109710. AssetsManager.prototype.reset = function () {
  109711. this._isLoading = false;
  109712. this._tasks = new Array();
  109713. return this;
  109714. };
  109715. /**
  109716. * Start the loading process
  109717. * @return the current instance of the {BABYLON.AssetsManager}
  109718. */
  109719. AssetsManager.prototype.load = function () {
  109720. if (this._isLoading) {
  109721. return this;
  109722. }
  109723. this._isLoading = true;
  109724. this._waitingTasksCount = this._tasks.length;
  109725. this._totalTasksCount = this._tasks.length;
  109726. if (this._waitingTasksCount === 0) {
  109727. this._isLoading = false;
  109728. if (this.onFinish) {
  109729. this.onFinish(this._tasks);
  109730. }
  109731. this.onTasksDoneObservable.notifyObservers(this._tasks);
  109732. return this;
  109733. }
  109734. if (this.useDefaultLoadingScreen) {
  109735. this._scene.getEngine().displayLoadingUI();
  109736. }
  109737. for (var index = 0; index < this._tasks.length; index++) {
  109738. var task = this._tasks[index];
  109739. if (task.taskState === AssetTaskState.INIT) {
  109740. this._runTask(task);
  109741. }
  109742. }
  109743. return this;
  109744. };
  109745. return AssetsManager;
  109746. }());
  109747. BABYLON.AssetsManager = AssetsManager;
  109748. })(BABYLON || (BABYLON = {}));
  109749. //# sourceMappingURL=babylon.assetsManager.js.map
  109750. var BABYLON;
  109751. (function (BABYLON) {
  109752. var serializedGeometries = [];
  109753. var serializeGeometry = function (geometry, serializationGeometries) {
  109754. if (serializedGeometries[geometry.id]) {
  109755. return;
  109756. }
  109757. if (geometry.doNotSerialize) {
  109758. return;
  109759. }
  109760. if (geometry instanceof BABYLON.BoxGeometry) {
  109761. serializationGeometries.boxes.push(geometry.serialize());
  109762. }
  109763. else if (geometry instanceof BABYLON.SphereGeometry) {
  109764. serializationGeometries.spheres.push(geometry.serialize());
  109765. }
  109766. else if (geometry instanceof BABYLON.CylinderGeometry) {
  109767. serializationGeometries.cylinders.push(geometry.serialize());
  109768. }
  109769. else if (geometry instanceof BABYLON.TorusGeometry) {
  109770. serializationGeometries.toruses.push(geometry.serialize());
  109771. }
  109772. else if (geometry instanceof BABYLON.GroundGeometry) {
  109773. serializationGeometries.grounds.push(geometry.serialize());
  109774. }
  109775. else if (geometry instanceof BABYLON.Plane) {
  109776. serializationGeometries.planes.push(geometry.serialize());
  109777. }
  109778. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  109779. serializationGeometries.torusKnots.push(geometry.serialize());
  109780. }
  109781. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  109782. throw new Error("Unknown primitive type");
  109783. }
  109784. else {
  109785. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  109786. }
  109787. serializedGeometries[geometry.id] = true;
  109788. };
  109789. var serializeMesh = function (mesh, serializationScene) {
  109790. var serializationObject = {};
  109791. // Geometry
  109792. var geometry = mesh._geometry;
  109793. if (geometry) {
  109794. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  109795. // 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
  109796. serializeGeometry(geometry, serializationScene.geometries);
  109797. }
  109798. }
  109799. // Custom
  109800. if (mesh.serialize) {
  109801. mesh.serialize(serializationObject);
  109802. }
  109803. return serializationObject;
  109804. };
  109805. var finalizeSingleMesh = function (mesh, serializationObject) {
  109806. //only works if the mesh is already loaded
  109807. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  109808. //serialize material
  109809. if (mesh.material) {
  109810. if (mesh.material instanceof BABYLON.MultiMaterial) {
  109811. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  109812. serializationObject.materials = serializationObject.materials || [];
  109813. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  109814. serializationObject.multiMaterials.push(mesh.material.serialize());
  109815. var _loop_1 = function (submaterial) {
  109816. if (submaterial) {
  109817. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  109818. serializationObject.materials.push(submaterial.serialize());
  109819. }
  109820. }
  109821. };
  109822. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  109823. var submaterial = _a[_i];
  109824. _loop_1(submaterial);
  109825. }
  109826. }
  109827. }
  109828. else {
  109829. serializationObject.materials = serializationObject.materials || [];
  109830. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  109831. serializationObject.materials.push(mesh.material.serialize());
  109832. }
  109833. }
  109834. }
  109835. //serialize geometry
  109836. var geometry = mesh._geometry;
  109837. if (geometry) {
  109838. if (!serializationObject.geometries) {
  109839. serializationObject.geometries = {};
  109840. serializationObject.geometries.boxes = [];
  109841. serializationObject.geometries.spheres = [];
  109842. serializationObject.geometries.cylinders = [];
  109843. serializationObject.geometries.toruses = [];
  109844. serializationObject.geometries.grounds = [];
  109845. serializationObject.geometries.planes = [];
  109846. serializationObject.geometries.torusKnots = [];
  109847. serializationObject.geometries.vertexData = [];
  109848. }
  109849. serializeGeometry(geometry, serializationObject.geometries);
  109850. }
  109851. // Skeletons
  109852. if (mesh.skeleton) {
  109853. serializationObject.skeletons = serializationObject.skeletons || [];
  109854. serializationObject.skeletons.push(mesh.skeleton.serialize());
  109855. }
  109856. //serialize the actual mesh
  109857. serializationObject.meshes = serializationObject.meshes || [];
  109858. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  109859. }
  109860. };
  109861. /**
  109862. * Class used to serialize a scene into a string
  109863. */
  109864. var SceneSerializer = /** @class */ (function () {
  109865. function SceneSerializer() {
  109866. }
  109867. /**
  109868. * Clear cache used by a previous serialization
  109869. */
  109870. SceneSerializer.ClearCache = function () {
  109871. serializedGeometries = [];
  109872. };
  109873. /**
  109874. * Serialize a scene into a JSON compatible object
  109875. * @param scene defines the scene to serialize
  109876. * @returns a JSON compatible object
  109877. */
  109878. SceneSerializer.Serialize = function (scene) {
  109879. var serializationObject = {};
  109880. SceneSerializer.ClearCache();
  109881. // Scene
  109882. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  109883. serializationObject.autoClear = scene.autoClear;
  109884. serializationObject.clearColor = scene.clearColor.asArray();
  109885. serializationObject.ambientColor = scene.ambientColor.asArray();
  109886. serializationObject.gravity = scene.gravity.asArray();
  109887. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  109888. serializationObject.workerCollisions = scene.workerCollisions;
  109889. // Fog
  109890. if (scene.fogMode && scene.fogMode !== 0) {
  109891. serializationObject.fogMode = scene.fogMode;
  109892. serializationObject.fogColor = scene.fogColor.asArray();
  109893. serializationObject.fogStart = scene.fogStart;
  109894. serializationObject.fogEnd = scene.fogEnd;
  109895. serializationObject.fogDensity = scene.fogDensity;
  109896. }
  109897. //Physics
  109898. if (scene.isPhysicsEnabled()) {
  109899. var physicEngine = scene.getPhysicsEngine();
  109900. if (physicEngine) {
  109901. serializationObject.physicsEnabled = true;
  109902. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  109903. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  109904. }
  109905. }
  109906. // Metadata
  109907. if (scene.metadata) {
  109908. serializationObject.metadata = scene.metadata;
  109909. }
  109910. // Morph targets
  109911. serializationObject.morphTargetManagers = [];
  109912. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  109913. var abstractMesh = _a[_i];
  109914. var manager = abstractMesh.morphTargetManager;
  109915. if (manager) {
  109916. serializationObject.morphTargetManagers.push(manager.serialize());
  109917. }
  109918. }
  109919. // Lights
  109920. serializationObject.lights = [];
  109921. var index;
  109922. var light;
  109923. for (index = 0; index < scene.lights.length; index++) {
  109924. light = scene.lights[index];
  109925. if (!light.doNotSerialize) {
  109926. serializationObject.lights.push(light.serialize());
  109927. }
  109928. }
  109929. // Cameras
  109930. serializationObject.cameras = [];
  109931. for (index = 0; index < scene.cameras.length; index++) {
  109932. var camera = scene.cameras[index];
  109933. if (!camera.doNotSerialize) {
  109934. serializationObject.cameras.push(camera.serialize());
  109935. }
  109936. }
  109937. if (scene.activeCamera) {
  109938. serializationObject.activeCameraID = scene.activeCamera.id;
  109939. }
  109940. // Animations
  109941. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  109942. // Materials
  109943. serializationObject.materials = [];
  109944. serializationObject.multiMaterials = [];
  109945. var material;
  109946. for (index = 0; index < scene.materials.length; index++) {
  109947. material = scene.materials[index];
  109948. if (!material.doNotSerialize) {
  109949. serializationObject.materials.push(material.serialize());
  109950. }
  109951. }
  109952. // MultiMaterials
  109953. serializationObject.multiMaterials = [];
  109954. for (index = 0; index < scene.multiMaterials.length; index++) {
  109955. var multiMaterial = scene.multiMaterials[index];
  109956. serializationObject.multiMaterials.push(multiMaterial.serialize());
  109957. }
  109958. // Environment texture
  109959. if (scene.environmentTexture) {
  109960. serializationObject.environmentTexture = scene.environmentTexture.name;
  109961. }
  109962. // Skeletons
  109963. serializationObject.skeletons = [];
  109964. for (index = 0; index < scene.skeletons.length; index++) {
  109965. var skeleton = scene.skeletons[index];
  109966. if (!skeleton.doNotSerialize) {
  109967. serializationObject.skeletons.push(skeleton.serialize());
  109968. }
  109969. }
  109970. // Transform nodes
  109971. serializationObject.transformNodes = [];
  109972. for (index = 0; index < scene.transformNodes.length; index++) {
  109973. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  109974. }
  109975. // Geometries
  109976. serializationObject.geometries = {};
  109977. serializationObject.geometries.boxes = [];
  109978. serializationObject.geometries.spheres = [];
  109979. serializationObject.geometries.cylinders = [];
  109980. serializationObject.geometries.toruses = [];
  109981. serializationObject.geometries.grounds = [];
  109982. serializationObject.geometries.planes = [];
  109983. serializationObject.geometries.torusKnots = [];
  109984. serializationObject.geometries.vertexData = [];
  109985. serializedGeometries = [];
  109986. var geometries = scene.getGeometries();
  109987. for (index = 0; index < geometries.length; index++) {
  109988. var geometry = geometries[index];
  109989. if (geometry.isReady()) {
  109990. serializeGeometry(geometry, serializationObject.geometries);
  109991. }
  109992. }
  109993. // Meshes
  109994. serializationObject.meshes = [];
  109995. for (index = 0; index < scene.meshes.length; index++) {
  109996. var abstractMesh = scene.meshes[index];
  109997. if (abstractMesh instanceof BABYLON.Mesh) {
  109998. var mesh = abstractMesh;
  109999. if (!mesh.doNotSerialize) {
  110000. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  110001. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  110002. }
  110003. }
  110004. }
  110005. }
  110006. // Particles Systems
  110007. serializationObject.particleSystems = [];
  110008. for (index = 0; index < scene.particleSystems.length; index++) {
  110009. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  110010. }
  110011. // Action Manager
  110012. if (scene.actionManager) {
  110013. serializationObject.actions = scene.actionManager.serialize("scene");
  110014. }
  110015. // Components
  110016. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  110017. var component = _c[_b];
  110018. component.serialize(serializationObject);
  110019. }
  110020. return serializationObject;
  110021. };
  110022. /**
  110023. * Serialize a mesh into a JSON compatible object
  110024. * @param toSerialize defines the mesh to serialize
  110025. * @param withParents defines if parents must be serialized as well
  110026. * @param withChildren defines if children must be serialized as well
  110027. * @returns a JSON compatible object
  110028. */
  110029. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  110030. if (withParents === void 0) { withParents = false; }
  110031. if (withChildren === void 0) { withChildren = false; }
  110032. var serializationObject = {};
  110033. SceneSerializer.ClearCache();
  110034. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  110035. if (withParents || withChildren) {
  110036. //deliberate for loop! not for each, appended should be processed as well.
  110037. for (var i = 0; i < toSerialize.length; ++i) {
  110038. if (withChildren) {
  110039. toSerialize[i].getDescendants().forEach(function (node) {
  110040. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  110041. toSerialize.push(node);
  110042. }
  110043. });
  110044. }
  110045. //make sure the array doesn't contain the object already
  110046. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  110047. toSerialize.push(toSerialize[i].parent);
  110048. }
  110049. }
  110050. }
  110051. toSerialize.forEach(function (mesh) {
  110052. finalizeSingleMesh(mesh, serializationObject);
  110053. });
  110054. return serializationObject;
  110055. };
  110056. return SceneSerializer;
  110057. }());
  110058. BABYLON.SceneSerializer = SceneSerializer;
  110059. })(BABYLON || (BABYLON = {}));
  110060. //# sourceMappingURL=babylon.sceneSerializer.js.map
  110061. var BABYLON;
  110062. (function (BABYLON) {
  110063. /**
  110064. * Class used to generate realtime reflection / refraction cube textures
  110065. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  110066. */
  110067. var ReflectionProbe = /** @class */ (function () {
  110068. /**
  110069. * Creates a new reflection probe
  110070. * @param name defines the name of the probe
  110071. * @param size defines the texture resolution (for each face)
  110072. * @param scene defines the hosting scene
  110073. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  110074. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  110075. */
  110076. function ReflectionProbe(
  110077. /** defines the name of the probe */
  110078. name, size, scene, generateMipMaps, useFloat) {
  110079. if (generateMipMaps === void 0) { generateMipMaps = true; }
  110080. if (useFloat === void 0) { useFloat = false; }
  110081. var _this = this;
  110082. this.name = name;
  110083. this._viewMatrix = BABYLON.Matrix.Identity();
  110084. this._target = BABYLON.Vector3.Zero();
  110085. this._add = BABYLON.Vector3.Zero();
  110086. this._invertYAxis = false;
  110087. /** Gets or sets probe position (center of the cube map) */
  110088. this.position = BABYLON.Vector3.Zero();
  110089. this._scene = scene;
  110090. // Create the scene field if not exist.
  110091. if (!this._scene.reflectionProbes) {
  110092. this._scene.reflectionProbes = new Array();
  110093. }
  110094. this._scene.reflectionProbes.push(this);
  110095. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  110096. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  110097. switch (faceIndex) {
  110098. case 0:
  110099. _this._add.copyFromFloats(1, 0, 0);
  110100. break;
  110101. case 1:
  110102. _this._add.copyFromFloats(-1, 0, 0);
  110103. break;
  110104. case 2:
  110105. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  110106. break;
  110107. case 3:
  110108. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  110109. break;
  110110. case 4:
  110111. _this._add.copyFromFloats(0, 0, 1);
  110112. break;
  110113. case 5:
  110114. _this._add.copyFromFloats(0, 0, -1);
  110115. break;
  110116. }
  110117. if (_this._attachedMesh) {
  110118. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  110119. }
  110120. _this.position.addToRef(_this._add, _this._target);
  110121. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  110122. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  110123. scene._forcedViewPosition = _this.position;
  110124. });
  110125. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  110126. scene._forcedViewPosition = null;
  110127. scene.updateTransformMatrix(true);
  110128. });
  110129. if (scene.activeCamera) {
  110130. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  110131. }
  110132. }
  110133. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  110134. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  110135. get: function () {
  110136. return this._renderTargetTexture.samples;
  110137. },
  110138. set: function (value) {
  110139. this._renderTargetTexture.samples = value;
  110140. },
  110141. enumerable: true,
  110142. configurable: true
  110143. });
  110144. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  110145. /** Gets or sets the refresh rate to use (on every frame by default) */
  110146. get: function () {
  110147. return this._renderTargetTexture.refreshRate;
  110148. },
  110149. set: function (value) {
  110150. this._renderTargetTexture.refreshRate = value;
  110151. },
  110152. enumerable: true,
  110153. configurable: true
  110154. });
  110155. /**
  110156. * Gets the hosting scene
  110157. * @returns a Scene
  110158. */
  110159. ReflectionProbe.prototype.getScene = function () {
  110160. return this._scene;
  110161. };
  110162. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  110163. /** Gets the internal CubeTexture used to render to */
  110164. get: function () {
  110165. return this._renderTargetTexture;
  110166. },
  110167. enumerable: true,
  110168. configurable: true
  110169. });
  110170. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  110171. /** Gets the list of meshes to render */
  110172. get: function () {
  110173. return this._renderTargetTexture.renderList;
  110174. },
  110175. enumerable: true,
  110176. configurable: true
  110177. });
  110178. /**
  110179. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  110180. * @param mesh defines the mesh to attach to
  110181. */
  110182. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  110183. this._attachedMesh = mesh;
  110184. };
  110185. /**
  110186. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  110187. * @param renderingGroupId The rendering group id corresponding to its index
  110188. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  110189. */
  110190. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  110191. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  110192. };
  110193. /**
  110194. * Clean all associated resources
  110195. */
  110196. ReflectionProbe.prototype.dispose = function () {
  110197. var index = this._scene.reflectionProbes.indexOf(this);
  110198. if (index !== -1) {
  110199. // Remove from the scene if found
  110200. this._scene.reflectionProbes.splice(index, 1);
  110201. }
  110202. if (this._renderTargetTexture) {
  110203. this._renderTargetTexture.dispose();
  110204. this._renderTargetTexture = null;
  110205. }
  110206. };
  110207. return ReflectionProbe;
  110208. }());
  110209. BABYLON.ReflectionProbe = ReflectionProbe;
  110210. })(BABYLON || (BABYLON = {}));
  110211. //# sourceMappingURL=babylon.reflectionProbe.js.map
  110212. var BABYLON;
  110213. (function (BABYLON) {
  110214. /**
  110215. * Defines the layer scene component responsible to manage any layers
  110216. * in a given scene.
  110217. */
  110218. var LayerSceneComponent = /** @class */ (function () {
  110219. /**
  110220. * Creates a new instance of the component for the given scene
  110221. * @param scene Defines the scene to register the component in
  110222. */
  110223. function LayerSceneComponent(scene) {
  110224. /**
  110225. * The component name helpfull to identify the component in the list of scene components.
  110226. */
  110227. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  110228. this.scene = scene;
  110229. this._engine = scene.getEngine();
  110230. scene.layers = new Array();
  110231. }
  110232. /**
  110233. * Registers the component in a given scene
  110234. */
  110235. LayerSceneComponent.prototype.register = function () {
  110236. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  110237. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  110238. };
  110239. /**
  110240. * Rebuilds the elements related to this component in case of
  110241. * context lost for instance.
  110242. */
  110243. LayerSceneComponent.prototype.rebuild = function () {
  110244. var layers = this.scene.layers;
  110245. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  110246. var layer = layers_1[_i];
  110247. layer._rebuild();
  110248. }
  110249. };
  110250. /**
  110251. * Disposes the component and the associated ressources.
  110252. */
  110253. LayerSceneComponent.prototype.dispose = function () {
  110254. var layers = this.scene.layers;
  110255. while (layers.length) {
  110256. layers[0].dispose();
  110257. }
  110258. };
  110259. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  110260. var layers = this.scene.layers;
  110261. if (layers.length) {
  110262. this._engine.setDepthBuffer(false);
  110263. var cameraLayerMask = camera.layerMask;
  110264. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  110265. var layer = layers_2[_i];
  110266. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  110267. layer.render();
  110268. }
  110269. }
  110270. this._engine.setDepthBuffer(true);
  110271. }
  110272. };
  110273. LayerSceneComponent.prototype._drawBackground = function (camera) {
  110274. this._draw(camera, true);
  110275. };
  110276. LayerSceneComponent.prototype._drawForeground = function (camera) {
  110277. this._draw(camera, false);
  110278. };
  110279. return LayerSceneComponent;
  110280. }());
  110281. BABYLON.LayerSceneComponent = LayerSceneComponent;
  110282. })(BABYLON || (BABYLON = {}));
  110283. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  110284. var BABYLON;
  110285. (function (BABYLON) {
  110286. /**
  110287. * This represents a full screen 2d layer.
  110288. * This can be usefull to display a picture in the background of your scene for instance.
  110289. * @see https://www.babylonjs-playground.com/#08A2BS#1
  110290. */
  110291. var Layer = /** @class */ (function () {
  110292. /**
  110293. * Instantiates a new layer.
  110294. * This represents a full screen 2d layer.
  110295. * This can be usefull to display a picture in the background of your scene for instance.
  110296. * @see https://www.babylonjs-playground.com/#08A2BS#1
  110297. * @param name Define the name of the layer in the scene
  110298. * @param imgUrl Define the url of the texture to display in the layer
  110299. * @param scene Define the scene the layer belongs to
  110300. * @param isBackground Defines whether the layer is displayed in front or behind the scene
  110301. * @param color Defines a color for the layer
  110302. */
  110303. function Layer(
  110304. /**
  110305. * Define the name of the layer.
  110306. */
  110307. name, imgUrl, scene, isBackground, color) {
  110308. this.name = name;
  110309. /**
  110310. * Define the scale of the layer in order to zoom in out of the texture.
  110311. */
  110312. this.scale = new BABYLON.Vector2(1, 1);
  110313. /**
  110314. * Define an offset for the layer in order to shift the texture.
  110315. */
  110316. this.offset = new BABYLON.Vector2(0, 0);
  110317. /**
  110318. * Define the alpha blending mode used in the layer in case the texture or color has an alpha.
  110319. */
  110320. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  110321. /**
  110322. * Define a mask to restrict the layer to only some of the scene cameras.
  110323. */
  110324. this.layerMask = 0x0FFFFFFF;
  110325. this._vertexBuffers = {};
  110326. /**
  110327. * An event triggered when the layer is disposed.
  110328. */
  110329. this.onDisposeObservable = new BABYLON.Observable();
  110330. /**
  110331. * An event triggered before rendering the scene
  110332. */
  110333. this.onBeforeRenderObservable = new BABYLON.Observable();
  110334. /**
  110335. * An event triggered after rendering the scene
  110336. */
  110337. this.onAfterRenderObservable = new BABYLON.Observable();
  110338. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  110339. this.isBackground = isBackground === undefined ? true : isBackground;
  110340. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  110341. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  110342. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  110343. if (!layerComponent) {
  110344. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  110345. this._scene._addComponent(layerComponent);
  110346. }
  110347. this._scene.layers.push(this);
  110348. var engine = this._scene.getEngine();
  110349. // VBO
  110350. var vertices = [];
  110351. vertices.push(1, 1);
  110352. vertices.push(-1, 1);
  110353. vertices.push(-1, -1);
  110354. vertices.push(1, -1);
  110355. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  110356. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  110357. this._createIndexBuffer();
  110358. // Effects
  110359. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  110360. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  110361. }
  110362. Object.defineProperty(Layer.prototype, "onDispose", {
  110363. /**
  110364. * Back compatibility with callback before the onDisposeObservable existed.
  110365. * The set callback will be triggered when the layer has been disposed.
  110366. */
  110367. set: function (callback) {
  110368. if (this._onDisposeObserver) {
  110369. this.onDisposeObservable.remove(this._onDisposeObserver);
  110370. }
  110371. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  110372. },
  110373. enumerable: true,
  110374. configurable: true
  110375. });
  110376. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  110377. /**
  110378. * Back compatibility with callback before the onBeforeRenderObservable existed.
  110379. * The set callback will be triggered just before rendering the layer.
  110380. */
  110381. set: function (callback) {
  110382. if (this._onBeforeRenderObserver) {
  110383. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  110384. }
  110385. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  110386. },
  110387. enumerable: true,
  110388. configurable: true
  110389. });
  110390. Object.defineProperty(Layer.prototype, "onAfterRender", {
  110391. /**
  110392. * Back compatibility with callback before the onAfterRenderObservable existed.
  110393. * The set callback will be triggered just after rendering the layer.
  110394. */
  110395. set: function (callback) {
  110396. if (this._onAfterRenderObserver) {
  110397. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  110398. }
  110399. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  110400. },
  110401. enumerable: true,
  110402. configurable: true
  110403. });
  110404. Layer.prototype._createIndexBuffer = function () {
  110405. var engine = this._scene.getEngine();
  110406. // Indices
  110407. var indices = [];
  110408. indices.push(0);
  110409. indices.push(1);
  110410. indices.push(2);
  110411. indices.push(0);
  110412. indices.push(2);
  110413. indices.push(3);
  110414. this._indexBuffer = engine.createIndexBuffer(indices);
  110415. };
  110416. /** @hidden */
  110417. Layer.prototype._rebuild = function () {
  110418. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  110419. if (vb) {
  110420. vb._rebuild();
  110421. }
  110422. this._createIndexBuffer();
  110423. };
  110424. /**
  110425. * Renders the layer in the scene.
  110426. */
  110427. Layer.prototype.render = function () {
  110428. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  110429. // Check
  110430. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  110431. return;
  110432. var engine = this._scene.getEngine();
  110433. this.onBeforeRenderObservable.notifyObservers(this);
  110434. // Render
  110435. engine.enableEffect(currentEffect);
  110436. engine.setState(false);
  110437. // Texture
  110438. currentEffect.setTexture("textureSampler", this.texture);
  110439. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  110440. // Color
  110441. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  110442. // Scale / offset
  110443. currentEffect.setVector2("offset", this.offset);
  110444. currentEffect.setVector2("scale", this.scale);
  110445. // VBOs
  110446. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  110447. // Draw order
  110448. if (!this.alphaTest) {
  110449. engine.setAlphaMode(this.alphaBlendingMode);
  110450. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  110451. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  110452. }
  110453. else {
  110454. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  110455. }
  110456. this.onAfterRenderObservable.notifyObservers(this);
  110457. };
  110458. /**
  110459. * Disposes and releases the associated ressources.
  110460. */
  110461. Layer.prototype.dispose = function () {
  110462. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  110463. if (vertexBuffer) {
  110464. vertexBuffer.dispose();
  110465. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  110466. }
  110467. if (this._indexBuffer) {
  110468. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  110469. this._indexBuffer = null;
  110470. }
  110471. if (this.texture) {
  110472. this.texture.dispose();
  110473. this.texture = null;
  110474. }
  110475. // Remove from scene
  110476. var index = this._scene.layers.indexOf(this);
  110477. this._scene.layers.splice(index, 1);
  110478. // Callback
  110479. this.onDisposeObservable.notifyObservers(this);
  110480. this.onDisposeObservable.clear();
  110481. this.onAfterRenderObservable.clear();
  110482. this.onBeforeRenderObservable.clear();
  110483. };
  110484. return Layer;
  110485. }());
  110486. BABYLON.Layer = Layer;
  110487. })(BABYLON || (BABYLON = {}));
  110488. //# sourceMappingURL=babylon.layer.js.map
  110489. var BABYLON;
  110490. (function (BABYLON) {
  110491. /**
  110492. * Class used to host texture specific utilities
  110493. */
  110494. var TextureTools = /** @class */ (function () {
  110495. function TextureTools() {
  110496. }
  110497. /**
  110498. * Uses the GPU to create a copy texture rescaled at a given size
  110499. * @param texture Texture to copy from
  110500. * @param width defines the desired width
  110501. * @param height defines the desired height
  110502. * @param useBilinearMode defines if bilinear mode has to be used
  110503. * @return the generated texture
  110504. */
  110505. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  110506. if (useBilinearMode === void 0) { useBilinearMode = true; }
  110507. var scene = texture.getScene();
  110508. var engine = scene.getEngine();
  110509. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  110510. rtt.wrapU = texture.wrapU;
  110511. rtt.wrapV = texture.wrapV;
  110512. rtt.uOffset = texture.uOffset;
  110513. rtt.vOffset = texture.vOffset;
  110514. rtt.uScale = texture.uScale;
  110515. rtt.vScale = texture.vScale;
  110516. rtt.uAng = texture.uAng;
  110517. rtt.vAng = texture.vAng;
  110518. rtt.wAng = texture.wAng;
  110519. rtt.coordinatesIndex = texture.coordinatesIndex;
  110520. rtt.level = texture.level;
  110521. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  110522. rtt._texture.isReady = false;
  110523. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110524. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110525. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  110526. passPostProcess.getEffect().executeWhenCompiled(function () {
  110527. passPostProcess.onApply = function (effect) {
  110528. effect.setTexture("textureSampler", texture);
  110529. };
  110530. var internalTexture = rtt.getInternalTexture();
  110531. if (internalTexture) {
  110532. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  110533. engine.unBindFramebuffer(internalTexture);
  110534. rtt.disposeFramebufferObjects();
  110535. passPostProcess.dispose();
  110536. internalTexture.isReady = true;
  110537. }
  110538. });
  110539. return rtt;
  110540. };
  110541. /**
  110542. * Gets an environment BRDF texture for a given scene
  110543. * @param scene defines the hosting scene
  110544. * @returns the environment BRDF texture
  110545. */
  110546. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  110547. if (!scene._environmentBRDFTexture) {
  110548. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  110549. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110550. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110551. scene._environmentBRDFTexture = texture;
  110552. }
  110553. return scene._environmentBRDFTexture;
  110554. };
  110555. 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=";
  110556. return TextureTools;
  110557. }());
  110558. BABYLON.TextureTools = TextureTools;
  110559. })(BABYLON || (BABYLON = {}));
  110560. //# sourceMappingURL=babylon.textureTools.js.map
  110561. var BABYLON;
  110562. (function (BABYLON) {
  110563. /**
  110564. * The framing behavior (BABYLON.FramingBehavior) is designed to automatically position an ArcRotateCamera when its target is set to a mesh. It is also useful if you want to prevent the camera to go under a virtual horizontal plane.
  110565. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  110566. */
  110567. var FramingBehavior = /** @class */ (function () {
  110568. function FramingBehavior() {
  110569. this._mode = FramingBehavior.FitFrustumSidesMode;
  110570. this._radiusScale = 1.0;
  110571. this._positionScale = 0.5;
  110572. this._defaultElevation = 0.3;
  110573. this._elevationReturnTime = 1500;
  110574. this._elevationReturnWaitTime = 1000;
  110575. this._zoomStopsAnimation = false;
  110576. this._framingTime = 1500;
  110577. /**
  110578. * Define if the behavior should automatically change the configured
  110579. * camera limits and sensibilities.
  110580. */
  110581. this.autoCorrectCameraLimitsAndSensibility = true;
  110582. this._isPointerDown = false;
  110583. this._lastInteractionTime = -Infinity;
  110584. // Framing control
  110585. this._animatables = new Array();
  110586. this._betaIsAnimating = false;
  110587. }
  110588. Object.defineProperty(FramingBehavior.prototype, "name", {
  110589. /**
  110590. * Gets the name of the behavior.
  110591. */
  110592. get: function () {
  110593. return "Framing";
  110594. },
  110595. enumerable: true,
  110596. configurable: true
  110597. });
  110598. Object.defineProperty(FramingBehavior.prototype, "mode", {
  110599. /**
  110600. * Gets current mode used by the behavior.
  110601. */
  110602. get: function () {
  110603. return this._mode;
  110604. },
  110605. /**
  110606. * Sets the current mode used by the behavior
  110607. */
  110608. set: function (mode) {
  110609. this._mode = mode;
  110610. },
  110611. enumerable: true,
  110612. configurable: true
  110613. });
  110614. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  110615. /**
  110616. * Gets the scale applied to the radius
  110617. */
  110618. get: function () {
  110619. return this._radiusScale;
  110620. },
  110621. /**
  110622. * Sets the scale applied to the radius (1 by default)
  110623. */
  110624. set: function (radius) {
  110625. this._radiusScale = radius;
  110626. },
  110627. enumerable: true,
  110628. configurable: true
  110629. });
  110630. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  110631. /**
  110632. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  110633. */
  110634. get: function () {
  110635. return this._positionScale;
  110636. },
  110637. /**
  110638. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  110639. */
  110640. set: function (scale) {
  110641. this._positionScale = scale;
  110642. },
  110643. enumerable: true,
  110644. configurable: true
  110645. });
  110646. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  110647. /**
  110648. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  110649. * behaviour is triggered, in radians.
  110650. */
  110651. get: function () {
  110652. return this._defaultElevation;
  110653. },
  110654. /**
  110655. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  110656. * behaviour is triggered, in radians.
  110657. */
  110658. set: function (elevation) {
  110659. this._defaultElevation = elevation;
  110660. },
  110661. enumerable: true,
  110662. configurable: true
  110663. });
  110664. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  110665. /**
  110666. * Gets the time (in milliseconds) taken to return to the default beta position.
  110667. * Negative value indicates camera should not return to default.
  110668. */
  110669. get: function () {
  110670. return this._elevationReturnTime;
  110671. },
  110672. /**
  110673. * Sets the time (in milliseconds) taken to return to the default beta position.
  110674. * Negative value indicates camera should not return to default.
  110675. */
  110676. set: function (speed) {
  110677. this._elevationReturnTime = speed;
  110678. },
  110679. enumerable: true,
  110680. configurable: true
  110681. });
  110682. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  110683. /**
  110684. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  110685. */
  110686. get: function () {
  110687. return this._elevationReturnWaitTime;
  110688. },
  110689. /**
  110690. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  110691. */
  110692. set: function (time) {
  110693. this._elevationReturnWaitTime = time;
  110694. },
  110695. enumerable: true,
  110696. configurable: true
  110697. });
  110698. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  110699. /**
  110700. * Gets the flag that indicates if user zooming should stop animation.
  110701. */
  110702. get: function () {
  110703. return this._zoomStopsAnimation;
  110704. },
  110705. /**
  110706. * Sets the flag that indicates if user zooming should stop animation.
  110707. */
  110708. set: function (flag) {
  110709. this._zoomStopsAnimation = flag;
  110710. },
  110711. enumerable: true,
  110712. configurable: true
  110713. });
  110714. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  110715. /**
  110716. * Gets the transition time when framing the mesh, in milliseconds
  110717. */
  110718. get: function () {
  110719. return this._framingTime;
  110720. },
  110721. /**
  110722. * Sets the transition time when framing the mesh, in milliseconds
  110723. */
  110724. set: function (time) {
  110725. this._framingTime = time;
  110726. },
  110727. enumerable: true,
  110728. configurable: true
  110729. });
  110730. /**
  110731. * Initializes the behavior.
  110732. */
  110733. FramingBehavior.prototype.init = function () {
  110734. // Do notihng
  110735. };
  110736. /**
  110737. * Attaches the behavior to its arc rotate camera.
  110738. * @param camera Defines the camera to attach the behavior to
  110739. */
  110740. FramingBehavior.prototype.attach = function (camera) {
  110741. var _this = this;
  110742. this._attachedCamera = camera;
  110743. var scene = this._attachedCamera.getScene();
  110744. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  110745. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  110746. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  110747. _this._isPointerDown = true;
  110748. return;
  110749. }
  110750. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  110751. _this._isPointerDown = false;
  110752. }
  110753. });
  110754. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  110755. if (mesh) {
  110756. _this.zoomOnMesh(mesh);
  110757. }
  110758. });
  110759. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  110760. // Stop the animation if there is user interaction and the animation should stop for this interaction
  110761. _this._applyUserInteraction();
  110762. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  110763. // back to the default position after a given timeout
  110764. _this._maintainCameraAboveGround();
  110765. });
  110766. };
  110767. /**
  110768. * Detaches the behavior from its current arc rotate camera.
  110769. */
  110770. FramingBehavior.prototype.detach = function () {
  110771. if (!this._attachedCamera) {
  110772. return;
  110773. }
  110774. var scene = this._attachedCamera.getScene();
  110775. if (this._onPrePointerObservableObserver) {
  110776. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  110777. }
  110778. if (this._onAfterCheckInputsObserver) {
  110779. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  110780. }
  110781. if (this._onMeshTargetChangedObserver) {
  110782. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  110783. }
  110784. this._attachedCamera = null;
  110785. };
  110786. /**
  110787. * Targets the given mesh and updates zoom level accordingly.
  110788. * @param mesh The mesh to target.
  110789. * @param radius Optional. If a cached radius position already exists, overrides default.
  110790. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  110791. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  110792. * @param onAnimationEnd Callback triggered at the end of the framing animation
  110793. */
  110794. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  110795. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  110796. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  110797. mesh.computeWorldMatrix(true);
  110798. var boundingBox = mesh.getBoundingInfo().boundingBox;
  110799. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  110800. };
  110801. /**
  110802. * Targets the given mesh with its children and updates zoom level accordingly.
  110803. * @param mesh The mesh to target.
  110804. * @param radius Optional. If a cached radius position already exists, overrides default.
  110805. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  110806. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  110807. * @param onAnimationEnd Callback triggered at the end of the framing animation
  110808. */
  110809. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  110810. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  110811. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  110812. mesh.computeWorldMatrix(true);
  110813. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  110814. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  110815. };
  110816. /**
  110817. * Targets the given meshes with their children and updates zoom level accordingly.
  110818. * @param meshes The mesh to target.
  110819. * @param radius Optional. If a cached radius position already exists, overrides default.
  110820. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  110821. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  110822. * @param onAnimationEnd Callback triggered at the end of the framing animation
  110823. */
  110824. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  110825. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  110826. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  110827. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  110828. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  110829. for (var i = 0; i < meshes.length; i++) {
  110830. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  110831. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  110832. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  110833. }
  110834. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  110835. };
  110836. /**
  110837. * Targets the bounding box info defined by its extends and updates zoom level accordingly.
  110838. * @param minimumWorld Determines the smaller position of the bounding box extend
  110839. * @param maximumWorld Determines the bigger position of the bounding box extend
  110840. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  110841. * @param onAnimationEnd Callback triggered at the end of the framing animation
  110842. */
  110843. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  110844. var _this = this;
  110845. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  110846. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  110847. var zoomTarget;
  110848. if (!this._attachedCamera) {
  110849. return;
  110850. }
  110851. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  110852. var bottom = minimumWorld.y;
  110853. var top = maximumWorld.y;
  110854. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  110855. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  110856. if (focusOnOriginXZ) {
  110857. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  110858. }
  110859. else {
  110860. var centerWorld = minimumWorld.add(radiusWorld);
  110861. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  110862. }
  110863. if (!this._vectorTransition) {
  110864. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  110865. }
  110866. this._betaIsAnimating = true;
  110867. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  110868. if (animatable) {
  110869. this._animatables.push(animatable);
  110870. }
  110871. // sets the radius and lower radius bounds
  110872. // Small delta ensures camera is not always at lower zoom limit.
  110873. var radius = 0;
  110874. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  110875. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  110876. if (this.autoCorrectCameraLimitsAndSensibility) {
  110877. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  110878. }
  110879. radius = position;
  110880. }
  110881. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  110882. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  110883. if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) {
  110884. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  110885. }
  110886. }
  110887. // Set sensibilities
  110888. if (this.autoCorrectCameraLimitsAndSensibility) {
  110889. var extend = maximumWorld.subtract(minimumWorld).length();
  110890. this._attachedCamera.panningSensibility = 5000 / extend;
  110891. this._attachedCamera.wheelPrecision = 100 / radius;
  110892. }
  110893. // transition to new radius
  110894. if (!this._radiusTransition) {
  110895. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  110896. }
  110897. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  110898. _this.stopAllAnimations();
  110899. if (onAnimationEnd) {
  110900. onAnimationEnd();
  110901. }
  110902. if (_this._attachedCamera && _this._attachedCamera.useInputToRestoreState) {
  110903. _this._attachedCamera.storeState();
  110904. }
  110905. });
  110906. if (animatable) {
  110907. this._animatables.push(animatable);
  110908. }
  110909. };
  110910. /**
  110911. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  110912. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  110913. * frustum width.
  110914. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  110915. * to fully enclose the mesh in the viewing frustum.
  110916. */
  110917. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  110918. var size = maximumWorld.subtract(minimumWorld);
  110919. var boxVectorGlobalDiagonal = size.length();
  110920. var frustumSlope = this._getFrustumSlope();
  110921. // Formula for setting distance
  110922. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  110923. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  110924. // Horizon distance
  110925. var radius = radiusWithoutFraming * this._radiusScale;
  110926. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  110927. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  110928. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  110929. var camera = this._attachedCamera;
  110930. if (!camera) {
  110931. return 0;
  110932. }
  110933. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  110934. // Don't exceed the requested limit
  110935. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  110936. }
  110937. // Don't exceed the upper radius limit
  110938. if (camera.upperRadiusLimit) {
  110939. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  110940. }
  110941. return distance;
  110942. };
  110943. /**
  110944. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  110945. * is automatically returned to its default position (expected to be above ground plane).
  110946. */
  110947. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  110948. var _this = this;
  110949. if (this._elevationReturnTime < 0) {
  110950. return;
  110951. }
  110952. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  110953. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  110954. var limitBeta = Math.PI * 0.5;
  110955. // Bring the camera back up if below the ground plane
  110956. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  110957. this._betaIsAnimating = true;
  110958. //Transition to new position
  110959. this.stopAllAnimations();
  110960. if (!this._betaTransition) {
  110961. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  110962. }
  110963. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  110964. _this._clearAnimationLocks();
  110965. _this.stopAllAnimations();
  110966. });
  110967. if (animatabe) {
  110968. this._animatables.push(animatabe);
  110969. }
  110970. }
  110971. };
  110972. /**
  110973. * Returns the frustum slope based on the canvas ratio and camera FOV
  110974. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  110975. */
  110976. FramingBehavior.prototype._getFrustumSlope = function () {
  110977. // Calculate the viewport ratio
  110978. // Aspect Ratio is Height/Width.
  110979. var camera = this._attachedCamera;
  110980. if (!camera) {
  110981. return BABYLON.Vector2.Zero();
  110982. }
  110983. var engine = camera.getScene().getEngine();
  110984. var aspectRatio = engine.getAspectRatio(camera);
  110985. // Camera FOV is the vertical field of view (top-bottom) in radians.
  110986. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  110987. var frustumSlopeY = Math.tan(camera.fov / 2);
  110988. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  110989. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  110990. // along the forward vector.
  110991. var frustumSlopeX = frustumSlopeY * aspectRatio;
  110992. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  110993. };
  110994. /**
  110995. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  110996. */
  110997. FramingBehavior.prototype._clearAnimationLocks = function () {
  110998. this._betaIsAnimating = false;
  110999. };
  111000. /**
  111001. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  111002. */
  111003. FramingBehavior.prototype._applyUserInteraction = function () {
  111004. if (this.isUserIsMoving) {
  111005. this._lastInteractionTime = BABYLON.Tools.Now;
  111006. this.stopAllAnimations();
  111007. this._clearAnimationLocks();
  111008. }
  111009. };
  111010. /**
  111011. * Stops and removes all animations that have been applied to the camera
  111012. */
  111013. FramingBehavior.prototype.stopAllAnimations = function () {
  111014. if (this._attachedCamera) {
  111015. this._attachedCamera.animations = [];
  111016. }
  111017. while (this._animatables.length) {
  111018. if (this._animatables[0]) {
  111019. this._animatables[0].onAnimationEnd = null;
  111020. this._animatables[0].stop();
  111021. }
  111022. this._animatables.shift();
  111023. }
  111024. };
  111025. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  111026. /**
  111027. * Gets a value indicating if the user is moving the camera
  111028. */
  111029. get: function () {
  111030. if (!this._attachedCamera) {
  111031. return false;
  111032. }
  111033. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  111034. this._attachedCamera.inertialBetaOffset !== 0 ||
  111035. this._attachedCamera.inertialRadiusOffset !== 0 ||
  111036. this._attachedCamera.inertialPanningX !== 0 ||
  111037. this._attachedCamera.inertialPanningY !== 0 ||
  111038. this._isPointerDown;
  111039. },
  111040. enumerable: true,
  111041. configurable: true
  111042. });
  111043. /**
  111044. * The easing function used by animations
  111045. */
  111046. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  111047. /**
  111048. * The easing mode used by animations
  111049. */
  111050. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  111051. // Statics
  111052. /**
  111053. * The camera can move all the way towards the mesh.
  111054. */
  111055. FramingBehavior.IgnoreBoundsSizeMode = 0;
  111056. /**
  111057. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  111058. */
  111059. FramingBehavior.FitFrustumSidesMode = 1;
  111060. return FramingBehavior;
  111061. }());
  111062. BABYLON.FramingBehavior = FramingBehavior;
  111063. })(BABYLON || (BABYLON = {}));
  111064. //# sourceMappingURL=babylon.framingBehavior.js.map
  111065. var BABYLON;
  111066. (function (BABYLON) {
  111067. /**
  111068. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  111069. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  111070. */
  111071. var BouncingBehavior = /** @class */ (function () {
  111072. function BouncingBehavior() {
  111073. /**
  111074. * The duration of the animation, in milliseconds
  111075. */
  111076. this.transitionDuration = 450;
  111077. /**
  111078. * Length of the distance animated by the transition when lower radius is reached
  111079. */
  111080. this.lowerRadiusTransitionRange = 2;
  111081. /**
  111082. * Length of the distance animated by the transition when upper radius is reached
  111083. */
  111084. this.upperRadiusTransitionRange = -2;
  111085. this._autoTransitionRange = false;
  111086. // Animations
  111087. this._radiusIsAnimating = false;
  111088. this._radiusBounceTransition = null;
  111089. this._animatables = new Array();
  111090. }
  111091. Object.defineProperty(BouncingBehavior.prototype, "name", {
  111092. /**
  111093. * Gets the name of the behavior.
  111094. */
  111095. get: function () {
  111096. return "Bouncing";
  111097. },
  111098. enumerable: true,
  111099. configurable: true
  111100. });
  111101. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  111102. /**
  111103. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  111104. */
  111105. get: function () {
  111106. return this._autoTransitionRange;
  111107. },
  111108. /**
  111109. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  111110. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  111111. */
  111112. set: function (value) {
  111113. var _this = this;
  111114. if (this._autoTransitionRange === value) {
  111115. return;
  111116. }
  111117. this._autoTransitionRange = value;
  111118. var camera = this._attachedCamera;
  111119. if (!camera) {
  111120. return;
  111121. }
  111122. if (value) {
  111123. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  111124. if (!mesh) {
  111125. return;
  111126. }
  111127. mesh.computeWorldMatrix(true);
  111128. var diagonal = mesh.getBoundingInfo().diagonalLength;
  111129. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  111130. _this.upperRadiusTransitionRange = diagonal * 0.05;
  111131. });
  111132. }
  111133. else if (this._onMeshTargetChangedObserver) {
  111134. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  111135. }
  111136. },
  111137. enumerable: true,
  111138. configurable: true
  111139. });
  111140. /**
  111141. * Initializes the behavior.
  111142. */
  111143. BouncingBehavior.prototype.init = function () {
  111144. // Do notihng
  111145. };
  111146. /**
  111147. * Attaches the behavior to its arc rotate camera.
  111148. * @param camera Defines the camera to attach the behavior to
  111149. */
  111150. BouncingBehavior.prototype.attach = function (camera) {
  111151. var _this = this;
  111152. this._attachedCamera = camera;
  111153. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  111154. if (!_this._attachedCamera) {
  111155. return;
  111156. }
  111157. // Add the bounce animation to the lower radius limit
  111158. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  111159. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  111160. }
  111161. // Add the bounce animation to the upper radius limit
  111162. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  111163. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  111164. }
  111165. });
  111166. };
  111167. /**
  111168. * Detaches the behavior from its current arc rotate camera.
  111169. */
  111170. BouncingBehavior.prototype.detach = function () {
  111171. if (!this._attachedCamera) {
  111172. return;
  111173. }
  111174. if (this._onAfterCheckInputsObserver) {
  111175. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  111176. }
  111177. if (this._onMeshTargetChangedObserver) {
  111178. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  111179. }
  111180. this._attachedCamera = null;
  111181. };
  111182. /**
  111183. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  111184. * @param radiusLimit The limit to check against.
  111185. * @return Bool to indicate if at limit.
  111186. */
  111187. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  111188. if (!this._attachedCamera) {
  111189. return false;
  111190. }
  111191. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  111192. return true;
  111193. }
  111194. return false;
  111195. };
  111196. /**
  111197. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  111198. * @param radiusDelta The delta by which to animate to. Can be negative.
  111199. */
  111200. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  111201. var _this = this;
  111202. if (!this._attachedCamera) {
  111203. return;
  111204. }
  111205. if (!this._radiusBounceTransition) {
  111206. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  111207. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  111208. }
  111209. // Prevent zoom until bounce has completed
  111210. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  111211. this._attachedCamera.wheelPrecision = Infinity;
  111212. this._attachedCamera.inertialRadiusOffset = 0;
  111213. // Animate to the radius limit
  111214. this.stopAllAnimations();
  111215. this._radiusIsAnimating = true;
  111216. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  111217. if (animatable) {
  111218. this._animatables.push(animatable);
  111219. }
  111220. };
  111221. /**
  111222. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  111223. */
  111224. BouncingBehavior.prototype._clearAnimationLocks = function () {
  111225. this._radiusIsAnimating = false;
  111226. if (this._attachedCamera) {
  111227. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  111228. }
  111229. };
  111230. /**
  111231. * Stops and removes all animations that have been applied to the camera
  111232. */
  111233. BouncingBehavior.prototype.stopAllAnimations = function () {
  111234. if (this._attachedCamera) {
  111235. this._attachedCamera.animations = [];
  111236. }
  111237. while (this._animatables.length) {
  111238. this._animatables[0].onAnimationEnd = null;
  111239. this._animatables[0].stop();
  111240. this._animatables.shift();
  111241. }
  111242. };
  111243. /**
  111244. * The easing function used by animations
  111245. */
  111246. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  111247. /**
  111248. * The easing mode used by animations
  111249. */
  111250. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  111251. return BouncingBehavior;
  111252. }());
  111253. BABYLON.BouncingBehavior = BouncingBehavior;
  111254. })(BABYLON || (BABYLON = {}));
  111255. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  111256. var BABYLON;
  111257. (function (BABYLON) {
  111258. /**
  111259. * The autoRotation behavior (BABYLON.AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction.
  111260. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  111261. */
  111262. var AutoRotationBehavior = /** @class */ (function () {
  111263. function AutoRotationBehavior() {
  111264. this._zoomStopsAnimation = false;
  111265. this._idleRotationSpeed = 0.05;
  111266. this._idleRotationWaitTime = 2000;
  111267. this._idleRotationSpinupTime = 2000;
  111268. this._isPointerDown = false;
  111269. this._lastFrameTime = null;
  111270. this._lastInteractionTime = -Infinity;
  111271. this._cameraRotationSpeed = 0;
  111272. this._lastFrameRadius = 0;
  111273. }
  111274. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  111275. /**
  111276. * Gets the name of the behavior.
  111277. */
  111278. get: function () {
  111279. return "AutoRotation";
  111280. },
  111281. enumerable: true,
  111282. configurable: true
  111283. });
  111284. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  111285. /**
  111286. * Gets the flag that indicates if user zooming should stop animation.
  111287. */
  111288. get: function () {
  111289. return this._zoomStopsAnimation;
  111290. },
  111291. /**
  111292. * Sets the flag that indicates if user zooming should stop animation.
  111293. */
  111294. set: function (flag) {
  111295. this._zoomStopsAnimation = flag;
  111296. },
  111297. enumerable: true,
  111298. configurable: true
  111299. });
  111300. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  111301. /**
  111302. * Gets the default speed at which the camera rotates around the model.
  111303. */
  111304. get: function () {
  111305. return this._idleRotationSpeed;
  111306. },
  111307. /**
  111308. * Sets the default speed at which the camera rotates around the model.
  111309. */
  111310. set: function (speed) {
  111311. this._idleRotationSpeed = speed;
  111312. },
  111313. enumerable: true,
  111314. configurable: true
  111315. });
  111316. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  111317. /**
  111318. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  111319. */
  111320. get: function () {
  111321. return this._idleRotationWaitTime;
  111322. },
  111323. /**
  111324. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  111325. */
  111326. set: function (time) {
  111327. this._idleRotationWaitTime = time;
  111328. },
  111329. enumerable: true,
  111330. configurable: true
  111331. });
  111332. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  111333. /**
  111334. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  111335. */
  111336. get: function () {
  111337. return this._idleRotationSpinupTime;
  111338. },
  111339. /**
  111340. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  111341. */
  111342. set: function (time) {
  111343. this._idleRotationSpinupTime = time;
  111344. },
  111345. enumerable: true,
  111346. configurable: true
  111347. });
  111348. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  111349. /**
  111350. * Gets a value indicating if the camera is currently rotating because of this behavior
  111351. */
  111352. get: function () {
  111353. return Math.abs(this._cameraRotationSpeed) > 0;
  111354. },
  111355. enumerable: true,
  111356. configurable: true
  111357. });
  111358. /**
  111359. * Initializes the behavior.
  111360. */
  111361. AutoRotationBehavior.prototype.init = function () {
  111362. // Do notihng
  111363. };
  111364. /**
  111365. * Attaches the behavior to its arc rotate camera.
  111366. * @param camera Defines the camera to attach the behavior to
  111367. */
  111368. AutoRotationBehavior.prototype.attach = function (camera) {
  111369. var _this = this;
  111370. this._attachedCamera = camera;
  111371. var scene = this._attachedCamera.getScene();
  111372. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  111373. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  111374. _this._isPointerDown = true;
  111375. return;
  111376. }
  111377. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  111378. _this._isPointerDown = false;
  111379. }
  111380. });
  111381. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  111382. var now = BABYLON.Tools.Now;
  111383. var dt = 0;
  111384. if (_this._lastFrameTime != null) {
  111385. dt = now - _this._lastFrameTime;
  111386. }
  111387. _this._lastFrameTime = now;
  111388. // Stop the animation if there is user interaction and the animation should stop for this interaction
  111389. _this._applyUserInteraction();
  111390. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  111391. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  111392. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  111393. // Step camera rotation by rotation speed
  111394. if (_this._attachedCamera) {
  111395. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  111396. }
  111397. });
  111398. };
  111399. /**
  111400. * Detaches the behavior from its current arc rotate camera.
  111401. */
  111402. AutoRotationBehavior.prototype.detach = function () {
  111403. if (!this._attachedCamera) {
  111404. return;
  111405. }
  111406. var scene = this._attachedCamera.getScene();
  111407. if (this._onPrePointerObservableObserver) {
  111408. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  111409. }
  111410. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  111411. this._attachedCamera = null;
  111412. };
  111413. /**
  111414. * Returns true if user is scrolling.
  111415. * @return true if user is scrolling.
  111416. */
  111417. AutoRotationBehavior.prototype._userIsZooming = function () {
  111418. if (!this._attachedCamera) {
  111419. return false;
  111420. }
  111421. return this._attachedCamera.inertialRadiusOffset !== 0;
  111422. };
  111423. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  111424. if (!this._attachedCamera) {
  111425. return false;
  111426. }
  111427. var zoomHasHitLimit = false;
  111428. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  111429. zoomHasHitLimit = true;
  111430. }
  111431. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  111432. this._lastFrameRadius = this._attachedCamera.radius;
  111433. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  111434. };
  111435. /**
  111436. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  111437. */
  111438. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  111439. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  111440. this._lastInteractionTime = BABYLON.Tools.Now;
  111441. }
  111442. };
  111443. // Tools
  111444. AutoRotationBehavior.prototype._userIsMoving = function () {
  111445. if (!this._attachedCamera) {
  111446. return false;
  111447. }
  111448. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  111449. this._attachedCamera.inertialBetaOffset !== 0 ||
  111450. this._attachedCamera.inertialRadiusOffset !== 0 ||
  111451. this._attachedCamera.inertialPanningX !== 0 ||
  111452. this._attachedCamera.inertialPanningY !== 0 ||
  111453. this._isPointerDown;
  111454. };
  111455. return AutoRotationBehavior;
  111456. }());
  111457. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  111458. })(BABYLON || (BABYLON = {}));
  111459. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  111460. var BABYLON;
  111461. (function (BABYLON) {
  111462. var NullEngineOptions = /** @class */ (function () {
  111463. function NullEngineOptions() {
  111464. this.renderWidth = 512;
  111465. this.renderHeight = 256;
  111466. this.textureSize = 512;
  111467. this.deterministicLockstep = false;
  111468. this.lockstepMaxSteps = 4;
  111469. }
  111470. return NullEngineOptions;
  111471. }());
  111472. BABYLON.NullEngineOptions = NullEngineOptions;
  111473. /**
  111474. * The null engine class provides support for headless version of babylon.js.
  111475. * This can be used in server side scenario or for testing purposes
  111476. */
  111477. var NullEngine = /** @class */ (function (_super) {
  111478. __extends(NullEngine, _super);
  111479. function NullEngine(options) {
  111480. if (options === void 0) { options = new NullEngineOptions(); }
  111481. var _this = _super.call(this, null) || this;
  111482. if (options.deterministicLockstep === undefined) {
  111483. options.deterministicLockstep = false;
  111484. }
  111485. if (options.lockstepMaxSteps === undefined) {
  111486. options.lockstepMaxSteps = 4;
  111487. }
  111488. _this._options = options;
  111489. // Init caps
  111490. // We consider we are on a webgl1 capable device
  111491. _this._caps = new BABYLON.EngineCapabilities();
  111492. _this._caps.maxTexturesImageUnits = 16;
  111493. _this._caps.maxVertexTextureImageUnits = 16;
  111494. _this._caps.maxTextureSize = 512;
  111495. _this._caps.maxCubemapTextureSize = 512;
  111496. _this._caps.maxRenderTextureSize = 512;
  111497. _this._caps.maxVertexAttribs = 16;
  111498. _this._caps.maxVaryingVectors = 16;
  111499. _this._caps.maxFragmentUniformVectors = 16;
  111500. _this._caps.maxVertexUniformVectors = 16;
  111501. // Extensions
  111502. _this._caps.standardDerivatives = false;
  111503. _this._caps.astc = null;
  111504. _this._caps.s3tc = null;
  111505. _this._caps.pvrtc = null;
  111506. _this._caps.etc1 = null;
  111507. _this._caps.etc2 = null;
  111508. _this._caps.textureAnisotropicFilterExtension = null;
  111509. _this._caps.maxAnisotropy = 0;
  111510. _this._caps.uintIndices = false;
  111511. _this._caps.fragmentDepthSupported = false;
  111512. _this._caps.highPrecisionShaderSupported = true;
  111513. _this._caps.colorBufferFloat = false;
  111514. _this._caps.textureFloat = false;
  111515. _this._caps.textureFloatLinearFiltering = false;
  111516. _this._caps.textureFloatRender = false;
  111517. _this._caps.textureHalfFloat = false;
  111518. _this._caps.textureHalfFloatLinearFiltering = false;
  111519. _this._caps.textureHalfFloatRender = false;
  111520. _this._caps.textureLOD = false;
  111521. _this._caps.drawBuffersExtension = false;
  111522. _this._caps.depthTextureExtension = false;
  111523. _this._caps.vertexArrayObject = false;
  111524. _this._caps.instancedArrays = false;
  111525. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  111526. // Wrappers
  111527. if (typeof URL === "undefined") {
  111528. URL = {
  111529. createObjectURL: function () { },
  111530. revokeObjectURL: function () { }
  111531. };
  111532. }
  111533. if (typeof Blob === "undefined") {
  111534. Blob = function () { };
  111535. }
  111536. return _this;
  111537. }
  111538. NullEngine.prototype.isDeterministicLockStep = function () {
  111539. return this._options.deterministicLockstep;
  111540. };
  111541. NullEngine.prototype.getLockstepMaxSteps = function () {
  111542. return this._options.lockstepMaxSteps;
  111543. };
  111544. NullEngine.prototype.getHardwareScalingLevel = function () {
  111545. return 1.0;
  111546. };
  111547. NullEngine.prototype.createVertexBuffer = function (vertices) {
  111548. return {
  111549. capacity: 0,
  111550. references: 1,
  111551. is32Bits: false
  111552. };
  111553. };
  111554. NullEngine.prototype.createIndexBuffer = function (indices) {
  111555. return {
  111556. capacity: 0,
  111557. references: 1,
  111558. is32Bits: false
  111559. };
  111560. };
  111561. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  111562. if (stencil === void 0) { stencil = false; }
  111563. };
  111564. NullEngine.prototype.getRenderWidth = function (useScreen) {
  111565. if (useScreen === void 0) { useScreen = false; }
  111566. if (!useScreen && this._currentRenderTarget) {
  111567. return this._currentRenderTarget.width;
  111568. }
  111569. return this._options.renderWidth;
  111570. };
  111571. NullEngine.prototype.getRenderHeight = function (useScreen) {
  111572. if (useScreen === void 0) { useScreen = false; }
  111573. if (!useScreen && this._currentRenderTarget) {
  111574. return this._currentRenderTarget.height;
  111575. }
  111576. return this._options.renderHeight;
  111577. };
  111578. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  111579. this._cachedViewport = viewport;
  111580. };
  111581. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  111582. return {
  111583. transformFeedback: null,
  111584. __SPECTOR_rebuildProgram: null
  111585. };
  111586. };
  111587. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  111588. return [];
  111589. };
  111590. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  111591. return [];
  111592. };
  111593. NullEngine.prototype.bindSamplers = function (effect) {
  111594. this._currentEffect = null;
  111595. };
  111596. NullEngine.prototype.enableEffect = function (effect) {
  111597. this._currentEffect = effect;
  111598. if (effect.onBind) {
  111599. effect.onBind(effect);
  111600. }
  111601. if (effect._onBindObservable) {
  111602. effect._onBindObservable.notifyObservers(effect);
  111603. }
  111604. };
  111605. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  111606. if (zOffset === void 0) { zOffset = 0; }
  111607. if (reverseSide === void 0) { reverseSide = false; }
  111608. };
  111609. NullEngine.prototype.setIntArray = function (uniform, array) {
  111610. };
  111611. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  111612. };
  111613. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  111614. };
  111615. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  111616. };
  111617. NullEngine.prototype.setFloatArray = function (uniform, array) {
  111618. };
  111619. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  111620. };
  111621. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  111622. };
  111623. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  111624. };
  111625. NullEngine.prototype.setArray = function (uniform, array) {
  111626. };
  111627. NullEngine.prototype.setArray2 = function (uniform, array) {
  111628. };
  111629. NullEngine.prototype.setArray3 = function (uniform, array) {
  111630. };
  111631. NullEngine.prototype.setArray4 = function (uniform, array) {
  111632. };
  111633. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  111634. };
  111635. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  111636. };
  111637. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  111638. };
  111639. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  111640. };
  111641. NullEngine.prototype.setFloat = function (uniform, value) {
  111642. };
  111643. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  111644. };
  111645. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  111646. };
  111647. NullEngine.prototype.setBool = function (uniform, bool) {
  111648. };
  111649. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  111650. };
  111651. NullEngine.prototype.setColor3 = function (uniform, color3) {
  111652. };
  111653. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  111654. };
  111655. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  111656. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  111657. if (this._alphaMode === mode) {
  111658. return;
  111659. }
  111660. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  111661. if (!noDepthWriteChange) {
  111662. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  111663. }
  111664. this._alphaMode = mode;
  111665. };
  111666. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  111667. };
  111668. NullEngine.prototype.wipeCaches = function (bruteForce) {
  111669. if (this.preventCacheWipeBetweenFrames) {
  111670. return;
  111671. }
  111672. this.resetTextureCache();
  111673. this._currentEffect = null;
  111674. if (bruteForce) {
  111675. this._currentProgram = null;
  111676. this._stencilState.reset();
  111677. this._depthCullingState.reset();
  111678. this._alphaState.reset();
  111679. }
  111680. this._cachedVertexBuffers = null;
  111681. this._cachedIndexBuffer = null;
  111682. this._cachedEffectForVertexBuffers = null;
  111683. };
  111684. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  111685. };
  111686. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  111687. };
  111688. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  111689. };
  111690. /** @hidden */
  111691. NullEngine.prototype._createTexture = function () {
  111692. return {};
  111693. };
  111694. /** @hidden */
  111695. NullEngine.prototype._releaseTexture = function (texture) {
  111696. };
  111697. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  111698. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  111699. if (onLoad === void 0) { onLoad = null; }
  111700. if (onError === void 0) { onError = null; }
  111701. if (buffer === void 0) { buffer = null; }
  111702. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  111703. var url = String(urlArg);
  111704. texture.url = url;
  111705. texture.generateMipMaps = !noMipmap;
  111706. texture.samplingMode = samplingMode;
  111707. texture.invertY = invertY;
  111708. texture.baseWidth = this._options.textureSize;
  111709. texture.baseHeight = this._options.textureSize;
  111710. texture.width = this._options.textureSize;
  111711. texture.height = this._options.textureSize;
  111712. if (format) {
  111713. texture.format = format;
  111714. }
  111715. texture.isReady = true;
  111716. if (onLoad) {
  111717. onLoad();
  111718. }
  111719. this._internalTexturesCache.push(texture);
  111720. return texture;
  111721. };
  111722. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  111723. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  111724. if (options !== undefined && typeof options === "object") {
  111725. fullOptions.generateMipMaps = options.generateMipMaps;
  111726. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  111727. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  111728. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  111729. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  111730. }
  111731. else {
  111732. fullOptions.generateMipMaps = options;
  111733. fullOptions.generateDepthBuffer = true;
  111734. fullOptions.generateStencilBuffer = false;
  111735. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  111736. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  111737. }
  111738. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  111739. var width = size.width || size;
  111740. var height = size.height || size;
  111741. texture._depthStencilBuffer = {};
  111742. texture._framebuffer = {};
  111743. texture.baseWidth = width;
  111744. texture.baseHeight = height;
  111745. texture.width = width;
  111746. texture.height = height;
  111747. texture.isReady = true;
  111748. texture.samples = 1;
  111749. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  111750. texture.samplingMode = fullOptions.samplingMode;
  111751. texture.type = fullOptions.type;
  111752. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  111753. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  111754. this._internalTexturesCache.push(texture);
  111755. return texture;
  111756. };
  111757. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  111758. texture.samplingMode = samplingMode;
  111759. };
  111760. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  111761. if (this._currentRenderTarget) {
  111762. this.unBindFramebuffer(this._currentRenderTarget);
  111763. }
  111764. this._currentRenderTarget = texture;
  111765. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  111766. if (this._cachedViewport && !forceFullscreenViewport) {
  111767. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  111768. }
  111769. };
  111770. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  111771. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  111772. this._currentRenderTarget = null;
  111773. if (onBeforeUnbind) {
  111774. if (texture._MSAAFramebuffer) {
  111775. this._currentFramebuffer = texture._framebuffer;
  111776. }
  111777. onBeforeUnbind();
  111778. }
  111779. this._currentFramebuffer = null;
  111780. };
  111781. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  111782. var vbo = {
  111783. capacity: 1,
  111784. references: 1,
  111785. is32Bits: false
  111786. };
  111787. return vbo;
  111788. };
  111789. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  111790. if (premulAlpha === void 0) { premulAlpha = false; }
  111791. };
  111792. /**
  111793. * @hidden
  111794. * Get the current error code of the webGL context
  111795. * @returns the error code
  111796. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  111797. */
  111798. NullEngine.prototype.getError = function () {
  111799. return 0;
  111800. };
  111801. /** @hidden */
  111802. NullEngine.prototype._getUnpackAlignement = function () {
  111803. return 1;
  111804. };
  111805. /** @hidden */
  111806. NullEngine.prototype._unpackFlipY = function (value) {
  111807. };
  111808. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  111809. if (offset === void 0) { offset = 0; }
  111810. };
  111811. /**
  111812. * Updates a dynamic vertex buffer.
  111813. * @param vertexBuffer the vertex buffer to update
  111814. * @param data the data used to update the vertex buffer
  111815. * @param byteOffset the byte offset of the data (optional)
  111816. * @param byteLength the byte length of the data (optional)
  111817. */
  111818. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  111819. };
  111820. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  111821. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  111822. this._boundTexturesCache[this._activeChannel] = texture;
  111823. return true;
  111824. }
  111825. return false;
  111826. };
  111827. /** @hidden */
  111828. NullEngine.prototype._bindTexture = function (channel, texture) {
  111829. if (channel < 0) {
  111830. return;
  111831. }
  111832. this._bindTextureDirectly(0, texture);
  111833. };
  111834. /** @hidden */
  111835. NullEngine.prototype._releaseBuffer = function (buffer) {
  111836. buffer.references--;
  111837. if (buffer.references === 0) {
  111838. return true;
  111839. }
  111840. return false;
  111841. };
  111842. NullEngine.prototype.releaseEffects = function () {
  111843. };
  111844. NullEngine.prototype.displayLoadingUI = function () {
  111845. };
  111846. NullEngine.prototype.hideLoadingUI = function () {
  111847. };
  111848. /** @hidden */
  111849. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  111850. if (faceIndex === void 0) { faceIndex = 0; }
  111851. if (lod === void 0) { lod = 0; }
  111852. };
  111853. /** @hidden */
  111854. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  111855. if (faceIndex === void 0) { faceIndex = 0; }
  111856. if (lod === void 0) { lod = 0; }
  111857. };
  111858. /** @hidden */
  111859. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  111860. if (faceIndex === void 0) { faceIndex = 0; }
  111861. if (lod === void 0) { lod = 0; }
  111862. };
  111863. /** @hidden */
  111864. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  111865. if (faceIndex === void 0) { faceIndex = 0; }
  111866. if (lod === void 0) { lod = 0; }
  111867. };
  111868. return NullEngine;
  111869. }(BABYLON.Engine));
  111870. BABYLON.NullEngine = NullEngine;
  111871. })(BABYLON || (BABYLON = {}));
  111872. //# sourceMappingURL=babylon.nullEngine.js.map
  111873. var BABYLON;
  111874. (function (BABYLON) {
  111875. /**
  111876. * This class can be used to get instrumentation data from a Babylon engine
  111877. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  111878. */
  111879. var EngineInstrumentation = /** @class */ (function () {
  111880. /**
  111881. * Instantiates a new engine instrumentation.
  111882. * This class can be used to get instrumentation data from a Babylon engine
  111883. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  111884. * @param engine Defines the engine to instrument
  111885. */
  111886. function EngineInstrumentation(
  111887. /**
  111888. * Define the instrumented engine.
  111889. */
  111890. engine) {
  111891. this.engine = engine;
  111892. this._captureGPUFrameTime = false;
  111893. this._gpuFrameTime = new BABYLON.PerfCounter();
  111894. this._captureShaderCompilationTime = false;
  111895. this._shaderCompilationTime = new BABYLON.PerfCounter();
  111896. // Observers
  111897. this._onBeginFrameObserver = null;
  111898. this._onEndFrameObserver = null;
  111899. this._onBeforeShaderCompilationObserver = null;
  111900. this._onAfterShaderCompilationObserver = null;
  111901. }
  111902. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  111903. // Properties
  111904. /**
  111905. * Gets the perf counter used for GPU frame time
  111906. */
  111907. get: function () {
  111908. return this._gpuFrameTime;
  111909. },
  111910. enumerable: true,
  111911. configurable: true
  111912. });
  111913. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  111914. /**
  111915. * Gets the GPU frame time capture status
  111916. */
  111917. get: function () {
  111918. return this._captureGPUFrameTime;
  111919. },
  111920. /**
  111921. * Enable or disable the GPU frame time capture
  111922. */
  111923. set: function (value) {
  111924. var _this = this;
  111925. if (value === this._captureGPUFrameTime) {
  111926. return;
  111927. }
  111928. this._captureGPUFrameTime = value;
  111929. if (value) {
  111930. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  111931. if (!_this._gpuFrameTimeToken) {
  111932. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  111933. }
  111934. });
  111935. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  111936. if (!_this._gpuFrameTimeToken) {
  111937. return;
  111938. }
  111939. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  111940. if (time > -1) {
  111941. _this._gpuFrameTimeToken = null;
  111942. _this._gpuFrameTime.fetchNewFrame();
  111943. _this._gpuFrameTime.addCount(time, true);
  111944. }
  111945. });
  111946. }
  111947. else {
  111948. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  111949. this._onBeginFrameObserver = null;
  111950. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  111951. this._onEndFrameObserver = null;
  111952. }
  111953. },
  111954. enumerable: true,
  111955. configurable: true
  111956. });
  111957. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  111958. /**
  111959. * Gets the perf counter used for shader compilation time
  111960. */
  111961. get: function () {
  111962. return this._shaderCompilationTime;
  111963. },
  111964. enumerable: true,
  111965. configurable: true
  111966. });
  111967. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  111968. /**
  111969. * Gets the shader compilation time capture status
  111970. */
  111971. get: function () {
  111972. return this._captureShaderCompilationTime;
  111973. },
  111974. /**
  111975. * Enable or disable the shader compilation time capture
  111976. */
  111977. set: function (value) {
  111978. var _this = this;
  111979. if (value === this._captureShaderCompilationTime) {
  111980. return;
  111981. }
  111982. this._captureShaderCompilationTime = value;
  111983. if (value) {
  111984. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  111985. _this._shaderCompilationTime.fetchNewFrame();
  111986. _this._shaderCompilationTime.beginMonitoring();
  111987. });
  111988. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  111989. _this._shaderCompilationTime.endMonitoring();
  111990. });
  111991. }
  111992. else {
  111993. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  111994. this._onBeforeShaderCompilationObserver = null;
  111995. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  111996. this._onAfterShaderCompilationObserver = null;
  111997. }
  111998. },
  111999. enumerable: true,
  112000. configurable: true
  112001. });
  112002. /**
  112003. * Dispose and release associated resources.
  112004. */
  112005. EngineInstrumentation.prototype.dispose = function () {
  112006. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  112007. this._onBeginFrameObserver = null;
  112008. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  112009. this._onEndFrameObserver = null;
  112010. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  112011. this._onBeforeShaderCompilationObserver = null;
  112012. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  112013. this._onAfterShaderCompilationObserver = null;
  112014. this.engine = null;
  112015. };
  112016. return EngineInstrumentation;
  112017. }());
  112018. BABYLON.EngineInstrumentation = EngineInstrumentation;
  112019. })(BABYLON || (BABYLON = {}));
  112020. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  112021. var BABYLON;
  112022. (function (BABYLON) {
  112023. /**
  112024. * This class can be used to get instrumentation data from a Babylon engine
  112025. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  112026. */
  112027. var SceneInstrumentation = /** @class */ (function () {
  112028. /**
  112029. * Instantiates a new scene instrumentation.
  112030. * This class can be used to get instrumentation data from a Babylon engine
  112031. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  112032. * @param scene Defines the scene to instrument
  112033. */
  112034. function SceneInstrumentation(
  112035. /**
  112036. * Defines the scene to instrument
  112037. */
  112038. scene) {
  112039. var _this = this;
  112040. this.scene = scene;
  112041. this._captureActiveMeshesEvaluationTime = false;
  112042. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  112043. this._captureRenderTargetsRenderTime = false;
  112044. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  112045. this._captureFrameTime = false;
  112046. this._frameTime = new BABYLON.PerfCounter();
  112047. this._captureRenderTime = false;
  112048. this._renderTime = new BABYLON.PerfCounter();
  112049. this._captureInterFrameTime = false;
  112050. this._interFrameTime = new BABYLON.PerfCounter();
  112051. this._captureParticlesRenderTime = false;
  112052. this._particlesRenderTime = new BABYLON.PerfCounter();
  112053. this._captureSpritesRenderTime = false;
  112054. this._spritesRenderTime = new BABYLON.PerfCounter();
  112055. this._capturePhysicsTime = false;
  112056. this._physicsTime = new BABYLON.PerfCounter();
  112057. this._captureAnimationsTime = false;
  112058. this._animationsTime = new BABYLON.PerfCounter();
  112059. this._captureCameraRenderTime = false;
  112060. this._cameraRenderTime = new BABYLON.PerfCounter();
  112061. // Observers
  112062. this._onBeforeActiveMeshesEvaluationObserver = null;
  112063. this._onAfterActiveMeshesEvaluationObserver = null;
  112064. this._onBeforeRenderTargetsRenderObserver = null;
  112065. this._onAfterRenderTargetsRenderObserver = null;
  112066. this._onAfterRenderObserver = null;
  112067. this._onBeforeDrawPhaseObserver = null;
  112068. this._onAfterDrawPhaseObserver = null;
  112069. this._onBeforeAnimationsObserver = null;
  112070. this._onBeforeParticlesRenderingObserver = null;
  112071. this._onAfterParticlesRenderingObserver = null;
  112072. this._onBeforeSpritesRenderingObserver = null;
  112073. this._onAfterSpritesRenderingObserver = null;
  112074. this._onBeforePhysicsObserver = null;
  112075. this._onAfterPhysicsObserver = null;
  112076. this._onAfterAnimationsObserver = null;
  112077. this._onBeforeCameraRenderObserver = null;
  112078. this._onAfterCameraRenderObserver = null;
  112079. // Before render
  112080. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  112081. if (_this._captureActiveMeshesEvaluationTime) {
  112082. _this._activeMeshesEvaluationTime.fetchNewFrame();
  112083. }
  112084. if (_this._captureRenderTargetsRenderTime) {
  112085. _this._renderTargetsRenderTime.fetchNewFrame();
  112086. }
  112087. if (_this._captureFrameTime) {
  112088. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  112089. _this._frameTime.beginMonitoring();
  112090. }
  112091. if (_this._captureInterFrameTime) {
  112092. _this._interFrameTime.endMonitoring();
  112093. }
  112094. if (_this._captureParticlesRenderTime) {
  112095. _this._particlesRenderTime.fetchNewFrame();
  112096. }
  112097. if (_this._captureSpritesRenderTime) {
  112098. _this._spritesRenderTime.fetchNewFrame();
  112099. }
  112100. if (_this._captureAnimationsTime) {
  112101. _this._animationsTime.beginMonitoring();
  112102. }
  112103. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  112104. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  112105. });
  112106. // After render
  112107. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  112108. if (_this._captureFrameTime) {
  112109. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  112110. _this._frameTime.endMonitoring();
  112111. }
  112112. if (_this._captureRenderTime) {
  112113. _this._renderTime.endMonitoring(false);
  112114. }
  112115. if (_this._captureInterFrameTime) {
  112116. _this._interFrameTime.beginMonitoring();
  112117. }
  112118. });
  112119. }
  112120. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  112121. // Properties
  112122. /**
  112123. * Gets the perf counter used for active meshes evaluation time
  112124. */
  112125. get: function () {
  112126. return this._activeMeshesEvaluationTime;
  112127. },
  112128. enumerable: true,
  112129. configurable: true
  112130. });
  112131. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  112132. /**
  112133. * Gets the active meshes evaluation time capture status
  112134. */
  112135. get: function () {
  112136. return this._captureActiveMeshesEvaluationTime;
  112137. },
  112138. /**
  112139. * Enable or disable the active meshes evaluation time capture
  112140. */
  112141. set: function (value) {
  112142. var _this = this;
  112143. if (value === this._captureActiveMeshesEvaluationTime) {
  112144. return;
  112145. }
  112146. this._captureActiveMeshesEvaluationTime = value;
  112147. if (value) {
  112148. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  112149. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  112150. _this._activeMeshesEvaluationTime.beginMonitoring();
  112151. });
  112152. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  112153. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  112154. _this._activeMeshesEvaluationTime.endMonitoring();
  112155. });
  112156. }
  112157. else {
  112158. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  112159. this._onBeforeActiveMeshesEvaluationObserver = null;
  112160. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  112161. this._onAfterActiveMeshesEvaluationObserver = null;
  112162. }
  112163. },
  112164. enumerable: true,
  112165. configurable: true
  112166. });
  112167. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  112168. /**
  112169. * Gets the perf counter used for render targets render time
  112170. */
  112171. get: function () {
  112172. return this._renderTargetsRenderTime;
  112173. },
  112174. enumerable: true,
  112175. configurable: true
  112176. });
  112177. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  112178. /**
  112179. * Gets the render targets render time capture status
  112180. */
  112181. get: function () {
  112182. return this._captureRenderTargetsRenderTime;
  112183. },
  112184. /**
  112185. * Enable or disable the render targets render time capture
  112186. */
  112187. set: function (value) {
  112188. var _this = this;
  112189. if (value === this._captureRenderTargetsRenderTime) {
  112190. return;
  112191. }
  112192. this._captureRenderTargetsRenderTime = value;
  112193. if (value) {
  112194. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  112195. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  112196. _this._renderTargetsRenderTime.beginMonitoring();
  112197. });
  112198. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  112199. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  112200. _this._renderTargetsRenderTime.endMonitoring(false);
  112201. });
  112202. }
  112203. else {
  112204. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  112205. this._onBeforeRenderTargetsRenderObserver = null;
  112206. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  112207. this._onAfterRenderTargetsRenderObserver = null;
  112208. }
  112209. },
  112210. enumerable: true,
  112211. configurable: true
  112212. });
  112213. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  112214. /**
  112215. * Gets the perf counter used for particles render time
  112216. */
  112217. get: function () {
  112218. return this._particlesRenderTime;
  112219. },
  112220. enumerable: true,
  112221. configurable: true
  112222. });
  112223. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  112224. /**
  112225. * Gets the particles render time capture status
  112226. */
  112227. get: function () {
  112228. return this._captureParticlesRenderTime;
  112229. },
  112230. /**
  112231. * Enable or disable the particles render time capture
  112232. */
  112233. set: function (value) {
  112234. var _this = this;
  112235. if (value === this._captureParticlesRenderTime) {
  112236. return;
  112237. }
  112238. this._captureParticlesRenderTime = value;
  112239. if (value) {
  112240. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  112241. BABYLON.Tools.StartPerformanceCounter("Particles");
  112242. _this._particlesRenderTime.beginMonitoring();
  112243. });
  112244. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  112245. BABYLON.Tools.EndPerformanceCounter("Particles");
  112246. _this._particlesRenderTime.endMonitoring(false);
  112247. });
  112248. }
  112249. else {
  112250. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  112251. this._onBeforeParticlesRenderingObserver = null;
  112252. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  112253. this._onAfterParticlesRenderingObserver = null;
  112254. }
  112255. },
  112256. enumerable: true,
  112257. configurable: true
  112258. });
  112259. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  112260. /**
  112261. * Gets the perf counter used for sprites render time
  112262. */
  112263. get: function () {
  112264. return this._spritesRenderTime;
  112265. },
  112266. enumerable: true,
  112267. configurable: true
  112268. });
  112269. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  112270. /**
  112271. * Gets the sprites render time capture status
  112272. */
  112273. get: function () {
  112274. return this._captureSpritesRenderTime;
  112275. },
  112276. /**
  112277. * Enable or disable the sprites render time capture
  112278. */
  112279. set: function (value) {
  112280. var _this = this;
  112281. if (value === this._captureSpritesRenderTime) {
  112282. return;
  112283. }
  112284. this._captureSpritesRenderTime = value;
  112285. if (!this.scene.spriteManagers) {
  112286. return;
  112287. }
  112288. if (value) {
  112289. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  112290. BABYLON.Tools.StartPerformanceCounter("Sprites");
  112291. _this._spritesRenderTime.beginMonitoring();
  112292. });
  112293. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  112294. BABYLON.Tools.EndPerformanceCounter("Sprites");
  112295. _this._spritesRenderTime.endMonitoring(false);
  112296. });
  112297. }
  112298. else {
  112299. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  112300. this._onBeforeSpritesRenderingObserver = null;
  112301. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  112302. this._onAfterSpritesRenderingObserver = null;
  112303. }
  112304. },
  112305. enumerable: true,
  112306. configurable: true
  112307. });
  112308. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  112309. /**
  112310. * Gets the perf counter used for physics time
  112311. */
  112312. get: function () {
  112313. return this._physicsTime;
  112314. },
  112315. enumerable: true,
  112316. configurable: true
  112317. });
  112318. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  112319. /**
  112320. * Gets the physics time capture status
  112321. */
  112322. get: function () {
  112323. return this._capturePhysicsTime;
  112324. },
  112325. /**
  112326. * Enable or disable the physics time capture
  112327. */
  112328. set: function (value) {
  112329. var _this = this;
  112330. if (value === this._capturePhysicsTime) {
  112331. return;
  112332. }
  112333. if (!this.scene.onBeforePhysicsObservable) {
  112334. return;
  112335. }
  112336. this._capturePhysicsTime = value;
  112337. if (value) {
  112338. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  112339. BABYLON.Tools.StartPerformanceCounter("Physics");
  112340. _this._physicsTime.beginMonitoring();
  112341. });
  112342. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  112343. BABYLON.Tools.EndPerformanceCounter("Physics");
  112344. _this._physicsTime.endMonitoring();
  112345. });
  112346. }
  112347. else {
  112348. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  112349. this._onBeforePhysicsObserver = null;
  112350. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  112351. this._onAfterPhysicsObserver = null;
  112352. }
  112353. },
  112354. enumerable: true,
  112355. configurable: true
  112356. });
  112357. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  112358. /**
  112359. * Gets the perf counter used for animations time
  112360. */
  112361. get: function () {
  112362. return this._animationsTime;
  112363. },
  112364. enumerable: true,
  112365. configurable: true
  112366. });
  112367. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  112368. /**
  112369. * Gets the animations time capture status
  112370. */
  112371. get: function () {
  112372. return this._captureAnimationsTime;
  112373. },
  112374. /**
  112375. * Enable or disable the animations time capture
  112376. */
  112377. set: function (value) {
  112378. var _this = this;
  112379. if (value === this._captureAnimationsTime) {
  112380. return;
  112381. }
  112382. this._captureAnimationsTime = value;
  112383. if (value) {
  112384. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  112385. _this._animationsTime.endMonitoring();
  112386. });
  112387. }
  112388. else {
  112389. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  112390. this._onAfterAnimationsObserver = null;
  112391. }
  112392. },
  112393. enumerable: true,
  112394. configurable: true
  112395. });
  112396. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  112397. /**
  112398. * Gets the perf counter used for frame time capture
  112399. */
  112400. get: function () {
  112401. return this._frameTime;
  112402. },
  112403. enumerable: true,
  112404. configurable: true
  112405. });
  112406. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  112407. /**
  112408. * Gets the frame time capture status
  112409. */
  112410. get: function () {
  112411. return this._captureFrameTime;
  112412. },
  112413. /**
  112414. * Enable or disable the frame time capture
  112415. */
  112416. set: function (value) {
  112417. this._captureFrameTime = value;
  112418. },
  112419. enumerable: true,
  112420. configurable: true
  112421. });
  112422. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  112423. /**
  112424. * Gets the perf counter used for inter-frames time capture
  112425. */
  112426. get: function () {
  112427. return this._interFrameTime;
  112428. },
  112429. enumerable: true,
  112430. configurable: true
  112431. });
  112432. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  112433. /**
  112434. * Gets the inter-frames time capture status
  112435. */
  112436. get: function () {
  112437. return this._captureInterFrameTime;
  112438. },
  112439. /**
  112440. * Enable or disable the inter-frames time capture
  112441. */
  112442. set: function (value) {
  112443. this._captureInterFrameTime = value;
  112444. },
  112445. enumerable: true,
  112446. configurable: true
  112447. });
  112448. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  112449. /**
  112450. * Gets the perf counter used for render time capture
  112451. */
  112452. get: function () {
  112453. return this._renderTime;
  112454. },
  112455. enumerable: true,
  112456. configurable: true
  112457. });
  112458. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  112459. /**
  112460. * Gets the render time capture status
  112461. */
  112462. get: function () {
  112463. return this._captureRenderTime;
  112464. },
  112465. /**
  112466. * Enable or disable the render time capture
  112467. */
  112468. set: function (value) {
  112469. var _this = this;
  112470. if (value === this._captureRenderTime) {
  112471. return;
  112472. }
  112473. this._captureRenderTime = value;
  112474. if (value) {
  112475. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  112476. _this._renderTime.beginMonitoring();
  112477. BABYLON.Tools.StartPerformanceCounter("Main render");
  112478. });
  112479. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  112480. _this._renderTime.endMonitoring(false);
  112481. BABYLON.Tools.EndPerformanceCounter("Main render");
  112482. });
  112483. }
  112484. else {
  112485. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  112486. this._onBeforeDrawPhaseObserver = null;
  112487. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  112488. this._onAfterDrawPhaseObserver = null;
  112489. }
  112490. },
  112491. enumerable: true,
  112492. configurable: true
  112493. });
  112494. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  112495. /**
  112496. * Gets the perf counter used for camera render time capture
  112497. */
  112498. get: function () {
  112499. return this._cameraRenderTime;
  112500. },
  112501. enumerable: true,
  112502. configurable: true
  112503. });
  112504. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  112505. /**
  112506. * Gets the camera render time capture status
  112507. */
  112508. get: function () {
  112509. return this._captureCameraRenderTime;
  112510. },
  112511. /**
  112512. * Enable or disable the camera render time capture
  112513. */
  112514. set: function (value) {
  112515. var _this = this;
  112516. if (value === this._captureCameraRenderTime) {
  112517. return;
  112518. }
  112519. this._captureCameraRenderTime = value;
  112520. if (value) {
  112521. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  112522. _this._cameraRenderTime.beginMonitoring();
  112523. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  112524. });
  112525. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  112526. _this._cameraRenderTime.endMonitoring(false);
  112527. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  112528. });
  112529. }
  112530. else {
  112531. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  112532. this._onBeforeCameraRenderObserver = null;
  112533. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  112534. this._onAfterCameraRenderObserver = null;
  112535. }
  112536. },
  112537. enumerable: true,
  112538. configurable: true
  112539. });
  112540. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  112541. /**
  112542. * Gets the perf counter used for draw calls
  112543. */
  112544. get: function () {
  112545. return this.scene.getEngine()._drawCalls;
  112546. },
  112547. enumerable: true,
  112548. configurable: true
  112549. });
  112550. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  112551. /**
  112552. * Gets the perf counter used for texture collisions
  112553. */
  112554. get: function () {
  112555. return this.scene.getEngine()._textureCollisions;
  112556. },
  112557. enumerable: true,
  112558. configurable: true
  112559. });
  112560. /**
  112561. * Dispose and release associated resources.
  112562. */
  112563. SceneInstrumentation.prototype.dispose = function () {
  112564. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  112565. this._onAfterRenderObserver = null;
  112566. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  112567. this._onBeforeActiveMeshesEvaluationObserver = null;
  112568. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  112569. this._onAfterActiveMeshesEvaluationObserver = null;
  112570. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  112571. this._onBeforeRenderTargetsRenderObserver = null;
  112572. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  112573. this._onAfterRenderTargetsRenderObserver = null;
  112574. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  112575. this._onBeforeAnimationsObserver = null;
  112576. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  112577. this._onBeforeParticlesRenderingObserver = null;
  112578. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  112579. this._onAfterParticlesRenderingObserver = null;
  112580. if (this._onBeforeSpritesRenderingObserver) {
  112581. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  112582. this._onBeforeSpritesRenderingObserver = null;
  112583. }
  112584. if (this._onAfterSpritesRenderingObserver) {
  112585. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  112586. this._onAfterSpritesRenderingObserver = null;
  112587. }
  112588. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  112589. this._onBeforeDrawPhaseObserver = null;
  112590. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  112591. this._onAfterDrawPhaseObserver = null;
  112592. if (this._onBeforePhysicsObserver) {
  112593. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  112594. this._onBeforePhysicsObserver = null;
  112595. }
  112596. if (this._onAfterPhysicsObserver) {
  112597. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  112598. this._onAfterPhysicsObserver = null;
  112599. }
  112600. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  112601. this._onAfterAnimationsObserver = null;
  112602. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  112603. this._onBeforeCameraRenderObserver = null;
  112604. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  112605. this._onAfterCameraRenderObserver = null;
  112606. this.scene = null;
  112607. };
  112608. return SceneInstrumentation;
  112609. }());
  112610. BABYLON.SceneInstrumentation = SceneInstrumentation;
  112611. })(BABYLON || (BABYLON = {}));
  112612. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  112613. var BABYLON;
  112614. (function (BABYLON) {
  112615. /**
  112616. * @hidden
  112617. **/
  112618. var _TimeToken = /** @class */ (function () {
  112619. function _TimeToken() {
  112620. this._timeElapsedQueryEnded = false;
  112621. }
  112622. return _TimeToken;
  112623. }());
  112624. BABYLON._TimeToken = _TimeToken;
  112625. })(BABYLON || (BABYLON = {}));
  112626. //# sourceMappingURL=babylon.timeToken.js.map
  112627. var BABYLON;
  112628. (function (BABYLON) {
  112629. /**
  112630. * Background material defines definition.
  112631. * @hidden Mainly internal Use
  112632. */
  112633. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  112634. __extends(BackgroundMaterialDefines, _super);
  112635. /**
  112636. * Constructor of the defines.
  112637. */
  112638. function BackgroundMaterialDefines() {
  112639. var _this = _super.call(this) || this;
  112640. /**
  112641. * True if the diffuse texture is in use.
  112642. */
  112643. _this.DIFFUSE = false;
  112644. /**
  112645. * The direct UV channel to use.
  112646. */
  112647. _this.DIFFUSEDIRECTUV = 0;
  112648. /**
  112649. * True if the diffuse texture is in gamma space.
  112650. */
  112651. _this.GAMMADIFFUSE = false;
  112652. /**
  112653. * True if the diffuse texture has opacity in the alpha channel.
  112654. */
  112655. _this.DIFFUSEHASALPHA = false;
  112656. /**
  112657. * True if you want the material to fade to transparent at grazing angle.
  112658. */
  112659. _this.OPACITYFRESNEL = false;
  112660. /**
  112661. * True if an extra blur needs to be added in the reflection.
  112662. */
  112663. _this.REFLECTIONBLUR = false;
  112664. /**
  112665. * True if you want the material to fade to reflection at grazing angle.
  112666. */
  112667. _this.REFLECTIONFRESNEL = false;
  112668. /**
  112669. * True if you want the material to falloff as far as you move away from the scene center.
  112670. */
  112671. _this.REFLECTIONFALLOFF = false;
  112672. /**
  112673. * False if the current Webgl implementation does not support the texture lod extension.
  112674. */
  112675. _this.TEXTURELODSUPPORT = false;
  112676. /**
  112677. * True to ensure the data are premultiplied.
  112678. */
  112679. _this.PREMULTIPLYALPHA = false;
  112680. /**
  112681. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  112682. */
  112683. _this.USERGBCOLOR = false;
  112684. /**
  112685. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  112686. * stays aligned with the desired configuration.
  112687. */
  112688. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  112689. /**
  112690. * True to add noise in order to reduce the banding effect.
  112691. */
  112692. _this.NOISE = false;
  112693. /**
  112694. * is the reflection texture in BGR color scheme?
  112695. * Mainly used to solve a bug in ios10 video tag
  112696. */
  112697. _this.REFLECTIONBGR = false;
  112698. _this.IMAGEPROCESSING = false;
  112699. _this.VIGNETTE = false;
  112700. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  112701. _this.VIGNETTEBLENDMODEOPAQUE = false;
  112702. _this.TONEMAPPING = false;
  112703. _this.TONEMAPPING_ACES = false;
  112704. _this.CONTRAST = false;
  112705. _this.COLORCURVES = false;
  112706. _this.COLORGRADING = false;
  112707. _this.COLORGRADING3D = false;
  112708. _this.SAMPLER3DGREENDEPTH = false;
  112709. _this.SAMPLER3DBGRMAP = false;
  112710. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  112711. _this.EXPOSURE = false;
  112712. // Reflection.
  112713. _this.REFLECTION = false;
  112714. _this.REFLECTIONMAP_3D = false;
  112715. _this.REFLECTIONMAP_SPHERICAL = false;
  112716. _this.REFLECTIONMAP_PLANAR = false;
  112717. _this.REFLECTIONMAP_CUBIC = false;
  112718. _this.REFLECTIONMAP_PROJECTION = false;
  112719. _this.REFLECTIONMAP_SKYBOX = false;
  112720. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  112721. _this.REFLECTIONMAP_EXPLICIT = false;
  112722. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  112723. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  112724. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  112725. _this.INVERTCUBICMAP = false;
  112726. _this.REFLECTIONMAP_OPPOSITEZ = false;
  112727. _this.LODINREFLECTIONALPHA = false;
  112728. _this.GAMMAREFLECTION = false;
  112729. _this.RGBDREFLECTION = false;
  112730. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  112731. // Default BJS.
  112732. _this.MAINUV1 = false;
  112733. _this.MAINUV2 = false;
  112734. _this.UV1 = false;
  112735. _this.UV2 = false;
  112736. _this.CLIPPLANE = false;
  112737. _this.CLIPPLANE2 = false;
  112738. _this.CLIPPLANE3 = false;
  112739. _this.CLIPPLANE4 = false;
  112740. _this.POINTSIZE = false;
  112741. _this.FOG = false;
  112742. _this.NORMAL = false;
  112743. _this.NUM_BONE_INFLUENCERS = 0;
  112744. _this.BonesPerMesh = 0;
  112745. _this.INSTANCES = false;
  112746. _this.SHADOWFLOAT = false;
  112747. _this.rebuild();
  112748. return _this;
  112749. }
  112750. return BackgroundMaterialDefines;
  112751. }(BABYLON.MaterialDefines));
  112752. /**
  112753. * Background material used to create an efficient environement around your scene.
  112754. */
  112755. var BackgroundMaterial = /** @class */ (function (_super) {
  112756. __extends(BackgroundMaterial, _super);
  112757. /**
  112758. * Instantiates a Background Material in the given scene
  112759. * @param name The friendly name of the material
  112760. * @param scene The scene to add the material to
  112761. */
  112762. function BackgroundMaterial(name, scene) {
  112763. var _this = _super.call(this, name, scene) || this;
  112764. /**
  112765. * Key light Color (multiply against the environement texture)
  112766. */
  112767. _this.primaryColor = BABYLON.Color3.White();
  112768. _this._primaryColorShadowLevel = 0;
  112769. _this._primaryColorHighlightLevel = 0;
  112770. /**
  112771. * Reflection Texture used in the material.
  112772. * Should be author in a specific way for the best result (refer to the documentation).
  112773. */
  112774. _this.reflectionTexture = null;
  112775. /**
  112776. * Reflection Texture level of blur.
  112777. *
  112778. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  112779. * texture twice.
  112780. */
  112781. _this.reflectionBlur = 0;
  112782. /**
  112783. * Diffuse Texture used in the material.
  112784. * Should be author in a specific way for the best result (refer to the documentation).
  112785. */
  112786. _this.diffuseTexture = null;
  112787. _this._shadowLights = null;
  112788. /**
  112789. * Specify the list of lights casting shadow on the material.
  112790. * All scene shadow lights will be included if null.
  112791. */
  112792. _this.shadowLights = null;
  112793. /**
  112794. * Helps adjusting the shadow to a softer level if required.
  112795. * 0 means black shadows and 1 means no shadows.
  112796. */
  112797. _this.shadowLevel = 0;
  112798. /**
  112799. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  112800. * It is usually zero but might be interesting to modify according to your setup.
  112801. */
  112802. _this.sceneCenter = BABYLON.Vector3.Zero();
  112803. /**
  112804. * This helps specifying that the material is falling off to the sky box at grazing angle.
  112805. * This helps ensuring a nice transition when the camera goes under the ground.
  112806. */
  112807. _this.opacityFresnel = true;
  112808. /**
  112809. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  112810. * This helps adding a mirror texture on the ground.
  112811. */
  112812. _this.reflectionFresnel = false;
  112813. /**
  112814. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  112815. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  112816. */
  112817. _this.reflectionFalloffDistance = 0.0;
  112818. /**
  112819. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  112820. */
  112821. _this.reflectionAmount = 1.0;
  112822. /**
  112823. * This specifies the weight of the reflection at grazing angle.
  112824. */
  112825. _this.reflectionReflectance0 = 0.05;
  112826. /**
  112827. * This specifies the weight of the reflection at a perpendicular point of view.
  112828. */
  112829. _this.reflectionReflectance90 = 0.5;
  112830. /**
  112831. * Helps to directly use the maps channels instead of their level.
  112832. */
  112833. _this.useRGBColor = true;
  112834. /**
  112835. * This helps reducing the banding effect that could occur on the background.
  112836. */
  112837. _this.enableNoise = false;
  112838. _this._fovMultiplier = 1.0;
  112839. /**
  112840. * Enable the FOV adjustment feature controlled by fovMultiplier.
  112841. */
  112842. _this.useEquirectangularFOV = false;
  112843. _this._maxSimultaneousLights = 4;
  112844. /**
  112845. * Number of Simultaneous lights allowed on the material.
  112846. */
  112847. _this.maxSimultaneousLights = 4;
  112848. /**
  112849. * Keep track of the image processing observer to allow dispose and replace.
  112850. */
  112851. _this._imageProcessingObserver = null;
  112852. /**
  112853. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  112854. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  112855. */
  112856. _this.switchToBGR = false;
  112857. // Temp values kept as cache in the material.
  112858. _this._renderTargets = new BABYLON.SmartArray(16);
  112859. _this._reflectionControls = BABYLON.Vector4.Zero();
  112860. _this._white = BABYLON.Color3.White();
  112861. _this._primaryShadowColor = BABYLON.Color3.Black();
  112862. _this._primaryHighlightColor = BABYLON.Color3.Black();
  112863. // Setup the default processing configuration to the scene.
  112864. _this._attachImageProcessingConfiguration(null);
  112865. _this.getRenderTargetTextures = function () {
  112866. _this._renderTargets.reset();
  112867. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  112868. _this._renderTargets.push(_this._diffuseTexture);
  112869. }
  112870. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  112871. _this._renderTargets.push(_this._reflectionTexture);
  112872. }
  112873. return _this._renderTargets;
  112874. };
  112875. return _this;
  112876. }
  112877. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  112878. /**
  112879. * Experimental Internal Use Only.
  112880. *
  112881. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  112882. * This acts as a helper to set the primary color to a more "human friendly" value.
  112883. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  112884. * output color as close as possible from the chosen value.
  112885. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  112886. * part of lighting setup.)
  112887. */
  112888. get: function () {
  112889. return this.__perceptualColor;
  112890. },
  112891. set: function (value) {
  112892. this.__perceptualColor = value;
  112893. this._computePrimaryColorFromPerceptualColor();
  112894. this._markAllSubMeshesAsLightsDirty();
  112895. },
  112896. enumerable: true,
  112897. configurable: true
  112898. });
  112899. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  112900. /**
  112901. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  112902. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  112903. */
  112904. get: function () {
  112905. return this._primaryColorShadowLevel;
  112906. },
  112907. set: function (value) {
  112908. this._primaryColorShadowLevel = value;
  112909. this._computePrimaryColors();
  112910. this._markAllSubMeshesAsLightsDirty();
  112911. },
  112912. enumerable: true,
  112913. configurable: true
  112914. });
  112915. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  112916. /**
  112917. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  112918. * The primary color is used at the level chosen to define what the white area would look.
  112919. */
  112920. get: function () {
  112921. return this._primaryColorHighlightLevel;
  112922. },
  112923. set: function (value) {
  112924. this._primaryColorHighlightLevel = value;
  112925. this._computePrimaryColors();
  112926. this._markAllSubMeshesAsLightsDirty();
  112927. },
  112928. enumerable: true,
  112929. configurable: true
  112930. });
  112931. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  112932. /**
  112933. * Sets the reflection reflectance fresnel values according to the default standard
  112934. * empirically know to work well :-)
  112935. */
  112936. set: function (value) {
  112937. var reflectionWeight = value;
  112938. if (reflectionWeight < 0.5) {
  112939. reflectionWeight = reflectionWeight * 2.0;
  112940. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  112941. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  112942. }
  112943. else {
  112944. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  112945. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  112946. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  112947. }
  112948. },
  112949. enumerable: true,
  112950. configurable: true
  112951. });
  112952. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  112953. /**
  112954. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  112955. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  112956. * Recommended to be keep at 1.0 except for special cases.
  112957. */
  112958. get: function () {
  112959. return this._fovMultiplier;
  112960. },
  112961. set: function (value) {
  112962. if (isNaN(value)) {
  112963. value = 1.0;
  112964. }
  112965. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  112966. },
  112967. enumerable: true,
  112968. configurable: true
  112969. });
  112970. /**
  112971. * Attaches a new image processing configuration to the PBR Material.
  112972. * @param configuration (if null the scene configuration will be use)
  112973. */
  112974. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  112975. var _this = this;
  112976. if (configuration === this._imageProcessingConfiguration) {
  112977. return;
  112978. }
  112979. // Detaches observer.
  112980. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  112981. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  112982. }
  112983. // Pick the scene configuration if needed.
  112984. if (!configuration) {
  112985. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  112986. }
  112987. else {
  112988. this._imageProcessingConfiguration = configuration;
  112989. }
  112990. // Attaches observer.
  112991. if (this._imageProcessingConfiguration) {
  112992. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  112993. _this._computePrimaryColorFromPerceptualColor();
  112994. _this._markAllSubMeshesAsImageProcessingDirty();
  112995. });
  112996. }
  112997. };
  112998. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  112999. /**
  113000. * Gets the image processing configuration used either in this material.
  113001. */
  113002. get: function () {
  113003. return this._imageProcessingConfiguration;
  113004. },
  113005. /**
  113006. * Sets the Default image processing configuration used either in the this material.
  113007. *
  113008. * If sets to null, the scene one is in use.
  113009. */
  113010. set: function (value) {
  113011. this._attachImageProcessingConfiguration(value);
  113012. // Ensure the effect will be rebuilt.
  113013. this._markAllSubMeshesAsTexturesDirty();
  113014. },
  113015. enumerable: true,
  113016. configurable: true
  113017. });
  113018. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  113019. /**
  113020. * Gets wether the color curves effect is enabled.
  113021. */
  113022. get: function () {
  113023. return this.imageProcessingConfiguration.colorCurvesEnabled;
  113024. },
  113025. /**
  113026. * Sets wether the color curves effect is enabled.
  113027. */
  113028. set: function (value) {
  113029. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  113030. },
  113031. enumerable: true,
  113032. configurable: true
  113033. });
  113034. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  113035. /**
  113036. * Gets wether the color grading effect is enabled.
  113037. */
  113038. get: function () {
  113039. return this.imageProcessingConfiguration.colorGradingEnabled;
  113040. },
  113041. /**
  113042. * Gets wether the color grading effect is enabled.
  113043. */
  113044. set: function (value) {
  113045. this.imageProcessingConfiguration.colorGradingEnabled = value;
  113046. },
  113047. enumerable: true,
  113048. configurable: true
  113049. });
  113050. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  113051. /**
  113052. * Gets wether tonemapping is enabled or not.
  113053. */
  113054. get: function () {
  113055. return this._imageProcessingConfiguration.toneMappingEnabled;
  113056. },
  113057. /**
  113058. * Sets wether tonemapping is enabled or not
  113059. */
  113060. set: function (value) {
  113061. this._imageProcessingConfiguration.toneMappingEnabled = value;
  113062. },
  113063. enumerable: true,
  113064. configurable: true
  113065. });
  113066. ;
  113067. ;
  113068. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  113069. /**
  113070. * The camera exposure used on this material.
  113071. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  113072. * This corresponds to a photographic exposure.
  113073. */
  113074. get: function () {
  113075. return this._imageProcessingConfiguration.exposure;
  113076. },
  113077. /**
  113078. * The camera exposure used on this material.
  113079. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  113080. * This corresponds to a photographic exposure.
  113081. */
  113082. set: function (value) {
  113083. this._imageProcessingConfiguration.exposure = value;
  113084. },
  113085. enumerable: true,
  113086. configurable: true
  113087. });
  113088. ;
  113089. ;
  113090. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  113091. /**
  113092. * Gets The camera contrast used on this material.
  113093. */
  113094. get: function () {
  113095. return this._imageProcessingConfiguration.contrast;
  113096. },
  113097. /**
  113098. * Sets The camera contrast used on this material.
  113099. */
  113100. set: function (value) {
  113101. this._imageProcessingConfiguration.contrast = value;
  113102. },
  113103. enumerable: true,
  113104. configurable: true
  113105. });
  113106. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  113107. /**
  113108. * Gets the Color Grading 2D Lookup Texture.
  113109. */
  113110. get: function () {
  113111. return this._imageProcessingConfiguration.colorGradingTexture;
  113112. },
  113113. /**
  113114. * Sets the Color Grading 2D Lookup Texture.
  113115. */
  113116. set: function (value) {
  113117. this.imageProcessingConfiguration.colorGradingTexture = value;
  113118. },
  113119. enumerable: true,
  113120. configurable: true
  113121. });
  113122. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  113123. /**
  113124. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  113125. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  113126. * 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;
  113127. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  113128. */
  113129. get: function () {
  113130. return this.imageProcessingConfiguration.colorCurves;
  113131. },
  113132. /**
  113133. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  113134. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  113135. * 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;
  113136. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  113137. */
  113138. set: function (value) {
  113139. this.imageProcessingConfiguration.colorCurves = value;
  113140. },
  113141. enumerable: true,
  113142. configurable: true
  113143. });
  113144. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  113145. /**
  113146. * Gets a boolean indicating that current material needs to register RTT
  113147. */
  113148. get: function () {
  113149. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  113150. return true;
  113151. }
  113152. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  113153. return true;
  113154. }
  113155. return false;
  113156. },
  113157. enumerable: true,
  113158. configurable: true
  113159. });
  113160. /**
  113161. * The entire material has been created in order to prevent overdraw.
  113162. * @returns false
  113163. */
  113164. BackgroundMaterial.prototype.needAlphaTesting = function () {
  113165. return true;
  113166. };
  113167. /**
  113168. * The entire material has been created in order to prevent overdraw.
  113169. * @returns true if blending is enable
  113170. */
  113171. BackgroundMaterial.prototype.needAlphaBlending = function () {
  113172. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  113173. };
  113174. /**
  113175. * Checks wether the material is ready to be rendered for a given mesh.
  113176. * @param mesh The mesh to render
  113177. * @param subMesh The submesh to check against
  113178. * @param useInstances Specify wether or not the material is used with instances
  113179. * @returns true if all the dependencies are ready (Textures, Effects...)
  113180. */
  113181. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  113182. var _this = this;
  113183. if (useInstances === void 0) { useInstances = false; }
  113184. if (subMesh.effect && this.isFrozen) {
  113185. if (this._wasPreviouslyReady) {
  113186. return true;
  113187. }
  113188. }
  113189. if (!subMesh._materialDefines) {
  113190. subMesh._materialDefines = new BackgroundMaterialDefines();
  113191. }
  113192. var scene = this.getScene();
  113193. var defines = subMesh._materialDefines;
  113194. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  113195. if (defines._renderId === scene.getRenderId()) {
  113196. return true;
  113197. }
  113198. }
  113199. var engine = scene.getEngine();
  113200. // Lights
  113201. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  113202. defines._needNormals = true;
  113203. // Textures
  113204. if (defines._areTexturesDirty) {
  113205. defines._needUVs = false;
  113206. if (scene.texturesEnabled) {
  113207. if (scene.getEngine().getCaps().textureLOD) {
  113208. defines.TEXTURELODSUPPORT = true;
  113209. }
  113210. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  113211. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  113212. return false;
  113213. }
  113214. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  113215. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  113216. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  113217. defines.OPACITYFRESNEL = this._opacityFresnel;
  113218. }
  113219. else {
  113220. defines.DIFFUSE = false;
  113221. defines.DIFFUSEHASALPHA = false;
  113222. defines.GAMMADIFFUSE = false;
  113223. defines.OPACITYFRESNEL = false;
  113224. }
  113225. var reflectionTexture = this._reflectionTexture;
  113226. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  113227. if (!reflectionTexture.isReadyOrNotBlocking()) {
  113228. return false;
  113229. }
  113230. defines.REFLECTION = true;
  113231. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  113232. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  113233. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  113234. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  113235. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  113236. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  113237. defines.REFLECTIONBGR = this.switchToBGR;
  113238. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  113239. defines.INVERTCUBICMAP = true;
  113240. }
  113241. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  113242. switch (reflectionTexture.coordinatesMode) {
  113243. case BABYLON.Texture.EXPLICIT_MODE:
  113244. defines.REFLECTIONMAP_EXPLICIT = true;
  113245. break;
  113246. case BABYLON.Texture.PLANAR_MODE:
  113247. defines.REFLECTIONMAP_PLANAR = true;
  113248. break;
  113249. case BABYLON.Texture.PROJECTION_MODE:
  113250. defines.REFLECTIONMAP_PROJECTION = true;
  113251. break;
  113252. case BABYLON.Texture.SKYBOX_MODE:
  113253. defines.REFLECTIONMAP_SKYBOX = true;
  113254. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  113255. break;
  113256. case BABYLON.Texture.SPHERICAL_MODE:
  113257. defines.REFLECTIONMAP_SPHERICAL = true;
  113258. break;
  113259. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  113260. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  113261. break;
  113262. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  113263. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  113264. break;
  113265. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  113266. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  113267. break;
  113268. case BABYLON.Texture.CUBIC_MODE:
  113269. case BABYLON.Texture.INVCUBIC_MODE:
  113270. default:
  113271. defines.REFLECTIONMAP_CUBIC = true;
  113272. break;
  113273. }
  113274. if (this.reflectionFresnel) {
  113275. defines.REFLECTIONFRESNEL = true;
  113276. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  113277. this._reflectionControls.x = this.reflectionAmount;
  113278. this._reflectionControls.y = this.reflectionReflectance0;
  113279. this._reflectionControls.z = this.reflectionReflectance90;
  113280. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  113281. }
  113282. else {
  113283. defines.REFLECTIONFRESNEL = false;
  113284. defines.REFLECTIONFALLOFF = false;
  113285. }
  113286. }
  113287. else {
  113288. defines.REFLECTION = false;
  113289. defines.REFLECTIONFRESNEL = false;
  113290. defines.REFLECTIONFALLOFF = false;
  113291. defines.REFLECTIONBLUR = false;
  113292. defines.REFLECTIONMAP_3D = false;
  113293. defines.REFLECTIONMAP_SPHERICAL = false;
  113294. defines.REFLECTIONMAP_PLANAR = false;
  113295. defines.REFLECTIONMAP_CUBIC = false;
  113296. defines.REFLECTIONMAP_PROJECTION = false;
  113297. defines.REFLECTIONMAP_SKYBOX = false;
  113298. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  113299. defines.REFLECTIONMAP_EXPLICIT = false;
  113300. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  113301. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  113302. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  113303. defines.INVERTCUBICMAP = false;
  113304. defines.REFLECTIONMAP_OPPOSITEZ = false;
  113305. defines.LODINREFLECTIONALPHA = false;
  113306. defines.GAMMAREFLECTION = false;
  113307. defines.RGBDREFLECTION = false;
  113308. }
  113309. }
  113310. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  113311. defines.USERGBCOLOR = this._useRGBColor;
  113312. defines.NOISE = this._enableNoise;
  113313. }
  113314. if (defines._areLightsDirty) {
  113315. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  113316. }
  113317. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  113318. if (!this._imageProcessingConfiguration.isReady()) {
  113319. return false;
  113320. }
  113321. this._imageProcessingConfiguration.prepareDefines(defines);
  113322. }
  113323. // Misc.
  113324. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  113325. // Values that need to be evaluated on every frame
  113326. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  113327. // Attribs
  113328. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  113329. if (mesh) {
  113330. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  113331. mesh.createNormals(true);
  113332. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  113333. }
  113334. }
  113335. }
  113336. // Get correct effect
  113337. if (defines.isDirty) {
  113338. defines.markAsProcessed();
  113339. scene.resetCachedMaterial();
  113340. // Fallbacks
  113341. var fallbacks = new BABYLON.EffectFallbacks();
  113342. if (defines.FOG) {
  113343. fallbacks.addFallback(0, "FOG");
  113344. }
  113345. if (defines.POINTSIZE) {
  113346. fallbacks.addFallback(1, "POINTSIZE");
  113347. }
  113348. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  113349. if (defines.NUM_BONE_INFLUENCERS > 0) {
  113350. fallbacks.addCPUSkinningFallback(0, mesh);
  113351. }
  113352. //Attributes
  113353. var attribs = [BABYLON.VertexBuffer.PositionKind];
  113354. if (defines.NORMAL) {
  113355. attribs.push(BABYLON.VertexBuffer.NormalKind);
  113356. }
  113357. if (defines.UV1) {
  113358. attribs.push(BABYLON.VertexBuffer.UVKind);
  113359. }
  113360. if (defines.UV2) {
  113361. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  113362. }
  113363. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  113364. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  113365. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  113366. "vFogInfos", "vFogColor", "pointSize",
  113367. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  113368. "vPrimaryColor", "vPrimaryColorShadow",
  113369. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  113370. "shadowLevel", "alpha",
  113371. "vBackgroundCenter", "vReflectionControl",
  113372. "vDiffuseInfos", "diffuseMatrix",
  113373. ];
  113374. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  113375. var uniformBuffers = ["Material", "Scene"];
  113376. if (BABYLON.ImageProcessingConfiguration) {
  113377. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  113378. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  113379. }
  113380. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  113381. uniformsNames: uniforms,
  113382. uniformBuffersNames: uniformBuffers,
  113383. samplers: samplers,
  113384. defines: defines,
  113385. maxSimultaneousLights: this._maxSimultaneousLights
  113386. });
  113387. var onCompiled = function (effect) {
  113388. if (_this.onCompiled) {
  113389. _this.onCompiled(effect);
  113390. }
  113391. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  113392. };
  113393. var join = defines.toString();
  113394. subMesh.setEffect(scene.getEngine().createEffect("background", {
  113395. attributes: attribs,
  113396. uniformsNames: uniforms,
  113397. uniformBuffersNames: uniformBuffers,
  113398. samplers: samplers,
  113399. defines: join,
  113400. fallbacks: fallbacks,
  113401. onCompiled: onCompiled,
  113402. onError: this.onError,
  113403. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  113404. }, engine), defines);
  113405. this.buildUniformLayout();
  113406. }
  113407. if (!subMesh.effect || !subMesh.effect.isReady()) {
  113408. return false;
  113409. }
  113410. defines._renderId = scene.getRenderId();
  113411. this._wasPreviouslyReady = true;
  113412. return true;
  113413. };
  113414. /**
  113415. * Compute the primary color according to the chosen perceptual color.
  113416. */
  113417. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  113418. if (!this.__perceptualColor) {
  113419. return;
  113420. }
  113421. this._primaryColor.copyFrom(this.__perceptualColor);
  113422. // Revert gamma space.
  113423. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  113424. // Revert image processing configuration.
  113425. if (this._imageProcessingConfiguration) {
  113426. // Revert Exposure.
  113427. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  113428. }
  113429. this._computePrimaryColors();
  113430. };
  113431. /**
  113432. * Compute the highlights and shadow colors according to their chosen levels.
  113433. */
  113434. BackgroundMaterial.prototype._computePrimaryColors = function () {
  113435. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  113436. return;
  113437. }
  113438. // Find the highlight color based on the configuration.
  113439. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  113440. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  113441. // Find the shadow color based on the configuration.
  113442. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  113443. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  113444. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  113445. };
  113446. /**
  113447. * Build the uniform buffer used in the material.
  113448. */
  113449. BackgroundMaterial.prototype.buildUniformLayout = function () {
  113450. // Order is important !
  113451. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  113452. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  113453. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  113454. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  113455. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  113456. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  113457. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  113458. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  113459. this._uniformBuffer.addUniform("pointSize", 1);
  113460. this._uniformBuffer.addUniform("shadowLevel", 1);
  113461. this._uniformBuffer.addUniform("alpha", 1);
  113462. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  113463. this._uniformBuffer.addUniform("vReflectionControl", 4);
  113464. this._uniformBuffer.create();
  113465. };
  113466. /**
  113467. * Unbind the material.
  113468. */
  113469. BackgroundMaterial.prototype.unbind = function () {
  113470. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  113471. this._uniformBuffer.setTexture("diffuseSampler", null);
  113472. }
  113473. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  113474. this._uniformBuffer.setTexture("reflectionSampler", null);
  113475. }
  113476. _super.prototype.unbind.call(this);
  113477. };
  113478. /**
  113479. * Bind only the world matrix to the material.
  113480. * @param world The world matrix to bind.
  113481. */
  113482. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  113483. this._activeEffect.setMatrix("world", world);
  113484. };
  113485. /**
  113486. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  113487. * @param world The world matrix to bind.
  113488. * @param subMesh The submesh to bind for.
  113489. */
  113490. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  113491. var scene = this.getScene();
  113492. var defines = subMesh._materialDefines;
  113493. if (!defines) {
  113494. return;
  113495. }
  113496. var effect = subMesh.effect;
  113497. if (!effect) {
  113498. return;
  113499. }
  113500. this._activeEffect = effect;
  113501. // Matrices
  113502. this.bindOnlyWorldMatrix(world);
  113503. // Bones
  113504. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  113505. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  113506. if (mustRebind) {
  113507. this._uniformBuffer.bindToEffect(effect, "Material");
  113508. this.bindViewProjection(effect);
  113509. var reflectionTexture = this._reflectionTexture;
  113510. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  113511. // Texture uniforms
  113512. if (scene.texturesEnabled) {
  113513. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  113514. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  113515. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  113516. }
  113517. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  113518. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  113519. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  113520. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  113521. }
  113522. }
  113523. if (this.shadowLevel > 0) {
  113524. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  113525. }
  113526. this._uniformBuffer.updateFloat("alpha", this.alpha);
  113527. // Point size
  113528. if (this.pointsCloud) {
  113529. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  113530. }
  113531. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  113532. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  113533. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  113534. }
  113535. else {
  113536. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  113537. }
  113538. }
  113539. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  113540. // Textures
  113541. if (scene.texturesEnabled) {
  113542. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  113543. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  113544. }
  113545. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  113546. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  113547. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  113548. }
  113549. else if (!defines.REFLECTIONBLUR) {
  113550. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  113551. }
  113552. else {
  113553. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  113554. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  113555. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  113556. }
  113557. if (defines.REFLECTIONFRESNEL) {
  113558. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  113559. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  113560. }
  113561. }
  113562. }
  113563. // Clip plane
  113564. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  113565. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  113566. }
  113567. if (mustRebind || !this.isFrozen) {
  113568. if (scene.lightsEnabled) {
  113569. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  113570. }
  113571. // View
  113572. this.bindView(effect);
  113573. // Fog
  113574. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  113575. // image processing
  113576. if (this._imageProcessingConfiguration) {
  113577. this._imageProcessingConfiguration.bind(this._activeEffect);
  113578. }
  113579. }
  113580. this._uniformBuffer.update();
  113581. this._afterBind(mesh, this._activeEffect);
  113582. };
  113583. /**
  113584. * Dispose the material.
  113585. * @param forceDisposeEffect Force disposal of the associated effect.
  113586. * @param forceDisposeTextures Force disposal of the associated textures.
  113587. */
  113588. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  113589. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  113590. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  113591. if (forceDisposeTextures) {
  113592. if (this.diffuseTexture) {
  113593. this.diffuseTexture.dispose();
  113594. }
  113595. if (this.reflectionTexture) {
  113596. this.reflectionTexture.dispose();
  113597. }
  113598. }
  113599. this._renderTargets.dispose();
  113600. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  113601. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  113602. }
  113603. _super.prototype.dispose.call(this, forceDisposeEffect);
  113604. };
  113605. /**
  113606. * Clones the material.
  113607. * @param name The cloned name.
  113608. * @returns The cloned material.
  113609. */
  113610. BackgroundMaterial.prototype.clone = function (name) {
  113611. var _this = this;
  113612. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  113613. };
  113614. /**
  113615. * Serializes the current material to its JSON representation.
  113616. * @returns The JSON representation.
  113617. */
  113618. BackgroundMaterial.prototype.serialize = function () {
  113619. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  113620. serializationObject.customType = "BABYLON.BackgroundMaterial";
  113621. return serializationObject;
  113622. };
  113623. /**
  113624. * Gets the class name of the material
  113625. * @returns "BackgroundMaterial"
  113626. */
  113627. BackgroundMaterial.prototype.getClassName = function () {
  113628. return "BackgroundMaterial";
  113629. };
  113630. /**
  113631. * Parse a JSON input to create back a background material.
  113632. * @param source The JSON data to parse
  113633. * @param scene The scene to create the parsed material in
  113634. * @param rootUrl The root url of the assets the material depends upon
  113635. * @returns the instantiated BackgroundMaterial.
  113636. */
  113637. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  113638. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  113639. };
  113640. /**
  113641. * Standard reflectance value at parallel view angle.
  113642. */
  113643. BackgroundMaterial.StandardReflectance0 = 0.05;
  113644. /**
  113645. * Standard reflectance value at grazing angle.
  113646. */
  113647. BackgroundMaterial.StandardReflectance90 = 0.5;
  113648. __decorate([
  113649. BABYLON.serializeAsColor3()
  113650. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  113651. __decorate([
  113652. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  113653. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  113654. __decorate([
  113655. BABYLON.serializeAsColor3()
  113656. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  113657. __decorate([
  113658. BABYLON.serialize()
  113659. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  113660. __decorate([
  113661. BABYLON.serialize()
  113662. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  113663. __decorate([
  113664. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  113665. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  113666. __decorate([
  113667. BABYLON.serializeAsTexture()
  113668. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  113669. __decorate([
  113670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113671. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  113672. __decorate([
  113673. BABYLON.serialize()
  113674. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  113675. __decorate([
  113676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113677. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  113678. __decorate([
  113679. BABYLON.serializeAsTexture()
  113680. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  113681. __decorate([
  113682. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113683. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  113684. __decorate([
  113685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113686. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  113687. __decorate([
  113688. BABYLON.serialize()
  113689. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  113690. __decorate([
  113691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113692. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  113693. __decorate([
  113694. BABYLON.serializeAsVector3()
  113695. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  113696. __decorate([
  113697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113698. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  113699. __decorate([
  113700. BABYLON.serialize()
  113701. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  113702. __decorate([
  113703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113704. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  113705. __decorate([
  113706. BABYLON.serialize()
  113707. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  113708. __decorate([
  113709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113710. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  113711. __decorate([
  113712. BABYLON.serialize()
  113713. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  113714. __decorate([
  113715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113716. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  113717. __decorate([
  113718. BABYLON.serialize()
  113719. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  113720. __decorate([
  113721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113722. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  113723. __decorate([
  113724. BABYLON.serialize()
  113725. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  113726. __decorate([
  113727. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113728. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  113729. __decorate([
  113730. BABYLON.serialize()
  113731. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  113732. __decorate([
  113733. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113734. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  113735. __decorate([
  113736. BABYLON.serialize()
  113737. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  113738. __decorate([
  113739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113740. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  113741. __decorate([
  113742. BABYLON.serialize()
  113743. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  113744. __decorate([
  113745. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113746. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  113747. __decorate([
  113748. BABYLON.serialize()
  113749. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  113750. __decorate([
  113751. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113752. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  113753. __decorate([
  113754. BABYLON.serializeAsImageProcessingConfiguration()
  113755. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  113756. return BackgroundMaterial;
  113757. }(BABYLON.PushMaterial));
  113758. BABYLON.BackgroundMaterial = BackgroundMaterial;
  113759. })(BABYLON || (BABYLON = {}));
  113760. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  113761. var __assign = (this && this.__assign) || function () {
  113762. __assign = Object.assign || function(t) {
  113763. for (var s, i = 1, n = arguments.length; i < n; i++) {
  113764. s = arguments[i];
  113765. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  113766. t[p] = s[p];
  113767. }
  113768. return t;
  113769. };
  113770. return __assign.apply(this, arguments);
  113771. };
  113772. var BABYLON;
  113773. (function (BABYLON) {
  113774. /**
  113775. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  113776. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  113777. * It also helps with the default setup of your imageProcessing configuration.
  113778. */
  113779. var EnvironmentHelper = /** @class */ (function () {
  113780. /**
  113781. * constructor
  113782. * @param options
  113783. * @param scene The scene to add the material to
  113784. */
  113785. function EnvironmentHelper(options, scene) {
  113786. var _this = this;
  113787. this._errorHandler = function (message, exception) {
  113788. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  113789. };
  113790. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  113791. this._scene = scene;
  113792. this.onErrorObservable = new BABYLON.Observable();
  113793. this._setupBackground();
  113794. this._setupImageProcessing();
  113795. }
  113796. /**
  113797. * Creates the default options for the helper.
  113798. */
  113799. EnvironmentHelper._getDefaultOptions = function () {
  113800. return {
  113801. createGround: true,
  113802. groundSize: 15,
  113803. groundTexture: this._groundTextureCDNUrl,
  113804. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  113805. groundOpacity: 0.9,
  113806. enableGroundShadow: true,
  113807. groundShadowLevel: 0.5,
  113808. enableGroundMirror: false,
  113809. groundMirrorSizeRatio: 0.3,
  113810. groundMirrorBlurKernel: 64,
  113811. groundMirrorAmount: 1,
  113812. groundMirrorFresnelWeight: 1,
  113813. groundMirrorFallOffDistance: 0,
  113814. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  113815. groundYBias: 0.00001,
  113816. createSkybox: true,
  113817. skyboxSize: 20,
  113818. skyboxTexture: this._skyboxTextureCDNUrl,
  113819. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  113820. backgroundYRotation: 0,
  113821. sizeAuto: true,
  113822. rootPosition: BABYLON.Vector3.Zero(),
  113823. setupImageProcessing: true,
  113824. environmentTexture: this._environmentTextureCDNUrl,
  113825. cameraExposure: 0.8,
  113826. cameraContrast: 1.2,
  113827. toneMappingEnabled: true,
  113828. };
  113829. };
  113830. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  113831. /**
  113832. * Gets the root mesh created by the helper.
  113833. */
  113834. get: function () {
  113835. return this._rootMesh;
  113836. },
  113837. enumerable: true,
  113838. configurable: true
  113839. });
  113840. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  113841. /**
  113842. * Gets the skybox created by the helper.
  113843. */
  113844. get: function () {
  113845. return this._skybox;
  113846. },
  113847. enumerable: true,
  113848. configurable: true
  113849. });
  113850. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  113851. /**
  113852. * Gets the skybox texture created by the helper.
  113853. */
  113854. get: function () {
  113855. return this._skyboxTexture;
  113856. },
  113857. enumerable: true,
  113858. configurable: true
  113859. });
  113860. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  113861. /**
  113862. * Gets the skybox material created by the helper.
  113863. */
  113864. get: function () {
  113865. return this._skyboxMaterial;
  113866. },
  113867. enumerable: true,
  113868. configurable: true
  113869. });
  113870. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  113871. /**
  113872. * Gets the ground mesh created by the helper.
  113873. */
  113874. get: function () {
  113875. return this._ground;
  113876. },
  113877. enumerable: true,
  113878. configurable: true
  113879. });
  113880. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  113881. /**
  113882. * Gets the ground texture created by the helper.
  113883. */
  113884. get: function () {
  113885. return this._groundTexture;
  113886. },
  113887. enumerable: true,
  113888. configurable: true
  113889. });
  113890. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  113891. /**
  113892. * Gets the ground mirror created by the helper.
  113893. */
  113894. get: function () {
  113895. return this._groundMirror;
  113896. },
  113897. enumerable: true,
  113898. configurable: true
  113899. });
  113900. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  113901. /**
  113902. * Gets the ground mirror render list to helps pushing the meshes
  113903. * you wish in the ground reflection.
  113904. */
  113905. get: function () {
  113906. if (this._groundMirror) {
  113907. return this._groundMirror.renderList;
  113908. }
  113909. return null;
  113910. },
  113911. enumerable: true,
  113912. configurable: true
  113913. });
  113914. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  113915. /**
  113916. * Gets the ground material created by the helper.
  113917. */
  113918. get: function () {
  113919. return this._groundMaterial;
  113920. },
  113921. enumerable: true,
  113922. configurable: true
  113923. });
  113924. /**
  113925. * Updates the background according to the new options
  113926. * @param options
  113927. */
  113928. EnvironmentHelper.prototype.updateOptions = function (options) {
  113929. var newOptions = __assign({}, this._options, options);
  113930. if (this._ground && !newOptions.createGround) {
  113931. this._ground.dispose();
  113932. this._ground = null;
  113933. }
  113934. if (this._groundMaterial && !newOptions.createGround) {
  113935. this._groundMaterial.dispose();
  113936. this._groundMaterial = null;
  113937. }
  113938. if (this._groundTexture) {
  113939. if (this._options.groundTexture != newOptions.groundTexture) {
  113940. this._groundTexture.dispose();
  113941. this._groundTexture = null;
  113942. }
  113943. }
  113944. if (this._skybox && !newOptions.createSkybox) {
  113945. this._skybox.dispose();
  113946. this._skybox = null;
  113947. }
  113948. if (this._skyboxMaterial && !newOptions.createSkybox) {
  113949. this._skyboxMaterial.dispose();
  113950. this._skyboxMaterial = null;
  113951. }
  113952. if (this._skyboxTexture) {
  113953. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  113954. this._skyboxTexture.dispose();
  113955. this._skyboxTexture = null;
  113956. }
  113957. }
  113958. if (this._groundMirror && !newOptions.enableGroundMirror) {
  113959. this._groundMirror.dispose();
  113960. this._groundMirror = null;
  113961. }
  113962. if (this._scene.environmentTexture) {
  113963. if (this._options.environmentTexture != newOptions.environmentTexture) {
  113964. this._scene.environmentTexture.dispose();
  113965. }
  113966. }
  113967. this._options = newOptions;
  113968. this._setupBackground();
  113969. this._setupImageProcessing();
  113970. };
  113971. /**
  113972. * Sets the primary color of all the available elements.
  113973. * @param color the main color to affect to the ground and the background
  113974. */
  113975. EnvironmentHelper.prototype.setMainColor = function (color) {
  113976. if (this.groundMaterial) {
  113977. this.groundMaterial.primaryColor = color;
  113978. }
  113979. if (this.skyboxMaterial) {
  113980. this.skyboxMaterial.primaryColor = color;
  113981. }
  113982. if (this.groundMirror) {
  113983. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  113984. }
  113985. };
  113986. /**
  113987. * Setup the image processing according to the specified options.
  113988. */
  113989. EnvironmentHelper.prototype._setupImageProcessing = function () {
  113990. if (this._options.setupImageProcessing) {
  113991. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  113992. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  113993. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  113994. this._setupEnvironmentTexture();
  113995. }
  113996. };
  113997. /**
  113998. * Setup the environment texture according to the specified options.
  113999. */
  114000. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  114001. if (this._scene.environmentTexture) {
  114002. return;
  114003. }
  114004. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  114005. this._scene.environmentTexture = this._options.environmentTexture;
  114006. return;
  114007. }
  114008. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  114009. this._scene.environmentTexture = environmentTexture;
  114010. };
  114011. /**
  114012. * Setup the background according to the specified options.
  114013. */
  114014. EnvironmentHelper.prototype._setupBackground = function () {
  114015. if (!this._rootMesh) {
  114016. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  114017. }
  114018. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  114019. var sceneSize = this._getSceneSize();
  114020. if (this._options.createGround) {
  114021. this._setupGround(sceneSize);
  114022. this._setupGroundMaterial();
  114023. this._setupGroundDiffuseTexture();
  114024. if (this._options.enableGroundMirror) {
  114025. this._setupGroundMirrorTexture(sceneSize);
  114026. }
  114027. this._setupMirrorInGroundMaterial();
  114028. }
  114029. if (this._options.createSkybox) {
  114030. this._setupSkybox(sceneSize);
  114031. this._setupSkyboxMaterial();
  114032. this._setupSkyboxReflectionTexture();
  114033. }
  114034. this._rootMesh.position.x = sceneSize.rootPosition.x;
  114035. this._rootMesh.position.z = sceneSize.rootPosition.z;
  114036. this._rootMesh.position.y = sceneSize.rootPosition.y;
  114037. };
  114038. /**
  114039. * Get the scene sizes according to the setup.
  114040. */
  114041. EnvironmentHelper.prototype._getSceneSize = function () {
  114042. var _this = this;
  114043. var groundSize = this._options.groundSize;
  114044. var skyboxSize = this._options.skyboxSize;
  114045. var rootPosition = this._options.rootPosition;
  114046. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  114047. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  114048. }
  114049. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  114050. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  114051. });
  114052. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  114053. if (this._options.sizeAuto) {
  114054. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  114055. this._scene.activeCamera.upperRadiusLimit) {
  114056. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  114057. skyboxSize = groundSize;
  114058. }
  114059. var sceneDiagonalLenght = sceneDiagonal.length();
  114060. if (sceneDiagonalLenght > groundSize) {
  114061. groundSize = sceneDiagonalLenght * 2;
  114062. skyboxSize = groundSize;
  114063. }
  114064. // 10 % bigger.
  114065. groundSize *= 1.1;
  114066. skyboxSize *= 1.5;
  114067. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  114068. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  114069. }
  114070. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  114071. };
  114072. /**
  114073. * Setup the ground according to the specified options.
  114074. */
  114075. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  114076. var _this = this;
  114077. if (!this._ground || this._ground.isDisposed()) {
  114078. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  114079. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  114080. this._ground.parent = this._rootMesh;
  114081. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  114082. }
  114083. this._ground.receiveShadows = this._options.enableGroundShadow;
  114084. };
  114085. /**
  114086. * Setup the ground material according to the specified options.
  114087. */
  114088. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  114089. if (!this._groundMaterial) {
  114090. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  114091. }
  114092. this._groundMaterial.alpha = this._options.groundOpacity;
  114093. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  114094. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  114095. this._groundMaterial.primaryColor = this._options.groundColor;
  114096. this._groundMaterial.useRGBColor = false;
  114097. this._groundMaterial.enableNoise = true;
  114098. if (this._ground) {
  114099. this._ground.material = this._groundMaterial;
  114100. }
  114101. };
  114102. /**
  114103. * Setup the ground diffuse texture according to the specified options.
  114104. */
  114105. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  114106. if (!this._groundMaterial) {
  114107. return;
  114108. }
  114109. if (this._groundTexture) {
  114110. return;
  114111. }
  114112. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  114113. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  114114. return;
  114115. }
  114116. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  114117. diffuseTexture.gammaSpace = false;
  114118. diffuseTexture.hasAlpha = true;
  114119. this._groundMaterial.diffuseTexture = diffuseTexture;
  114120. };
  114121. /**
  114122. * Setup the ground mirror texture according to the specified options.
  114123. */
  114124. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  114125. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114126. if (!this._groundMirror) {
  114127. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  114128. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  114129. this._groundMirror.anisotropicFilteringLevel = 1;
  114130. this._groundMirror.wrapU = wrapping;
  114131. this._groundMirror.wrapV = wrapping;
  114132. this._groundMirror.gammaSpace = false;
  114133. if (this._groundMirror.renderList) {
  114134. for (var i = 0; i < this._scene.meshes.length; i++) {
  114135. var mesh = this._scene.meshes[i];
  114136. if (mesh !== this._ground &&
  114137. mesh !== this._skybox &&
  114138. mesh !== this._rootMesh) {
  114139. this._groundMirror.renderList.push(mesh);
  114140. }
  114141. }
  114142. }
  114143. }
  114144. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  114145. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  114146. };
  114147. /**
  114148. * Setup the ground to receive the mirror texture.
  114149. */
  114150. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  114151. if (this._groundMaterial) {
  114152. this._groundMaterial.reflectionTexture = this._groundMirror;
  114153. this._groundMaterial.reflectionFresnel = true;
  114154. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  114155. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  114156. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  114157. }
  114158. };
  114159. /**
  114160. * Setup the skybox according to the specified options.
  114161. */
  114162. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  114163. var _this = this;
  114164. if (!this._skybox || this._skybox.isDisposed()) {
  114165. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  114166. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  114167. }
  114168. this._skybox.parent = this._rootMesh;
  114169. };
  114170. /**
  114171. * Setup the skybox material according to the specified options.
  114172. */
  114173. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  114174. if (!this._skybox) {
  114175. return;
  114176. }
  114177. if (!this._skyboxMaterial) {
  114178. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  114179. }
  114180. this._skyboxMaterial.useRGBColor = false;
  114181. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  114182. this._skyboxMaterial.enableNoise = true;
  114183. this._skybox.material = this._skyboxMaterial;
  114184. };
  114185. /**
  114186. * Setup the skybox reflection texture according to the specified options.
  114187. */
  114188. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  114189. if (!this._skyboxMaterial) {
  114190. return;
  114191. }
  114192. if (this._skyboxTexture) {
  114193. return;
  114194. }
  114195. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  114196. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  114197. return;
  114198. }
  114199. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  114200. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  114201. this._skyboxTexture.gammaSpace = false;
  114202. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  114203. };
  114204. /**
  114205. * Dispose all the elements created by the Helper.
  114206. */
  114207. EnvironmentHelper.prototype.dispose = function () {
  114208. if (this._groundMaterial) {
  114209. this._groundMaterial.dispose(true, true);
  114210. }
  114211. if (this._skyboxMaterial) {
  114212. this._skyboxMaterial.dispose(true, true);
  114213. }
  114214. this._rootMesh.dispose(false);
  114215. };
  114216. /**
  114217. * Default ground texture URL.
  114218. */
  114219. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  114220. /**
  114221. * Default skybox texture URL.
  114222. */
  114223. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  114224. /**
  114225. * Default environment texture URL.
  114226. */
  114227. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  114228. return EnvironmentHelper;
  114229. }());
  114230. BABYLON.EnvironmentHelper = EnvironmentHelper;
  114231. })(BABYLON || (BABYLON = {}));
  114232. //# sourceMappingURL=babylon.environmentHelper.js.map
  114233. var BABYLON;
  114234. (function (BABYLON) {
  114235. /** Internal class used to store shapes for emitters */
  114236. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  114237. function ParticleSystemSetEmitterCreationOptions() {
  114238. }
  114239. return ParticleSystemSetEmitterCreationOptions;
  114240. }());
  114241. /**
  114242. * Represents a set of particle systems working together to create a specific effect
  114243. */
  114244. var ParticleSystemSet = /** @class */ (function () {
  114245. function ParticleSystemSet() {
  114246. /**
  114247. * Gets the particle system list
  114248. */
  114249. this.systems = new Array();
  114250. }
  114251. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  114252. /**
  114253. * Gets the emitter node used with this set
  114254. */
  114255. get: function () {
  114256. return this._emitterNode;
  114257. },
  114258. enumerable: true,
  114259. configurable: true
  114260. });
  114261. /**
  114262. * Creates a new emitter mesh as a sphere
  114263. * @param options defines the options used to create the sphere
  114264. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  114265. * @param scene defines the hosting scene
  114266. */
  114267. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  114268. if (this._emitterNode) {
  114269. this._emitterNode.dispose();
  114270. }
  114271. this._emitterCreationOptions = {
  114272. kind: "Sphere",
  114273. options: options,
  114274. renderingGroupId: renderingGroupId
  114275. };
  114276. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  114277. emitterMesh.renderingGroupId = renderingGroupId;
  114278. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  114279. material.emissiveColor = options.color;
  114280. emitterMesh.material = material;
  114281. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  114282. var system = _a[_i];
  114283. system.emitter = emitterMesh;
  114284. }
  114285. this._emitterNode = emitterMesh;
  114286. };
  114287. /**
  114288. * Starts all particle systems of the set
  114289. * @param emitter defines an optional mesh to use as emitter for the particle systems
  114290. */
  114291. ParticleSystemSet.prototype.start = function (emitter) {
  114292. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  114293. var system = _a[_i];
  114294. if (emitter) {
  114295. system.emitter = emitter;
  114296. }
  114297. system.start();
  114298. }
  114299. };
  114300. /**
  114301. * Release all associated resources
  114302. */
  114303. ParticleSystemSet.prototype.dispose = function () {
  114304. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  114305. var system = _a[_i];
  114306. system.dispose();
  114307. }
  114308. this.systems = [];
  114309. if (this._emitterNode) {
  114310. this._emitterNode.dispose();
  114311. this._emitterNode = null;
  114312. }
  114313. };
  114314. /**
  114315. * Serialize the set into a JSON compatible object
  114316. * @returns a JSON compatible representation of the set
  114317. */
  114318. ParticleSystemSet.prototype.serialize = function () {
  114319. var result = {};
  114320. result.systems = [];
  114321. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  114322. var system = _a[_i];
  114323. result.systems.push(system.serialize());
  114324. }
  114325. if (this._emitterNode) {
  114326. result.emitter = this._emitterCreationOptions;
  114327. }
  114328. return result;
  114329. };
  114330. /**
  114331. * Parse a new ParticleSystemSet from a serialized source
  114332. * @param data defines a JSON compatible representation of the set
  114333. * @param scene defines the hosting scene
  114334. * @param gpu defines if we want GPU particles or CPU particles
  114335. * @returns a new ParticleSystemSet
  114336. */
  114337. ParticleSystemSet.Parse = function (data, scene, gpu) {
  114338. if (gpu === void 0) { gpu = false; }
  114339. var result = new ParticleSystemSet();
  114340. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  114341. scene = scene || BABYLON.Engine.LastCreatedScene;
  114342. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  114343. var system = _a[_i];
  114344. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl, true) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl, true));
  114345. }
  114346. if (data.emitter) {
  114347. var options = data.emitter.options;
  114348. switch (data.emitter.kind) {
  114349. case "Sphere":
  114350. result.setEmitterAsSphere({
  114351. diameter: options.diameter,
  114352. segments: options.segments,
  114353. color: BABYLON.Color3.FromArray(options.color)
  114354. }, data.emitter.renderingGroupId, scene);
  114355. break;
  114356. }
  114357. }
  114358. return result;
  114359. };
  114360. return ParticleSystemSet;
  114361. }());
  114362. BABYLON.ParticleSystemSet = ParticleSystemSet;
  114363. })(BABYLON || (BABYLON = {}));
  114364. //# sourceMappingURL=babylon.particleSystemSet.js.map
  114365. var BABYLON;
  114366. (function (BABYLON) {
  114367. /**
  114368. * This class is made for on one-liner static method to help creating particle system set.
  114369. */
  114370. var ParticleHelper = /** @class */ (function () {
  114371. function ParticleHelper() {
  114372. }
  114373. /**
  114374. * Create a default particle system that you can tweak
  114375. * @param emitter defines the emitter to use
  114376. * @param capacity defines the system capacity (default is 500 particles)
  114377. * @param scene defines the hosting scene
  114378. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  114379. * @returns the new Particle system
  114380. */
  114381. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  114382. if (capacity === void 0) { capacity = 500; }
  114383. if (useGPU === void 0) { useGPU = false; }
  114384. var system;
  114385. if (useGPU) {
  114386. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  114387. }
  114388. else {
  114389. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  114390. }
  114391. system.emitter = emitter;
  114392. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  114393. system.createConeEmitter(0.1, Math.PI / 4);
  114394. // Particle color
  114395. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  114396. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  114397. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  114398. // Particle Size
  114399. system.minSize = 0.1;
  114400. system.maxSize = 0.1;
  114401. // Emission speed
  114402. system.minEmitPower = 2;
  114403. system.maxEmitPower = 2;
  114404. // Update speed
  114405. system.updateSpeed = 1 / 60;
  114406. system.emitRate = 30;
  114407. return system;
  114408. };
  114409. /**
  114410. * This is the main static method (one-liner) of this helper to create different particle systems
  114411. * @param type This string represents the type to the particle system to create
  114412. * @param scene The scene where the particle system should live
  114413. * @param gpu If the system will use gpu
  114414. * @returns the ParticleSystemSet created
  114415. */
  114416. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  114417. if (gpu === void 0) { gpu = false; }
  114418. if (!scene) {
  114419. scene = BABYLON.Engine.LastCreatedScene;
  114420. ;
  114421. }
  114422. var token = {};
  114423. scene._addPendingData(token);
  114424. return new Promise(function (resolve, reject) {
  114425. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  114426. scene._removePendingData(token);
  114427. return reject("Particle system with GPU is not supported.");
  114428. }
  114429. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  114430. scene._removePendingData(token);
  114431. var newData = JSON.parse(data.toString());
  114432. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  114433. }, undefined, undefined, undefined, function (req, exception) {
  114434. scene._removePendingData(token);
  114435. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  114436. });
  114437. });
  114438. };
  114439. /**
  114440. * Static function used to export a particle system to a ParticleSystemSet variable.
  114441. * Please note that the emitter shape is not exported
  114442. * @param systems defines the particle systems to export
  114443. * @returns the created particle system set
  114444. */
  114445. ParticleHelper.ExportSet = function (systems) {
  114446. var set = new BABYLON.ParticleSystemSet();
  114447. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  114448. var system = systems_1[_i];
  114449. set.systems.push(system);
  114450. }
  114451. return set;
  114452. };
  114453. /**
  114454. * Gets or sets base Assets URL
  114455. */
  114456. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  114457. return ParticleHelper;
  114458. }());
  114459. BABYLON.ParticleHelper = ParticleHelper;
  114460. })(BABYLON || (BABYLON = {}));
  114461. //# sourceMappingURL=babylon.particleHelper.js.map
  114462. var BABYLON;
  114463. (function (BABYLON) {
  114464. /**
  114465. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  114466. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  114467. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  114468. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  114469. */
  114470. var VideoDome = /** @class */ (function (_super) {
  114471. __extends(VideoDome, _super);
  114472. /**
  114473. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  114474. * @param name Element's name, child elements will append suffixes for their own names.
  114475. * @param urlsOrVideo defines the url(s) or the video element to use
  114476. * @param options An object containing optional or exposed sub element properties
  114477. */
  114478. function VideoDome(name, urlsOrVideo, options, scene) {
  114479. var _this = _super.call(this, name, scene) || this;
  114480. _this._useDirectMapping = false;
  114481. // set defaults and manage values
  114482. name = name || "videoDome";
  114483. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  114484. options.clickToPlay = Boolean(options.clickToPlay);
  114485. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  114486. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  114487. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  114488. if (options.useDirectMapping === undefined) {
  114489. _this._useDirectMapping = true;
  114490. }
  114491. else {
  114492. _this._useDirectMapping = options.useDirectMapping;
  114493. }
  114494. _this._setReady(false);
  114495. // create
  114496. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  114497. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  114498. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  114499. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  114500. texture.onLoadObservable.addOnce(function () {
  114501. _this._setReady(true);
  114502. });
  114503. // configure material
  114504. material.useEquirectangularFOV = true;
  114505. material.fovMultiplier = 1.0;
  114506. material.opacityFresnel = false;
  114507. if (_this._useDirectMapping) {
  114508. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114509. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114510. material.diffuseTexture = texture;
  114511. }
  114512. else {
  114513. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  114514. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114515. material.reflectionTexture = texture;
  114516. }
  114517. // configure mesh
  114518. _this._mesh.material = material;
  114519. _this._mesh.parent = _this;
  114520. // optional configuration
  114521. if (options.clickToPlay) {
  114522. scene.onPointerUp = function () {
  114523. _this._videoTexture.video.play();
  114524. };
  114525. }
  114526. return _this;
  114527. }
  114528. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  114529. /**
  114530. * Gets the video texture being displayed on the sphere
  114531. */
  114532. get: function () {
  114533. return this._videoTexture;
  114534. },
  114535. enumerable: true,
  114536. configurable: true
  114537. });
  114538. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  114539. /**
  114540. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  114541. * Also see the options.resolution property.
  114542. */
  114543. get: function () {
  114544. return this._material.fovMultiplier;
  114545. },
  114546. set: function (value) {
  114547. this._material.fovMultiplier = value;
  114548. },
  114549. enumerable: true,
  114550. configurable: true
  114551. });
  114552. /**
  114553. * Releases resources associated with this node.
  114554. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  114555. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  114556. */
  114557. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  114558. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  114559. this._videoTexture.dispose();
  114560. this._mesh.dispose();
  114561. this._material.dispose();
  114562. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  114563. };
  114564. return VideoDome;
  114565. }(BABYLON.TransformNode));
  114566. BABYLON.VideoDome = VideoDome;
  114567. })(BABYLON || (BABYLON = {}));
  114568. //# sourceMappingURL=babylon.videoDome.js.map
  114569. var BABYLON;
  114570. (function (BABYLON) {
  114571. /**
  114572. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  114573. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  114574. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  114575. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  114576. */
  114577. var PhotoDome = /** @class */ (function (_super) {
  114578. __extends(PhotoDome, _super);
  114579. /**
  114580. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  114581. * @param name Element's name, child elements will append suffixes for their own names.
  114582. * @param urlsOfPhoto defines the url of the photo to display
  114583. * @param options defines an object containing optional or exposed sub element properties
  114584. * @param onError defines a callback called when an error occured while loading the texture
  114585. */
  114586. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  114587. if (onError === void 0) { onError = null; }
  114588. var _this = _super.call(this, name, scene) || this;
  114589. _this._useDirectMapping = false;
  114590. /**
  114591. * Observable raised when an error occured while loading the 360 image
  114592. */
  114593. _this.onLoadErrorObservable = new BABYLON.Observable();
  114594. // set defaults and manage values
  114595. name = name || "photoDome";
  114596. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  114597. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  114598. if (options.useDirectMapping === undefined) {
  114599. _this._useDirectMapping = true;
  114600. }
  114601. else {
  114602. _this._useDirectMapping = options.useDirectMapping;
  114603. }
  114604. _this._setReady(false);
  114605. // create
  114606. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  114607. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  114608. // configure material
  114609. material.opacityFresnel = false;
  114610. material.useEquirectangularFOV = true;
  114611. material.fovMultiplier = 1.0;
  114612. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  114613. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  114614. if (onError) {
  114615. onError(message, exception);
  114616. }
  114617. });
  114618. _this.photoTexture.onLoadObservable.addOnce(function () {
  114619. _this._setReady(true);
  114620. });
  114621. // configure mesh
  114622. _this._mesh.material = material;
  114623. _this._mesh.parent = _this;
  114624. return _this;
  114625. }
  114626. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  114627. /**
  114628. * Gets or sets the texture being displayed on the sphere
  114629. */
  114630. get: function () {
  114631. return this._photoTexture;
  114632. },
  114633. set: function (value) {
  114634. if (this._photoTexture === value) {
  114635. return;
  114636. }
  114637. this._photoTexture = value;
  114638. if (this._useDirectMapping) {
  114639. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114640. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114641. this._material.diffuseTexture = this._photoTexture;
  114642. }
  114643. else {
  114644. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  114645. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114646. this._material.reflectionTexture = this._photoTexture;
  114647. }
  114648. },
  114649. enumerable: true,
  114650. configurable: true
  114651. });
  114652. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  114653. /**
  114654. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  114655. * Also see the options.resolution property.
  114656. */
  114657. get: function () {
  114658. return this._material.fovMultiplier;
  114659. },
  114660. set: function (value) {
  114661. this._material.fovMultiplier = value;
  114662. },
  114663. enumerable: true,
  114664. configurable: true
  114665. });
  114666. /**
  114667. * Releases resources associated with this node.
  114668. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  114669. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  114670. */
  114671. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  114672. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  114673. this._photoTexture.dispose();
  114674. this._mesh.dispose();
  114675. this._material.dispose();
  114676. this.onLoadErrorObservable.clear();
  114677. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  114678. };
  114679. return PhotoDome;
  114680. }(BABYLON.TransformNode));
  114681. BABYLON.PhotoDome = PhotoDome;
  114682. })(BABYLON || (BABYLON = {}));
  114683. //# sourceMappingURL=babylon.photoDome.js.map
  114684. var BABYLON;
  114685. (function (BABYLON) {
  114686. /** @hidden */
  114687. var _OcclusionDataStorage = /** @class */ (function () {
  114688. function _OcclusionDataStorage() {
  114689. /** @hidden */
  114690. this.occlusionInternalRetryCounter = 0;
  114691. /** @hidden */
  114692. this.isOcclusionQueryInProgress = false;
  114693. /** @hidden */
  114694. this.isOccluded = false;
  114695. /** @hidden */
  114696. this.occlusionRetryCount = -1;
  114697. /** @hidden */
  114698. this.occlusionType = BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE;
  114699. /** @hidden */
  114700. this.occlusionQueryAlgorithmType = BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  114701. }
  114702. return _OcclusionDataStorage;
  114703. }());
  114704. BABYLON.Engine.prototype.createQuery = function () {
  114705. return this._gl.createQuery();
  114706. };
  114707. BABYLON.Engine.prototype.deleteQuery = function (query) {
  114708. this._gl.deleteQuery(query);
  114709. return this;
  114710. };
  114711. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  114712. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  114713. };
  114714. BABYLON.Engine.prototype.getQueryResult = function (query) {
  114715. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  114716. };
  114717. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  114718. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  114719. this._gl.beginQuery(glAlgorithm, query);
  114720. return this;
  114721. };
  114722. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  114723. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  114724. this._gl.endQuery(glAlgorithm);
  114725. return this;
  114726. };
  114727. BABYLON.Engine.prototype._createTimeQuery = function () {
  114728. var timerQuery = this.getCaps().timerQuery;
  114729. if (timerQuery.createQueryEXT) {
  114730. return timerQuery.createQueryEXT();
  114731. }
  114732. return this.createQuery();
  114733. };
  114734. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  114735. var timerQuery = this.getCaps().timerQuery;
  114736. if (timerQuery.deleteQueryEXT) {
  114737. timerQuery.deleteQueryEXT(query);
  114738. return;
  114739. }
  114740. this.deleteQuery(query);
  114741. };
  114742. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  114743. var timerQuery = this.getCaps().timerQuery;
  114744. if (timerQuery.getQueryObjectEXT) {
  114745. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  114746. }
  114747. return this.getQueryResult(query);
  114748. };
  114749. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  114750. var timerQuery = this.getCaps().timerQuery;
  114751. if (timerQuery.getQueryObjectEXT) {
  114752. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  114753. }
  114754. return this.isQueryResultAvailable(query);
  114755. };
  114756. BABYLON.Engine.prototype.startTimeQuery = function () {
  114757. var caps = this.getCaps();
  114758. var timerQuery = caps.timerQuery;
  114759. if (!timerQuery) {
  114760. return null;
  114761. }
  114762. var token = new BABYLON._TimeToken();
  114763. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  114764. if (caps.canUseTimestampForTimerQuery) {
  114765. token._startTimeQuery = this._createTimeQuery();
  114766. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  114767. }
  114768. else {
  114769. if (this._currentNonTimestampToken) {
  114770. return this._currentNonTimestampToken;
  114771. }
  114772. token._timeElapsedQuery = this._createTimeQuery();
  114773. if (timerQuery.beginQueryEXT) {
  114774. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  114775. }
  114776. else {
  114777. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  114778. }
  114779. this._currentNonTimestampToken = token;
  114780. }
  114781. return token;
  114782. };
  114783. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  114784. var caps = this.getCaps();
  114785. var timerQuery = caps.timerQuery;
  114786. if (!timerQuery || !token) {
  114787. return -1;
  114788. }
  114789. if (caps.canUseTimestampForTimerQuery) {
  114790. if (!token._startTimeQuery) {
  114791. return -1;
  114792. }
  114793. if (!token._endTimeQuery) {
  114794. token._endTimeQuery = this._createTimeQuery();
  114795. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  114796. }
  114797. }
  114798. else if (!token._timeElapsedQueryEnded) {
  114799. if (!token._timeElapsedQuery) {
  114800. return -1;
  114801. }
  114802. if (timerQuery.endQueryEXT) {
  114803. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  114804. }
  114805. else {
  114806. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  114807. }
  114808. token._timeElapsedQueryEnded = true;
  114809. }
  114810. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  114811. var available = false;
  114812. if (token._endTimeQuery) {
  114813. available = this._getTimeQueryAvailability(token._endTimeQuery);
  114814. }
  114815. else if (token._timeElapsedQuery) {
  114816. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  114817. }
  114818. if (available && !disjoint) {
  114819. var result = 0;
  114820. if (caps.canUseTimestampForTimerQuery) {
  114821. if (!token._startTimeQuery || !token._endTimeQuery) {
  114822. return -1;
  114823. }
  114824. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  114825. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  114826. result = timeEnd - timeStart;
  114827. this._deleteTimeQuery(token._startTimeQuery);
  114828. this._deleteTimeQuery(token._endTimeQuery);
  114829. token._startTimeQuery = null;
  114830. token._endTimeQuery = null;
  114831. }
  114832. else {
  114833. if (!token._timeElapsedQuery) {
  114834. return -1;
  114835. }
  114836. result = this._getTimeQueryResult(token._timeElapsedQuery);
  114837. this._deleteTimeQuery(token._timeElapsedQuery);
  114838. token._timeElapsedQuery = null;
  114839. token._timeElapsedQueryEnded = false;
  114840. this._currentNonTimestampToken = null;
  114841. }
  114842. return result;
  114843. }
  114844. return -1;
  114845. };
  114846. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  114847. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  114848. };
  114849. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  114850. get: function () {
  114851. return this._occlusionDataStorage.isOcclusionQueryInProgress;
  114852. },
  114853. enumerable: false,
  114854. configurable: true
  114855. });
  114856. Object.defineProperty(BABYLON.AbstractMesh.prototype, "_occlusionDataStorage", {
  114857. get: function () {
  114858. if (!this.__occlusionDataStorage) {
  114859. this.__occlusionDataStorage = new _OcclusionDataStorage();
  114860. }
  114861. return this.__occlusionDataStorage;
  114862. },
  114863. enumerable: false,
  114864. configurable: true
  114865. });
  114866. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOccluded", {
  114867. get: function () {
  114868. return this._occlusionDataStorage.isOccluded;
  114869. },
  114870. set: function (value) {
  114871. this._occlusionDataStorage.isOccluded = value;
  114872. },
  114873. enumerable: true,
  114874. configurable: true
  114875. });
  114876. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionQueryAlgorithmType", {
  114877. get: function () {
  114878. return this._occlusionDataStorage.occlusionQueryAlgorithmType;
  114879. },
  114880. set: function (value) {
  114881. this._occlusionDataStorage.occlusionQueryAlgorithmType = value;
  114882. },
  114883. enumerable: true,
  114884. configurable: true
  114885. });
  114886. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionType", {
  114887. get: function () {
  114888. return this._occlusionDataStorage.occlusionType;
  114889. },
  114890. set: function (value) {
  114891. this._occlusionDataStorage.occlusionType = value;
  114892. },
  114893. enumerable: true,
  114894. configurable: true
  114895. });
  114896. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionRetryCount", {
  114897. get: function () {
  114898. return this._occlusionDataStorage.occlusionRetryCount;
  114899. },
  114900. set: function (value) {
  114901. this._occlusionDataStorage.occlusionRetryCount = value;
  114902. },
  114903. enumerable: true,
  114904. configurable: true
  114905. });
  114906. // We also need to update AbstractMesh as there is a portion of the code there
  114907. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  114908. var dataStorage = this._occlusionDataStorage;
  114909. if (dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  114910. dataStorage.isOccluded = false;
  114911. return false;
  114912. }
  114913. var engine = this.getEngine();
  114914. if (engine.webGLVersion < 2) {
  114915. dataStorage.isOccluded = false;
  114916. return false;
  114917. }
  114918. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  114919. dataStorage.isOccluded = false;
  114920. return false;
  114921. }
  114922. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  114923. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  114924. if (isOcclusionQueryAvailable) {
  114925. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  114926. dataStorage.isOcclusionQueryInProgress = false;
  114927. dataStorage.occlusionInternalRetryCounter = 0;
  114928. dataStorage.isOccluded = occlusionQueryResult === 1 ? false : true;
  114929. }
  114930. else {
  114931. dataStorage.occlusionInternalRetryCounter++;
  114932. if (dataStorage.occlusionRetryCount !== -1 && dataStorage.occlusionInternalRetryCounter > dataStorage.occlusionRetryCount) {
  114933. dataStorage.isOcclusionQueryInProgress = false;
  114934. dataStorage.occlusionInternalRetryCounter = 0;
  114935. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  114936. // if strict continue the last state of the object.
  114937. dataStorage.isOccluded = dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded;
  114938. }
  114939. else {
  114940. return false;
  114941. }
  114942. }
  114943. }
  114944. var scene = this.getScene();
  114945. if (scene.getBoundingBoxRenderer) {
  114946. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  114947. if (!this._occlusionQuery) {
  114948. this._occlusionQuery = engine.createQuery();
  114949. }
  114950. engine.beginOcclusionQuery(dataStorage.occlusionQueryAlgorithmType, this._occlusionQuery);
  114951. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  114952. engine.endOcclusionQuery(dataStorage.occlusionQueryAlgorithmType);
  114953. this._occlusionDataStorage.isOcclusionQueryInProgress = true;
  114954. }
  114955. return dataStorage.isOccluded;
  114956. };
  114957. })(BABYLON || (BABYLON = {}));
  114958. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  114959. var BABYLON;
  114960. (function (BABYLON) {
  114961. /**
  114962. * Class used to generate noise procedural textures
  114963. */
  114964. var NoiseProceduralTexture = /** @class */ (function (_super) {
  114965. __extends(NoiseProceduralTexture, _super);
  114966. /**
  114967. * Creates a new NoiseProceduralTexture
  114968. * @param name defines the name fo the texture
  114969. * @param size defines the size of the texture (default is 256)
  114970. * @param scene defines the hosting scene
  114971. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  114972. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  114973. */
  114974. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  114975. if (size === void 0) { size = 256; }
  114976. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  114977. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  114978. _this._time = 0;
  114979. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  114980. _this.brightness = 0.2;
  114981. /** Defines the number of octaves to process */
  114982. _this.octaves = 3;
  114983. /** Defines the level of persistence (0.8 by default) */
  114984. _this.persistence = 0.8;
  114985. /** Gets or sets animation speed factor (default is 1) */
  114986. _this.animationSpeedFactor = 1;
  114987. _this._updateShaderUniforms();
  114988. return _this;
  114989. }
  114990. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  114991. var scene = this.getScene();
  114992. if (!scene) {
  114993. return;
  114994. }
  114995. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  114996. this.setFloat("brightness", this.brightness);
  114997. this.setFloat("persistence", this.persistence);
  114998. this.setFloat("timeScale", this._time);
  114999. };
  115000. NoiseProceduralTexture.prototype._getDefines = function () {
  115001. return "#define OCTAVES " + (this.octaves | 0);
  115002. };
  115003. /** Generate the current state of the procedural texture */
  115004. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  115005. this._updateShaderUniforms();
  115006. _super.prototype.render.call(this, useCameraPostProcess);
  115007. };
  115008. /**
  115009. * Serializes this noise procedural texture
  115010. * @returns a serialized noise procedural texture object
  115011. */
  115012. NoiseProceduralTexture.prototype.serialize = function () {
  115013. var serializationObject = {};
  115014. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  115015. serializationObject.brightness = this.brightness;
  115016. serializationObject.octaves = this.octaves;
  115017. serializationObject.persistence = this.persistence;
  115018. serializationObject.animationSpeedFactor = this.animationSpeedFactor;
  115019. serializationObject.size = this.getSize().width;
  115020. serializationObject.generateMipMaps = this._generateMipMaps;
  115021. return serializationObject;
  115022. };
  115023. /**
  115024. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  115025. * @param parsedTexture defines parsed texture data
  115026. * @param scene defines the current scene
  115027. * @param rootUrl defines the root URL containing noise procedural texture information
  115028. * @returns a parsed NoiseProceduralTexture
  115029. */
  115030. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  115031. var texture = new NoiseProceduralTexture(parsedTexture.name, parsedTexture.size, scene, undefined, parsedTexture.generateMipMaps);
  115032. texture.brightness = parsedTexture.brightness;
  115033. texture.octaves = parsedTexture.octaves;
  115034. texture.persistence = parsedTexture.persistence;
  115035. texture.animationSpeedFactor = parsedTexture.animationSpeedFactor;
  115036. return texture;
  115037. };
  115038. return NoiseProceduralTexture;
  115039. }(BABYLON.ProceduralTexture));
  115040. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  115041. })(BABYLON || (BABYLON = {}));
  115042. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  115043. var __assign = (this && this.__assign) || function () {
  115044. __assign = Object.assign || function(t) {
  115045. for (var s, i = 1, n = arguments.length; i < n; i++) {
  115046. s = arguments[i];
  115047. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  115048. t[p] = s[p];
  115049. }
  115050. return t;
  115051. };
  115052. return __assign.apply(this, arguments);
  115053. };
  115054. var BABYLON;
  115055. (function (BABYLON) {
  115056. /**
  115057. * This can helps recording videos from BabylonJS.
  115058. * This is based on the available WebRTC functionalities of the browser.
  115059. *
  115060. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  115061. */
  115062. var VideoRecorder = /** @class */ (function () {
  115063. /**
  115064. * Create a new VideoCapture object which can help converting what you see in Babylon to
  115065. * a video file.
  115066. * @param engine Defines the BabylonJS Engine you wish to record
  115067. * @param options Defines options that can be used to customized the capture
  115068. */
  115069. function VideoRecorder(engine, options) {
  115070. if (options === void 0) { options = null; }
  115071. if (!VideoRecorder.IsSupported(engine)) {
  115072. throw "Your browser does not support recording so far.";
  115073. }
  115074. var canvas = engine.getRenderingCanvas();
  115075. if (!canvas) {
  115076. throw "The babylon engine must have a canvas to be recorded";
  115077. }
  115078. this._canvas = canvas;
  115079. this._canvas.isRecording = false;
  115080. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  115081. var stream = this._canvas.captureStream(this._options.fps);
  115082. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  115083. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  115084. this._mediaRecorder.onerror = this._handleError.bind(this);
  115085. this._mediaRecorder.onstop = this._handleStop.bind(this);
  115086. }
  115087. /**
  115088. * Returns wehther or not the VideoRecorder is available in your browser.
  115089. * @param engine Defines the Babylon Engine to check the support for
  115090. * @returns true if supported otherwise false
  115091. */
  115092. VideoRecorder.IsSupported = function (engine) {
  115093. var canvas = engine.getRenderingCanvas();
  115094. return (!!canvas && typeof canvas.captureStream === "function");
  115095. };
  115096. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  115097. /**
  115098. * True wether a recording is already in progress.
  115099. */
  115100. get: function () {
  115101. return !!this._canvas && this._canvas.isRecording;
  115102. },
  115103. enumerable: true,
  115104. configurable: true
  115105. });
  115106. /**
  115107. * Stops the current recording before the default capture timeout passed in the startRecording
  115108. * functions.
  115109. */
  115110. VideoRecorder.prototype.stopRecording = function () {
  115111. if (!this._canvas || !this._mediaRecorder) {
  115112. return;
  115113. }
  115114. if (!this.isRecording) {
  115115. return;
  115116. }
  115117. this._canvas.isRecording = false;
  115118. this._mediaRecorder.stop();
  115119. };
  115120. /**
  115121. * Starts recording the canvas for a max duration specified in parameters.
  115122. * @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.
  115123. * @param maxDuration Defines the maximum recording time in seconds.
  115124. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  115125. * @return a promise callback at the end of the recording with the video data in Blob.
  115126. */
  115127. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  115128. var _this = this;
  115129. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  115130. if (maxDuration === void 0) { maxDuration = 7; }
  115131. if (!this._canvas || !this._mediaRecorder) {
  115132. throw "Recorder has already been disposed";
  115133. }
  115134. if (this.isRecording) {
  115135. throw "Recording already in progress";
  115136. }
  115137. if (maxDuration > 0) {
  115138. setTimeout(function () {
  115139. _this.stopRecording();
  115140. }, maxDuration * 1000);
  115141. }
  115142. this._fileName = fileName;
  115143. this._recordedChunks = [];
  115144. this._resolve = null;
  115145. this._reject = null;
  115146. this._canvas.isRecording = true;
  115147. this._mediaRecorder.start(this._options.recordChunckSize);
  115148. return new Promise(function (resolve, reject) {
  115149. _this._resolve = resolve;
  115150. _this._reject = reject;
  115151. });
  115152. };
  115153. /**
  115154. * Releases internal resources used during the recording.
  115155. */
  115156. VideoRecorder.prototype.dispose = function () {
  115157. this._canvas = null;
  115158. this._mediaRecorder = null;
  115159. this._recordedChunks = [];
  115160. this._fileName = null;
  115161. this._resolve = null;
  115162. this._reject = null;
  115163. };
  115164. VideoRecorder.prototype._handleDataAvailable = function (event) {
  115165. if (event.data.size > 0) {
  115166. this._recordedChunks.push(event.data);
  115167. }
  115168. };
  115169. VideoRecorder.prototype._handleError = function (event) {
  115170. this.stopRecording();
  115171. if (this._reject) {
  115172. this._reject(event.error);
  115173. }
  115174. else {
  115175. throw new event.error;
  115176. }
  115177. };
  115178. VideoRecorder.prototype._handleStop = function () {
  115179. this.stopRecording();
  115180. var superBuffer = new Blob(this._recordedChunks);
  115181. if (this._resolve) {
  115182. this._resolve(superBuffer);
  115183. }
  115184. window.URL.createObjectURL(superBuffer);
  115185. if (this._fileName) {
  115186. BABYLON.Tools.Download(superBuffer, this._fileName);
  115187. }
  115188. };
  115189. VideoRecorder._defaultOptions = {
  115190. mimeType: "video/webm",
  115191. fps: 25,
  115192. recordChunckSize: 3000
  115193. };
  115194. return VideoRecorder;
  115195. }());
  115196. BABYLON.VideoRecorder = VideoRecorder;
  115197. })(BABYLON || (BABYLON = {}));
  115198. //# sourceMappingURL=babylon.videoRecorder.js.map
  115199. var BABYLON;
  115200. (function (BABYLON) {
  115201. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  115202. if (replace === void 0) { replace = false; }
  115203. // Dispose existing light in replace mode.
  115204. if (replace) {
  115205. if (this.lights) {
  115206. for (var i = 0; i < this.lights.length; i++) {
  115207. this.lights[i].dispose();
  115208. }
  115209. }
  115210. }
  115211. // Light
  115212. if (this.lights.length === 0) {
  115213. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  115214. }
  115215. };
  115216. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  115217. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  115218. if (replace === void 0) { replace = false; }
  115219. if (attachCameraControls === void 0) { attachCameraControls = false; }
  115220. // Dispose existing camera in replace mode.
  115221. if (replace) {
  115222. if (this.activeCamera) {
  115223. this.activeCamera.dispose();
  115224. this.activeCamera = null;
  115225. }
  115226. }
  115227. // Camera
  115228. if (!this.activeCamera) {
  115229. var worldExtends = this.getWorldExtends();
  115230. var worldSize = worldExtends.max.subtract(worldExtends.min);
  115231. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  115232. var camera;
  115233. var radius = worldSize.length() * 1.5;
  115234. // empty scene scenario!
  115235. if (!isFinite(radius)) {
  115236. radius = 1;
  115237. worldCenter.copyFromFloats(0, 0, 0);
  115238. }
  115239. if (createArcRotateCamera) {
  115240. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  115241. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  115242. arcRotateCamera.wheelPrecision = 100 / radius;
  115243. camera = arcRotateCamera;
  115244. }
  115245. else {
  115246. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  115247. freeCamera.setTarget(worldCenter);
  115248. camera = freeCamera;
  115249. }
  115250. camera.minZ = radius * 0.01;
  115251. camera.maxZ = radius * 1000;
  115252. camera.speed = radius * 0.2;
  115253. this.activeCamera = camera;
  115254. var canvas = this.getEngine().getRenderingCanvas();
  115255. if (attachCameraControls && canvas) {
  115256. camera.attachControl(canvas);
  115257. }
  115258. }
  115259. };
  115260. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  115261. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  115262. if (replace === void 0) { replace = false; }
  115263. if (attachCameraControls === void 0) { attachCameraControls = false; }
  115264. this.createDefaultLight(replace);
  115265. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  115266. };
  115267. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  115268. if (pbr === void 0) { pbr = false; }
  115269. if (scale === void 0) { scale = 1000; }
  115270. if (blur === void 0) { blur = 0; }
  115271. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  115272. if (!environmentTexture) {
  115273. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  115274. return null;
  115275. }
  115276. if (setGlobalEnvTexture) {
  115277. if (environmentTexture) {
  115278. this.environmentTexture = environmentTexture;
  115279. }
  115280. }
  115281. // Skybox
  115282. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  115283. if (pbr) {
  115284. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  115285. hdrSkyboxMaterial.backFaceCulling = false;
  115286. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  115287. if (hdrSkyboxMaterial.reflectionTexture) {
  115288. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  115289. }
  115290. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  115291. hdrSkyboxMaterial.disableLighting = true;
  115292. hdrSkyboxMaterial.twoSidedLighting = true;
  115293. hdrSkybox.infiniteDistance = true;
  115294. hdrSkybox.material = hdrSkyboxMaterial;
  115295. }
  115296. else {
  115297. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  115298. skyboxMaterial.backFaceCulling = false;
  115299. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  115300. if (skyboxMaterial.reflectionTexture) {
  115301. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  115302. }
  115303. skyboxMaterial.disableLighting = true;
  115304. hdrSkybox.infiniteDistance = true;
  115305. hdrSkybox.material = skyboxMaterial;
  115306. }
  115307. return hdrSkybox;
  115308. };
  115309. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  115310. if (BABYLON.EnvironmentHelper) {
  115311. return new BABYLON.EnvironmentHelper(options, this);
  115312. }
  115313. return null;
  115314. };
  115315. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  115316. if (webVROptions === void 0) { webVROptions = {}; }
  115317. return new BABYLON.VRExperienceHelper(this, webVROptions);
  115318. };
  115319. })(BABYLON || (BABYLON = {}));
  115320. //# sourceMappingURL=babylon.sceneHelpers.js.map
  115321. 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 BILLBOARDSTRETCHED\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}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\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#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,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\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\n#include<instancesVertex>\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\n#ifdef BILLBOARDSTRETCHED\nin vec3 direction;\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}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\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#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,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(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"};
  115322. 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};"};
  115323. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  115324. globalObject["BABYLON"] = BABYLON;
  115325. //backwards compatibility
  115326. if(typeof earcut !== 'undefined') {
  115327. globalObject["Earcut"] = {
  115328. earcut: earcut
  115329. };
  115330. }
  115331. return BABYLON;
  115332. });